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
|
|---|---|---|---|---|---|
b041e23f3d1b00170d5155dbfb53073204a14e0c
| 1,385
|
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FancyBarcodes {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String barcodeRegex = "(@#+)(?<barcode>[A-Z][A-Za-z\\d]{4,}[A-Z])(@#+)";
Pattern barcodePattern = Pattern.compile(barcodeRegex);
String digitsRegex = "\\d";
Pattern digitsPattern = Pattern.compile(digitsRegex);
for (int i = 0; i < n; i++) {
String string = scan.nextLine();
Matcher barcodeMatcher = barcodePattern.matcher(string);
if (barcodeMatcher.find()) {
String barcode = barcodeMatcher.group("barcode");
Matcher digitsMatcher = digitsPattern.matcher(barcode);
StringBuilder sb = new StringBuilder();
while (digitsMatcher.find()) {
sb.append(digitsMatcher.group());
}
if (sb.length() == 0) {
System.out.println("Product group: 00");
} else {
System.out.println(String.format("Product group: %s", sb));
}
} else {
System.out.println("Invalid barcode");
}
}
}
}
| 36.447368
| 81
| 0.5213
|
28bf4a370cbe0aa2ddd312ef7152c318c8c1acd6
| 1,509
|
package com.brentonbostick.capsloc;
import com.brentonbostick.capsloc.math.Point;
import com.brentonbostick.capsloc.ui.InputEvent;
import com.brentonbostick.capsloc.ui.paint.RenderingContext;
public abstract class Tool {
public void qKey() {
}
public void wKey() {
}
public void aKey() {
}
public void sKey() {
}
public void dKey() {
}
public void fKey() {
}
public void gKey() {
}
public void hKey() {
}
public void insertKey() {
}
public void d1Key() {
}
public void d2Key() {
}
public void d3Key() {
}
public void plusKey() {
}
public void minusKey() {
}
public void upKey() {
}
public void downKey() {
}
public void escKey() {
}
public void deleteKey() {
}
public void ctrlSKey() {
}
public void ctrlOKey() {
}
public void enterKey() {
}
/**
* in panel coords
*/
public void pressed(InputEvent ev) {
}
/**
* in panel coords
*/
public void released(InputEvent ev) {
}
/**
* in panel coords
*/
public void dragged(InputEvent ev) {
}
/**
* in panel coords
*/
public void moved(InputEvent ev) {
}
/**
* in panel coords
*/
public void clicked(InputEvent ev) {
}
/**
* in panel coords
*/
public void canceled(InputEvent ev) {
}
public Point p;
public abstract void setPoint(Point p);
public Point getPoint() {
return p;
}
public abstract void paint_panel(RenderingContext ctxt);
}
| 10.626761
| 60
| 0.590457
|
7a75aebfbd9eefbcca1776feb5cbb2885f68bb23
| 4,413
|
package io.github.mike10004.containment.lifecycle;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class LifecycleStackTest {
@Test
public void builder_toSequence() {
LifecycleStage<Void, TypeA> stage1 = stage(x -> new TypeA());
LifecycleStage<TypeA, TypeB> stage2 = stage(x -> new TypeB());
LifecycleStage<TypeB, TypeC> stage3 = stage(x -> new TypeC());
Lifecycle<TypeC> lifecycle = LifecycleStack.startingAt(stage1)
.andThen(stage2)
.andThen(stage3)
.toSequence();
LifecycleStack<TypeC> stack = (LifecycleStack<TypeC>) lifecycle;
assertEquals("stage sequence", Arrays.asList(stage1, stage2, stage3), stack.getStages());
}
private static final class TypeA {}
private static final class TypeB {}
private static final class TypeC {}
private static <R, P> LifecycleStage<R, P> stage(Function<R, P> commissioner) {
return stage(commissioner, ()->{});
}
private static <R, P> LifecycleStage<R, P> stage(Function<R, P> commissioner, Runnable decommissioner) {
return new LifecycleStage<R, P>() {
@Override
public P commission(R requirement) throws Exception {
return commissioner.apply(requirement);
}
@Override
public void decommission() {
}
};
}
private static class IntStage implements LifecycleStage<Integer, Integer> {
private final List<Integer> collection;
private Integer value;
public IntStage(List<Integer> collection) {
this.collection = collection;
}
@Override
public Integer commission(Integer requirement) {
value = requirement.intValue() + 1;
collection.add(value);
return value;
}
@Override
public void decommission() {
collection.add(value);
}
}
private static class FirstIntStage implements Lifecycle<Integer> {
@Override
public Integer commission() {
return 0;
}
@Override
public void decommission() {
}
}
@Test
public void testExecute() throws Exception {
List<Integer> sequence = Collections.synchronizedList(new ArrayList<>());
Lifecycle<Integer> stack = LifecycleStack.startingAt(new FirstIntStage())
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.toSequence();
Integer commissioned = stack.commission();
assertEquals("commissioned", 5, commissioned.intValue());
assertEquals("sequence", Arrays.asList(1, 2, 3, 4, 5), sequence);
stack.decommission();
assertEquals("sequence", Arrays.asList(1, 2, 3, 4, 5, 5, 4, 3, 2, 1), sequence);
}
private static class IntStageCommissionException extends RuntimeException {}
@Test
public void testExecute_interrupted() throws Exception {
List<Integer> sequence = Collections.synchronizedList(new ArrayList<>());
Lifecycle<Integer> stack = LifecycleStack.startingAt(new FirstIntStage())
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence) {
@Override
public Integer commission(Integer requirement) {
throw new IntStageCommissionException();
}
})
.andThen(new IntStage(sequence))
.andThen(new IntStage(sequence))
.toSequence();
try {
stack.commission();
fail("should have thrown LifecycleStageStackCommissionException");
} catch (LifecycleStackCommissionException e) {
assertTrue(e.getCause() instanceof IntStageCommissionException);
}
assertEquals("sequence", Arrays.asList(1, 2, 2, 1), sequence);
}
}
| 34.476563
| 108
| 0.609336
|
a45057cfe5dbdc3d42de5d9caf7212bad9bba57e
| 5,831
|
package org.apache.ofbiz.shipment.shipment;
import lombok.experimental.FieldNameConstants;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.apache.ofbiz.entity.GenericValue;
import java.util.List;
import java.util.ArrayList;
/**
* Shipment Cost Estimate
*/
@FieldNameConstants
public class ShipmentCostEstimate implements Serializable {
public static final long serialVersionUID = 4814167936380244992L;
public static final String NAME = "ShipmentCostEstimate";
/**
* Shipment Cost Estimate Id
*/
@Getter
@Setter
private String shipmentCostEstimateId;
/**
* Shipment Method Type Id
*/
@Getter
@Setter
private String shipmentMethodTypeId;
/**
* Carrier Party Id
*/
@Getter
@Setter
private String carrierPartyId;
/**
* Carrier Role Type Id
*/
@Getter
@Setter
private String carrierRoleTypeId;
/**
* Product Store Ship Meth Id
*/
@Getter
@Setter
private String productStoreShipMethId;
/**
* Product Store Id
*/
@Getter
@Setter
private String productStoreId;
/**
* Party Id
*/
@Getter
@Setter
private String partyId;
/**
* Role Type Id
*/
@Getter
@Setter
private String roleTypeId;
/**
* Geo Id To
*/
@Getter
@Setter
private String geoIdTo;
/**
* Geo Id From
*/
@Getter
@Setter
private String geoIdFrom;
/**
* Weight Break Id
*/
@Getter
@Setter
private String weightBreakId;
/**
* Weight Uom Id
*/
@Getter
@Setter
private String weightUomId;
/**
* Weight Unit Price
*/
@Getter
@Setter
private BigDecimal weightUnitPrice;
/**
* Quantity Break Id
*/
@Getter
@Setter
private String quantityBreakId;
/**
* Quantity Uom Id
*/
@Getter
@Setter
private String quantityUomId;
/**
* Quantity Unit Price
*/
@Getter
@Setter
private BigDecimal quantityUnitPrice;
/**
* Price Break Id
*/
@Getter
@Setter
private String priceBreakId;
/**
* Price Uom Id
*/
@Getter
@Setter
private String priceUomId;
/**
* Price Unit Price
*/
@Getter
@Setter
private BigDecimal priceUnitPrice;
/**
* Order Flat Price
*/
@Getter
@Setter
private BigDecimal orderFlatPrice;
/**
* Order Price Percent
*/
@Getter
@Setter
private BigDecimal orderPricePercent;
/**
* Order Item Flat Price
*/
@Getter
@Setter
private BigDecimal orderItemFlatPrice;
/**
* Shipping Price Percent
*/
@Getter
@Setter
private BigDecimal shippingPricePercent;
/**
* Product Feature Group Id
*/
@Getter
@Setter
private String productFeatureGroupId;
/**
* Oversize Unit
*/
@Getter
@Setter
private BigDecimal oversizeUnit;
/**
* Oversize Price
*/
@Getter
@Setter
private BigDecimal oversizePrice;
/**
* Feature Percent
*/
@Getter
@Setter
private BigDecimal featurePercent;
/**
* Feature Price
*/
@Getter
@Setter
private BigDecimal featurePrice;
/**
* Last Updated Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedStamp;
/**
* Last Updated Tx Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedTxStamp;
/**
* Created Stamp
*/
@Getter
@Setter
private Timestamp createdStamp;
/**
* Created Tx Stamp
*/
@Getter
@Setter
private Timestamp createdTxStamp;
public ShipmentCostEstimate(GenericValue value) {
shipmentCostEstimateId = (String) value
.get(FIELD_SHIPMENT_COST_ESTIMATE_ID);
shipmentMethodTypeId = (String) value
.get(FIELD_SHIPMENT_METHOD_TYPE_ID);
carrierPartyId = (String) value.get(FIELD_CARRIER_PARTY_ID);
carrierRoleTypeId = (String) value.get(FIELD_CARRIER_ROLE_TYPE_ID);
productStoreShipMethId = (String) value
.get(FIELD_PRODUCT_STORE_SHIP_METH_ID);
productStoreId = (String) value.get(FIELD_PRODUCT_STORE_ID);
partyId = (String) value.get(FIELD_PARTY_ID);
roleTypeId = (String) value.get(FIELD_ROLE_TYPE_ID);
geoIdTo = (String) value.get(FIELD_GEO_ID_TO);
geoIdFrom = (String) value.get(FIELD_GEO_ID_FROM);
weightBreakId = (String) value.get(FIELD_WEIGHT_BREAK_ID);
weightUomId = (String) value.get(FIELD_WEIGHT_UOM_ID);
weightUnitPrice = (BigDecimal) value.get(FIELD_WEIGHT_UNIT_PRICE);
quantityBreakId = (String) value.get(FIELD_QUANTITY_BREAK_ID);
quantityUomId = (String) value.get(FIELD_QUANTITY_UOM_ID);
quantityUnitPrice = (BigDecimal) value.get(FIELD_QUANTITY_UNIT_PRICE);
priceBreakId = (String) value.get(FIELD_PRICE_BREAK_ID);
priceUomId = (String) value.get(FIELD_PRICE_UOM_ID);
priceUnitPrice = (BigDecimal) value.get(FIELD_PRICE_UNIT_PRICE);
orderFlatPrice = (BigDecimal) value.get(FIELD_ORDER_FLAT_PRICE);
orderPricePercent = (BigDecimal) value.get(FIELD_ORDER_PRICE_PERCENT);
orderItemFlatPrice = (BigDecimal) value
.get(FIELD_ORDER_ITEM_FLAT_PRICE);
shippingPricePercent = (BigDecimal) value
.get(FIELD_SHIPPING_PRICE_PERCENT);
productFeatureGroupId = (String) value
.get(FIELD_PRODUCT_FEATURE_GROUP_ID);
oversizeUnit = (BigDecimal) value.get(FIELD_OVERSIZE_UNIT);
oversizePrice = (BigDecimal) value.get(FIELD_OVERSIZE_PRICE);
featurePercent = (BigDecimal) value.get(FIELD_FEATURE_PERCENT);
featurePrice = (BigDecimal) value.get(FIELD_FEATURE_PRICE);
lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP);
lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP);
createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP);
createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP);
}
public static ShipmentCostEstimate fromValue(
org.apache.ofbiz.entity.GenericValue value) {
return new ShipmentCostEstimate(value);
}
public static List<ShipmentCostEstimate> fromValues(
List<GenericValue> values) {
List<ShipmentCostEstimate> entities = new ArrayList<>();
for (GenericValue value : values) {
entities.add(new ShipmentCostEstimate(value));
}
return entities;
}
}
| 21.757463
| 74
| 0.73315
|
14171ff40028e549cabf37584efb75681055d407
| 922
|
/**
* Copyright (C) 2014 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.integration.adapter;
import net.finmath.time.daycount.DayCountConvention_UNKNOWN;
/**
* An adapter for {@link net.finmath.time.daycount.DayCountConvention_UNKNOWN} that allows use of the named instance
* factory.
*/
@FinmathDayCountType(name = "Unknown")
public final class UnknownFinmathDayCount extends FinmathDayCount {
/**
* Creates an instance of this adapter with name "Unknown" and implementation {@link DayCountConvention_UNKNOWN}.
*/
public UnknownFinmathDayCount() {
super("Unknown", new DayCountConvention_UNKNOWN());
}
/**
* Creates an instance that wraps {@link DayCountConvention_UNKNOWN}.
* @param name the name of the convention, not null
*/
public UnknownFinmathDayCount(final String name) {
super(name, new DayCountConvention_UNKNOWN());
}
}
| 30.733333
| 116
| 0.745119
|
e5450579dbebae36a58d0f240a56866529654046
| 2,348
|
/*
* Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.tests.control.xmlconfig;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import java.util.UUID;
import com.arjuna.databroker.data.DataFlow;
import com.arjuna.databroker.data.DataProvider;
import com.arjuna.databroker.data.DataSource;
public class Dummy01DataSource extends TimerTask implements DataSource
{
public Dummy01DataSource(DataFlow dataFlow, String name, Map<String, String> properties)
{
_dataFlow = dataFlow;
_name = name;
_properties = properties;
_dataProvider = new DummyDataProvider<String>(this);
}
@Override
public DataFlow getDataFlow()
{
return _dataFlow;
}
@Override
public void setDataFlow(DataFlow dataFlow)
{
_dataFlow = dataFlow;
}
@Override
public String getName()
{
return _name;
}
@Override
public void setName(String name)
{
_name = name;
}
@Override
public Map<String, String> getProperties()
{
return Collections.unmodifiableMap(_properties);
}
@Override
public void run()
{
String data = UUID.randomUUID().toString();
System.out.println("Source: [" + data + "]");
_dataProvider.produce(data);
}
@Override
public void setProperties(Map<String, String> properties)
{
_properties = properties;
}
@Override
public Collection<Class<?>> getDataProviderDataClasses()
{
Set<Class<?>> dataProviderDataClasses = new HashSet<Class<?>>();
dataProviderDataClasses.add(String.class);
return dataProviderDataClasses;
}
@Override
@SuppressWarnings("unchecked")
public <T> DataProvider<T> getDataProvider(Class<T> dataClass)
{
if (dataClass.equals(String.class))
return (DataProvider<T>) _dataProvider;
else
return null;
}
private DataFlow _dataFlow;
private String _name;
private Map<String, String> _properties;
private DummyDataProvider<String> _dataProvider;
}
| 24.206186
| 107
| 0.647359
|
6d9141991bc4aa1d322df962223f4652ee992271
| 115
|
package com.hlbk.game.world.monsters;
public interface Monster {
String getName();
int getExperience();
}
| 16.428571
| 37
| 0.713043
|
1a3394a4166e96100153b974f9ed287c42458d15
| 3,310
|
/**
* 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.lens.cli.commands;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.ws.rs.core.Response;
import org.apache.lens.cli.commands.annotations.UserDocumentation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
/**
* The Class LensLogResourceCommands.
* SUSPEND CHECKSTYLE CHECK InnerAssignmentCheck
*/
@Component
@UserDocumentation(title = "Commands for Accessing Logs",
description = "This section provides commands for fetching logs under LENS_LOG_DIR.")
public class LensLogResourceCommands extends BaseLensCommand {
@CliCommand(value = "show logs",
help = "show logs for the given handle <log_handle>. Handle can either be a query handle or request id. "
+ LensQueryCommands.DEFAULT_QUERY_HANDLE_DESCRIPTION + " "
+ "You can optionally provide a location to save the logs as <save_location>")
public String getLogs(
@CliOption(key = {"", "log_handle"}, mandatory = false, help = "<log_handle>")
String logFile, @CliOption(key = {"save_location"}, mandatory = false, help = "<save_location>") String location) {
try {
logFile = getOrDefaultQueryHandleString(logFile);
Response response = getClient().getLogs(logFile);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
if (StringUtils.isBlank(location)) {
OutputStream outStream = new PrintStream(System.out, true, "UTF-8");
try (InputStream stream = response.readEntity(InputStream.class)) {
IOUtils.copy(stream, outStream);
return "printed complete log content";
}
} else {
String existingDirectoryLocation = getValidPath(new File(location), true, true);
location = getValidPath(new File(existingDirectoryLocation + File.separator + logFile), false, false);
try (InputStream stream = response.readEntity(InputStream.class);
FileOutputStream outStream = new FileOutputStream(new File(location))) {
IOUtils.copy(stream, outStream);
return "Saved to " + location;
}
}
} else {
return response.toString();
}
} catch (Throwable t) {
return t.getMessage();
}
}
}
| 40.864198
| 119
| 0.714199
|
f0d0a0943c7de6d6b9175cdffdc5c72f5cc851f4
| 4,036
|
package com.fuel.consumption;
import com.fuel.consumption.api.request.FuelReportPostRequest;
import com.fuel.consumption.api.dto.ExpenseReportDto;
import com.fuel.consumption.model.entity.FuelConsumption;
import com.fuel.consumption.model.repository.FuelConsumptionRepository;
import com.fuel.consumption.util.BigDecimalUtil;
import com.fuel.consumption.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Vahap Gencdal
* @email avahap19@gmail.com
*/
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@ActiveProfiles("logback-test")
@Slf4j
public class FuelConsumptionRepositoryTest {
@Autowired
private FuelConsumptionRepository fuelConsumptionRepository;
public void readJson(String repositoryFunctionName) throws IOException {
List<FuelReportPostRequest> fuelConsumptionDtoList = JsonUtil.getJsonListFromFile("file:src/test/resources/test-data/" + repositoryFunctionName + ".json");
List<FuelConsumption> fuelConsumptionList = fuelConsumptionDtoList.stream().map(FuelReportPostRequest::toEntity).collect(Collectors.toList());
fuelConsumptionRepository.saveAll(fuelConsumptionList);
}
@AfterEach
public void afterEach() {
fuelConsumptionRepository.deleteAll();
}
@Test
public void findAllTotalSpentAmountOfMoney_Success_Case() throws IOException {
readJson("find_all_total_spent_amount_of_money");
List<ExpenseReportDto> expenseReportDtoList = fuelConsumptionRepository.findExpenseReportByPeriod();
Assertions.assertEquals(1, expenseReportDtoList.size());
Assertions.assertEquals(10, expenseReportDtoList.get(0).getMonth());
}
@Test
public void findCategoriesWithConsultantCountByDriverId_Success_case() throws IOException {
readJson("find_all_total_spent_amount_of_money_by_driver");
List<ExpenseReportDto> expenseReportDtoList = fuelConsumptionRepository.findExpenseReportByPeriodByDriverId(123L);
Assertions.assertEquals(1, expenseReportDtoList.size());
Assertions.assertEquals(new BigDecimal("1.12").setScale(4, BigDecimal.ROUND_CEILING).stripTrailingZeros(), expenseReportDtoList.get(0).getFuelPrice());
Assertions.assertEquals(new BigDecimal("40.4").setScale(4, BigDecimal.ROUND_CEILING).stripTrailingZeros(), expenseReportDtoList.get(0).getFuelVolume());
Assertions.assertEquals(123L, expenseReportDtoList.get(0).getDriverId());
Assertions.assertEquals(12, expenseReportDtoList.get(0).getMonth());
}
@Test
public void findByDriverId_Success_case() throws IOException {
readJson("find_by_driver_id_repo_data");
List<FuelConsumption> fuelConsumptionList = fuelConsumptionRepository.findByDriverId(123L);
Assertions.assertEquals(1, fuelConsumptionList.size());
Assertions.assertEquals(new BigDecimal("1.12").setScale(BigDecimalUtil.SCALE, BigDecimalUtil.ROUNDING_MODE).stripTrailingZeros(), fuelConsumptionList.get(0).getFuelPrice().setScale(BigDecimalUtil.SCALE, BigDecimalUtil.ROUNDING_MODE).stripTrailingZeros());
Assertions.assertEquals(new BigDecimal("40.40").setScale(BigDecimalUtil.SCALE, BigDecimalUtil.ROUNDING_MODE).stripTrailingZeros(), fuelConsumptionList.get(0).getFuelVolume().setScale(BigDecimalUtil.SCALE, BigDecimalUtil.ROUNDING_MODE).stripTrailingZeros());
Assertions.assertEquals(123L, fuelConsumptionList.get(0).getDriverId());
Assertions.assertEquals(12, fuelConsumptionList.get(0).getConsumptionDate().getMonth().getValue());
}
}
| 43.397849
| 265
| 0.786918
|
75444012bb4d4930a6c87da8084d63b97437279c
| 14,650
|
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.docs.programming.client.http3;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http3.api.Session;
import org.eclipse.jetty.http3.api.Stream;
import org.eclipse.jetty.http3.client.HTTP3Client;
import org.eclipse.jetty.http3.frames.DataFrame;
import org.eclipse.jetty.http3.frames.HeadersFrame;
import org.eclipse.jetty.http3.internal.HTTP3ErrorCode;
import static java.lang.System.Logger.Level.INFO;
@SuppressWarnings("unused")
public class HTTP3ClientDocs
{
public void start() throws Exception
{
// tag::start[]
// Instantiate HTTP3Client.
HTTP3Client http3Client = new HTTP3Client();
// Configure HTTP3Client, for example:
http3Client.getHTTP3Configuration().setStreamIdleTimeout(15000);
// Start HTTP3Client.
http3Client.start();
// end::start[]
}
public void stop() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
// tag::stop[]
// Stop HTTP3Client.
http3Client.stop();
// end::stop[]
}
public void connect() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
// tag::connect[]
// Address of the server's port.
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
// Connect to the server, the CompletableFuture will be
// notified when the connection is succeeded (or failed).
CompletableFuture<Session.Client> sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {});
// Block to obtain the Session.
// Alternatively you can use the CompletableFuture APIs to avoid blocking.
Session session = sessionCF.get();
// end::connect[]
}
public void configure() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
// tag::configure[]
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
http3Client.connect(serverAddress, new Session.Client.Listener()
{
@Override
public Map<Long, Long> onPreface(Session session)
{
Map<Long, Long> configuration = new HashMap<>();
// Add here configuration settings.
return configuration;
}
});
// end::configure[]
}
public void newStream() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
// tag::newStream[]
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session.Client> sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {});
Session.Client session = sessionCF.get();
// Configure the request headers.
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}");
// The request metadata with method, URI and headers.
MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders);
// The HTTP/3 HEADERS frame, with endStream=true
// to signal that this request has no content.
HeadersFrame headersFrame = new HeadersFrame(request, true);
// Open a Stream by sending the HEADERS frame.
session.newRequest(headersFrame, new Stream.Client.Listener() {});
// end::newStream[]
}
public void newStreamWithData() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
// tag::newStreamWithData[]
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session.Client> sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {});
Session.Client session = sessionCF.get();
// Configure the request headers.
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.CONTENT_TYPE, "application/json");
// The request metadata with method, URI and headers.
MetaData.Request request = new MetaData.Request("POST", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders);
// The HTTP/3 HEADERS frame, with endStream=false to
// signal that there will be more frames in this stream.
HeadersFrame headersFrame = new HeadersFrame(request, false);
// Open a Stream by sending the HEADERS frame.
CompletableFuture<Stream> streamCF = session.newRequest(headersFrame, new Stream.Client.Listener() {});
// Block to obtain the Stream.
// Alternatively you can use the CompletableFuture APIs to avoid blocking.
Stream stream = streamCF.get();
// The request content, in two chunks.
String content1 = "{\"greet\": \"hello world\"}";
ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(content1);
String content2 = "{\"user\": \"jetty\"}";
ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(content2);
// Send the first DATA frame on the stream, with endStream=false
// to signal that there are more frames in this stream.
CompletableFuture<Stream> dataCF1 = stream.data(new DataFrame(buffer1, false));
// Only when the first chunk has been sent we can send the second,
// with endStream=true to signal that there are no more frames.
dataCF1.thenCompose(s -> s.data(new DataFrame(buffer2, true)));
// end::newStreamWithData[]
}
public void responseListener() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session.Client> sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {});
Session.Client session = sessionCF.get();
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}");
MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders);
HeadersFrame headersFrame = new HeadersFrame(request, true);
// tag::responseListener[]
// Open a Stream by sending the HEADERS frame.
session.newRequest(headersFrame, new Stream.Client.Listener()
{
@Override
public void onResponse(Stream.Client stream, HeadersFrame frame)
{
MetaData metaData = frame.getMetaData();
MetaData.Response response = (MetaData.Response)metaData;
System.getLogger("http3").log(INFO, "Received response {0}", response);
}
@Override
public void onDataAvailable(Stream.Client stream)
{
// Read a chunk of the content.
Stream.Data data = stream.readData();
if (data == null)
{
// No data available now, demand to be called back.
stream.demand();
}
else
{
// Process the content.
process(data.getByteBuffer());
// Notify the implementation that the content has been consumed.
data.complete();
if (!data.isLast())
{
// Demand to be called back.
stream.demand();
}
}
}
});
// end::responseListener[]
}
private void process(ByteBuffer byteBuffer)
{
}
public void reset() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session.Client> sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {});
Session.Client session = sessionCF.get();
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}");
MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders);
HeadersFrame headersFrame = new HeadersFrame(request, true);
// tag::reset[]
// Open a Stream by sending the HEADERS frame.
CompletableFuture<Stream> streamCF = session.newRequest(headersFrame, new Stream.Client.Listener()
{
@Override
public void onFailure(Stream.Client stream, long error, Throwable failure)
{
// The server reset this stream.
}
});
Stream stream = streamCF.get();
// Reset this stream (for example, the user closed the application).
stream.reset(HTTP3ErrorCode.REQUEST_CANCELLED_ERROR.code(), new ClosedChannelException());
// end::reset[]
}
// TODO: push not yet implemented in HTTP/3
/*
public void push() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session> sessionCF = http3Client.connect(serverAddress, new Session.Listener.Adapter());
Session session = sessionCF.get();
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}");
MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders);
HeadersFrame headersFrame = new HeadersFrame(request, null, true);
// tag::push[]
// Open a Stream by sending the HEADERS frame.
CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter()
{
@Override
public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame)
{
// The "request" the client would make for the pushed resource.
MetaData.Request pushedRequest = frame.getMetaData();
// The pushed "request" URI.
HttpURI pushedURI = pushedRequest.getURI();
// The pushed "request" headers.
HttpFields pushedRequestHeaders = pushedRequest.getFields();
// If needed, retrieve the primary stream that triggered the push.
Stream primaryStream = pushedStream.getSession().getStream(frame.getStreamId());
// Return a Stream.Listener to listen for the pushed "response" events.
return new Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Handle the pushed stream "response".
MetaData metaData = frame.getMetaData();
if (metaData.isResponse())
{
// The pushed "response" headers.
HttpFields pushedResponseHeaders = metaData.getFields();
}
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Handle the pushed stream "response" content.
// The pushed stream "response" content bytes.
ByteBuffer buffer = frame.getData();
// Consume the buffer and complete the callback.
callback.succeeded();
}
};
}
});
// end::push[]
}
public void pushReset() throws Exception
{
HTTP3Client http3Client = new HTTP3Client();
http3Client.start();
SocketAddress serverAddress = new InetSocketAddress("localhost", 8444);
CompletableFuture<Session> sessionCF = http3Client.connect(serverAddress, new Session.Listener.Adapter());
Session session = sessionCF.get();
HttpFields requestHeaders = HttpFields.build()
.put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}");
MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders);
HeadersFrame headersFrame = new HeadersFrame(request, null, true);
// tag::pushReset[]
// Open a Stream by sending the HEADERS frame.
CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter()
{
@Override
public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame)
{
// Reset the pushed stream to tell the server we are not interested.
pushedStream.reset(new ResetFrame(pushedStream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
// Not interested in listening to pushed response events.
return null;
}
});
// end::pushReset[]
}
*/
}
| 41.036415
| 144
| 0.616382
|
b2687a574a720d0a1728e0ee9c78d7ddece7fb13
| 1,316
|
package com.zhourui.leetcode;
import org.junit.Test;
import static org.junit.Assert.*;
import static java.lang.Math.*;
// 对于每个坐标,都计算出其左侧和右侧的最高点,
// 注意到这道题,每个柱之间没有空间,水就积在柱子之上,所以高度相减即为本x处能存的水
// 从idx=1处开始,因为0处肯定不能存水
// 2nd loop,
public class Lc0042_trapwater {
class Solution {
public int trap(int[] height) {
int length = height.length;
int[] left=new int[length];
int leftMax = 0;
for (int i=1;i<length;i++) {
if (leftMax < height[i-1]) {
leftMax = height[i-1];
}
left[i]=leftMax;
}
int[] right=new int[length];
int rightMax = 0;
for (int i=length-2;i>=0;i--) {
if (rightMax < height[i+1]) {
rightMax = height[i+1];
}
right[i]=rightMax;
}
int ans = 0;
for (int i=1;i<length-1;i++) {
int h = max(min(left[i],right[i]),height[i]);
ans += h - height[i];
}
return ans;
}
}
@Test
public void Lc0042Test() {
assertEquals(1,new Solution().trap(new int[]{3,1,2}));
assertEquals(6,new Solution().trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1}));
}
}
| 27.416667
| 80
| 0.474924
|
2d6595437a79ee9ee42d601334ba071bbed91acf
| 2,087
|
package main.domain.participant.reading;
import java.util.Collection;
import main.domain.participant.Participant;
import main.domain.participant.ParticipantRepository;
public class ReadParticipantsUseCase {
private final ParticipantRepository repository;
private final Collection<ParticipantSummary> response;
public ReadParticipantsUseCase(ParticipantRepository repository, Collection<ParticipantSummary> response) {
this.repository = repository;
this.response = response;
}
public void execute() {
for (Participant participant : repository.getAll())
response.add(makeParticipantSummary(participant));
}
private ParticipantSummary makeParticipantSummary(Participant participant) {
ParticipantSummary summary = new ParticipantSummary();
summary.id = participant.getId();
summary.name = participant.getName().toString();
summary.userId = participant.getUserId().toString();
summary.nametag = participant.getNametag().toString();
summary.nationality = participant.getNationality().toString();
summary.gender = participant.getGender().toString();
summary.education = participant.getEducation().toString();
summary.birth = participant.getBirth().toString();
summary.homeAddress = participant.getHomeAddress().toSummary();
summary.homePhone = participant.getHomePhone().toString();
summary.cellphone = participant.getCellphone().toString();
summary.professionId = participant.getProfessionId().toString();
summary.organization = participant.getOrganization().toString();
summary.department = participant.getDepartment().toString();
summary.role = participant.getRole().toString();
summary.workAddress = participant.getWorkAddress().toSummary();
summary.workPhone = participant.getWorkPhone().toString();
summary.workCellphone = participant.getWorkCellphone().toString();
summary.workEmail = participant.getWorkEmail().toString();
return summary;
}
}
| 45.369565
| 111
| 0.720172
|
2ae42adcd73ef99b6b81ce1d5369e70592a9d525
| 553
|
package uk.ac.derby.Tanq.Navigation3;
/** Abstract definition of an A* node. */
interface AStarNode {
/** Node-to-node cost. */
public abstract void setG(float newG);
/** Node-to-destination cost. */
public abstract void setH(float newH);
/** Barrier cost. */
public abstract void setT(float newT);
public abstract float getCost();
public abstract AStarNode getParent();
public abstract int compareTo(AStarNode o);
public abstract boolean equals(Object o);
public abstract boolean isTouching(AStarNode o);
}
| 22.12
| 50
| 0.694394
|
d90a01ab127a2f556ac1ab6e25e651c4e4bbe93f
| 4,314
|
/**
* Copyright 2018
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.sdb.controller;
import io.sdb.common.annotation.SysLog;
import io.sdb.common.exception.RRException;
import io.sdb.vo.ProductCategoryVO;
import io.sdb.common.utils.R;
import io.sdb.common.utils.TreeBuilder;
import io.sdb.model.ProductCategory;
import io.sdb.service.ProductCategoryService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/sys/productCategory")
public class SysProductCategoryController extends AbstractController {
@Autowired
private ProductCategoryService productCategoryService;
@ResponseBody
@GetMapping("/tree")
public R tree(){
List<ProductCategory> productCategoryList = productCategoryService.findAll();
List<ProductCategoryVO> productCategoryVOList = productCategoryList.stream().map(item -> {
ProductCategoryVO productCategoryVO = new ProductCategoryVO(item);
return productCategoryVO;
}).collect(Collectors.toList());
List<ProductCategoryVO> productCategoryVOTree = new TreeBuilder().buildTree(productCategoryVOList);
return R.ok().put("productCategroyTree", productCategoryVOTree);
}
/**
* 列表
*/
@ResponseBody
@GetMapping("/list")
public R list(){
List<ProductCategory> productCategoryList = productCategoryService.findAll();
for(ProductCategory p : productCategoryList){
ProductCategory productCategory = productCategoryService.findById(p.getParentId());
if(productCategory!=null){
p.setParentName(productCategory.getName());
}
}
return R.ok().put("productCategoryList", productCategoryList);
}
/**
* 分类信息
*/
@GetMapping("/info/{productCategoryId}")
// @RequiresPermissions("sys:productCategory:info")
public R info(@PathVariable("productCategoryId") Long productCategoryId){
ProductCategory productCategory = productCategoryService.findById(productCategoryId);
return R.ok().put("productCategory", productCategory);
}
/**
* 选择菜单(添加、修改菜单)
*/
@GetMapping("/select")
// @RequiresPermissions("sys:productCategory:select")
public R select(){
//查询列表数据
List<ProductCategory> productCategoryList = productCategoryService.queryListOrder();
//添加顶级菜单
/*ProductCategory root = new ProductCategory();
root.setId(null);
root.setName("一级菜单");
root.setParentId(-1L);
root.setOpen(true);
root.setOrder(100);
productCategoryList.add(0, root);*/
return R.ok().put("productCategoryList", productCategoryList);
}
/**
* 保存
*/
@SysLog("保存商品类目")
@PostMapping("/save")
// @RequiresPermissions("sys:productCategory:save")
public R save(@RequestBody ProductCategory productCategory){
//数据校验
verifyForm(productCategory);
productCategoryService.save(productCategory);
return R.ok();
}
/**
* 修改
*/
@SysLog("修改菜单")
@PostMapping("/update")
// @RequiresPermissions("sys:productCategory:update")
public R update(@RequestBody ProductCategory productCategory){
//数据校验
verifyForm(productCategory);
productCategoryService.update(productCategory);
return R.ok();
}
/**
* 删除
*/
@SysLog("删除菜单")
@PostMapping("/delete/{productCategoryId}")
// @RequiresPermissions("sys:productCategory:delete")
public R delete(@PathVariable("productCategoryId") long productCategoryId){
return productCategoryService.delete(productCategoryId);
}
/**
* 验证参数是否正确
*/
private void verifyForm(ProductCategory productCategory){
if(StringUtils.isBlank(productCategory.getName())){
throw new RRException("类目名称不能为空");
}
// if(productCategory.getParentId() == null){
// throw new RRException("上级类目不能为空");
// }
}
}
| 28.76
| 101
| 0.751043
|
079de51fa9606f564bd7608837e0fe0b2b3a9f44
| 7,914
|
package fall2018.csc2017.GameCenter.GameCenter.lobby;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import fall2018.csc2017.GameCenter.GameCenter.blocks.GridManager;
import fall2018.csc2017.GameCenter.GameCenter.slidingtiles.BoardManager;
/**
* Stores a user account's account information.
*/
public class UserAccount implements Serializable {
/**
* The user account's username.
*/
private String username;
/**
* The user account's password.
*/
private String password;
/**
* Map of Sliding Tiles games of user account.
* Keys: The names of the user account's past Sliding Tiles games.
* Values: The board manager of each game.
*/
private Map<String, BoardManager> slidingTilesGameNames;
/**
* Map of Snake games of user account.
* Keys: The names of the user account's past Snake games.
* Values: The saved data of each game.
*/
private Map<String, Object[]> snakeGameNames;
/**
* Map of Blocks games of user account.
* Keys: The names of the user account's past Blocks games.
* Values: The grid state of each game.
*/
private Map<String, GridManager> blocksGameNames;
/**
* Map of scores.
* Keys: The game levels.
* Values: The user account's scores for each game level.
*/
private Map<String, Integer> scores;
/**
* String Array of the game level names.
*/
public static final String[] gameLevels = {"Sliding Tiles 3x3", "Sliding Tiles 4x4",
"Sliding Tiles 5x5", "Snake Easy Mode", "Snake Hard Mode", "Blocks"};
/**
* An instance of a user account with a username, password, and a blank list of game names.
* Default top score for Sliding Tiles is 1000000, which displays as "None" on the scoreboard.
* Default top score for Snake and Blocks is 0, which displays as "None" on the scoreboard.
*
* @param username the username of the user account
* @param password the password of the user account
*/
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
this.slidingTilesGameNames = new HashMap<>();
this.snakeGameNames = new HashMap<>();
this.blocksGameNames = new HashMap<>();
this.scores = new HashMap<>();
// Set the default starting scores
for (int i = 0; i < gameLevels.length; i++) {
if (i < 3) {
this.scores.put(gameLevels[i], 1000000);
} else {
this.scores.put(gameLevels[i], 0);
}
}
}
/**
* Returns the username of the user account.
*
* @return the user account's username
*/
public String getUsername() {
return username;
}
/**
* Returns the password of the user account.
*
* @return the user account's password
*/
public String getPassword() {
return password;
}
/**
* Returns the top score of the specified game level for the user account.
*
* @param levelName name of the game's level as stored in the score map
* @return top score of specified game level
*/
public Integer getTopScore(String levelName) {
if (this.scores.containsKey(levelName)) {
return this.scores.get(levelName);
} else {
return null;
}
}
/**
* Sets the top score of the specified game level for the user account.
*
* @param levelName name of the game's level as stored in the score map
* @param newScore new top score of specified game level
*/
public void setTopScore(String levelName, Integer newScore) {
this.scores.replace(levelName, newScore);
}
/**
* Adds a new game name to this user account.
*
* @param newName a new game name added to the user account
* @param game the board manager of the new game
*/
public void addSlidingTilesGame(String newName, BoardManager game) {
this.slidingTilesGameNames.put(newName, game);
}
/**
* Get a game saved by the game name.
*
* @param gameName a game name saved to this user account
*/
public BoardManager getSlidingTilesGame(String gameName) {
if (this.slidingTilesGameNames.containsKey(gameName)) {
return this.slidingTilesGameNames.get(gameName);
} else {
return null;
}
}
/**
* Returns this user account's key set of saved Sliding Tiles game names.
*
* @return key set of this user account's saved Sliding Tiles game names
*/
public Set<String> getSlidingTilesGameNames() {
return slidingTilesGameNames.keySet();
}
/**
* Adds a new game name to this user account
*
* @param newName a new game name added to the user account
* @param savedData saved data of the new game
*/
public void addSnakeGame(String newName, Object[] savedData) {
this.snakeGameNames.put(newName, savedData);
}
/**
* Get a game saved by the game name.
*
* @param gameName a game name saved to the user account
* @return saved data of the game
*/
public Object[] getSnakeGame(String gameName) {
if (this.snakeGameNames.containsKey(gameName)) {
return this.snakeGameNames.get(gameName);
} else {
return null;
}
}
/**
* Returns this user account's key set of saved Snake game names.
*
* @return key set of this user account's saved Snake game names
*/
public Set<String> getSnakeGameNames() {
return snakeGameNames.keySet();
}
/**
* Adds a new game name to this user account
*
* @param newName a new game name added to the user account
* @param gridManager grid manager of the new game
*/
public void addBlocksGame(String newName, GridManager gridManager) {
this.blocksGameNames.put(newName, gridManager);
}
/**
* Get a game saved by the game name.
*
* @param gameName a game name saved to the user account
* @return grid manager of the game
*/
public GridManager getBlocksGame(String gameName) {
if (this.blocksGameNames.containsKey(gameName)) {
return this.blocksGameNames.get(gameName);
} else {
return null;
}
}
/**
* Returns this user account's key set of saved Blocks game names.
*
* @return key set of this user account's saved Blocks game names
*/
public Set<String> getBlocksGameNames() {
return blocksGameNames.keySet();
}
/**
* Returns whether Object o equals this UserAccount - only if username and password match.
*
* @param o Object to compare to
* @return true if UserAccounts are equal
*/
@Override
public boolean equals(Object o) {
boolean scoresMatch = true;
if ((o != null) && (this.getClass() == o.getClass())) {
for (String gameLevel : gameLevels) {
if (!this.getTopScore(gameLevel).equals(((UserAccount) o).getTopScore(gameLevel))) {
scoresMatch = false;
}
}
}
return ((o != null) && (this.getClass() == o.getClass()) &&
(this.getUsername().equals(((UserAccount) o).getUsername())) &&
(this.getPassword().equals(((UserAccount) o).getPassword())) &&
(this.getSlidingTilesGameNames().equals((((UserAccount) o).getSlidingTilesGameNames())))
&& (this.getSnakeGameNames().equals((((UserAccount) o).getSnakeGameNames())))
&& (this.getBlocksGameNames().equals((((UserAccount) o).getBlocksGameNames())))
&& scoresMatch);
}
}
| 31.656
| 104
| 0.611195
|
f152a91af711f2234c6739c15232914c2438b8dc
| 1,242
|
package andioopp.common.time;
import java.util.Objects;
/**
* Represents a moment in time emitted by a {@link Clock}.
*/
public class Time {
private final float time, deltaTime;
public Time(float time, float deltaTime) {
this.time = time;
this.deltaTime = deltaTime;
}
/**
* Returns time elapsed since the clock was started.
* @return the elapsed time in seconds
*/
public float getTime() {
return time;
}
/**
* Returns time elapsed since the last event emitted by a clock.
* @return the elapsed time in seconds
*/
public float getDeltaTime() {
return deltaTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Time time = (Time) o;
return Float.compare(time.time, this.time) == 0 && Float.compare(time.deltaTime, deltaTime) == 0;
}
@Override
public int hashCode() {
return Objects.hash(time, deltaTime);
}
@Override
public String toString() {
return "Time{" +
"time=" + time +
", deltaTime=" + deltaTime +
'}';
}
}
| 23
| 105
| 0.566023
|
2be4549e3212dcfbe96f89606110ce148a19cae0
| 21,311
|
/**
* 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.oozie.action;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.client.WorkflowAction;
import org.apache.oozie.client.WorkflowJob;
import org.apache.oozie.service.ConfigurationService;
import org.apache.oozie.util.ELEvaluator;
import org.apache.oozie.util.ParamChecker;
import org.apache.oozie.util.XLog;
import org.apache.oozie.service.HadoopAccessorException;
import org.apache.oozie.service.Services;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.LinkedHashMap;
/**
* Base action executor class. <p> All the action executors should extend this class.
*/
public abstract class ActionExecutor {
/**
* Configuration prefix for action executor (sub-classes) properties.
*/
public static final String CONF_PREFIX = "oozie.action.";
public static final String MAX_RETRIES = CONF_PREFIX + "retries.max";
public static final String ACTION_RETRY_INTERVAL = CONF_PREFIX + "retry.interval";
public static final String ACTION_RETRY_POLICY = CONF_PREFIX + "retry.policy";
/**
* Error code used by {@link #convertException} when there is not register error information for an exception.
*/
public static final String ERROR_OTHER = "OTHER";
public static enum RETRYPOLICY {
EXPONENTIAL, PERIODIC
}
private static class ErrorInfo {
ActionExecutorException.ErrorType errorType;
String errorCode;
Class<?> errorClass;
private ErrorInfo(ActionExecutorException.ErrorType errorType, String errorCode, Class<?> errorClass) {
this.errorType = errorType;
this.errorCode = errorCode;
this.errorClass = errorClass;
}
}
private static boolean initMode = false;
private static Map<String, Map<String, ErrorInfo>> ERROR_INFOS = new HashMap<String, Map<String, ErrorInfo>>();
/**
* Context information passed to the ActionExecutor methods.
*/
public interface Context {
/**
* Create the callback URL for the action.
*
* @param externalStatusVar variable for the caller to inject the external status.
* @return the callback URL.
*/
public String getCallbackUrl(String externalStatusVar);
/**
* Return a proto configuration for actions with auth properties already set.
*
* @return a proto configuration for actions with auth properties already set.
*/
public Configuration getProtoActionConf();
/**
* Return the workflow job.
*
* @return the workflow job.
*/
public WorkflowJob getWorkflow();
/**
* Return an ELEvaluator with the context injected.
*
* @return configured ELEvaluator.
*/
public ELEvaluator getELEvaluator();
/**
* Set a workflow action variable. <p> Convenience method that prefixes the variable name with the action name
* plus a '.'.
*
* @param name variable name.
* @param value variable value, <code>null</code> removes the variable.
*/
public void setVar(String name, String value);
/**
* Get a workflow action variable. <p> Convenience method that prefixes the variable name with the action name
* plus a '.'.
*
* @param name variable name.
* @return the variable value, <code>null</code> if not set.
*/
public String getVar(String name);
/**
* Set the action tracking information for an successfully started action.
*
* @param externalId the action external ID.
* @param trackerUri the action tracker URI.
* @param consoleUrl the action console URL.
*/
void setStartData(String externalId, String trackerUri, String consoleUrl);
/**
* Set the action execution completion information for an action. The action status is set to {@link
* org.apache.oozie.client.WorkflowAction.Status#DONE}
*
* @param externalStatus the action external end status.
* @param actionData the action data on completion, <code>null</code> if none.
*/
void setExecutionData(String externalStatus, Properties actionData);
/**
* Set execution statistics information for a particular action. The action status is set to {@link
* org.apache.oozie.client.WorkflowAction.Status#DONE}
*
* @param jsonStats the JSON string representation of the stats.
*/
void setExecutionStats(String jsonStats);
/**
* Set external child IDs for a particular action (Eg: pig). The action status is set to {@link
* org.apache.oozie.client.WorkflowAction.Status#DONE}
*
* @param externalChildIDs the external child IDs as a comma-delimited string.
*/
void setExternalChildIDs(String externalChildIDs);
/**
* Set the action end completion information for a completed action.
*
* @param status the action end status, it can be {@link org.apache.oozie.client.WorkflowAction.Status#OK} or
* {@link org.apache.oozie.client.WorkflowAction.Status#ERROR}.
* @param signalValue the action external end status.
*/
void setEndData(WorkflowAction.Status status, String signalValue);
/**
* Return if the executor invocation is a retry or not.
*
* @return if the executor invocation is a retry or not.
*/
boolean isRetry();
/**
* Sets the external status for the action in context.
*
* @param externalStatus the external status.
*/
void setExternalStatus(String externalStatus);
/**
* Get the Action Recovery ID.
*
* @return recovery ID.
*/
String getRecoveryId();
/*
* @return the path that will be used to store action specific data
* @throws IOException @throws URISyntaxException @throws HadoopAccessorException
*/
public Path getActionDir() throws HadoopAccessorException, IOException, URISyntaxException;
/**
* @return filesystem handle for the application deployment fs.
* @throws IOException
* @throws URISyntaxException
* @throws HadoopAccessorException
*/
public FileSystem getAppFileSystem() throws HadoopAccessorException, IOException, URISyntaxException;
public void setErrorInfo(String str, String exMsg);
}
/**
* Define the default inteval in seconds between retries.
*/
public static final long RETRY_INTERVAL = 60;
private String type;
private int maxRetries;
private long retryInterval;
private RETRYPOLICY retryPolicy;
/**
* Create an action executor with default retry parameters.
*
* @param type action executor type.
*/
protected ActionExecutor(String type) {
this(type, RETRY_INTERVAL);
}
/**
* Create an action executor.
*
* @param type action executor type.
* @param defaultRetryInterval retry interval, in seconds.
*/
protected ActionExecutor(String type, long defaultRetryInterval) {
this.type = ParamChecker.notEmpty(type, "type");
this.maxRetries = ConfigurationService.getInt(MAX_RETRIES);
int retryInterval = ConfigurationService.getInt(ACTION_RETRY_INTERVAL);
this.retryInterval = retryInterval > 0 ? retryInterval : defaultRetryInterval;
this.retryPolicy = getRetryPolicyFromConf();
}
private RETRYPOLICY getRetryPolicyFromConf() {
String retryPolicy = ConfigurationService.get(ACTION_RETRY_POLICY);
if (StringUtils.isBlank(retryPolicy)) {
return RETRYPOLICY.PERIODIC;
} else {
try {
return RETRYPOLICY.valueOf(retryPolicy.toUpperCase().trim());
} catch (IllegalArgumentException e) {
return RETRYPOLICY.PERIODIC;
}
}
}
/**
* Clear all init settings for all action types.
*/
public static void resetInitInfo() {
if (!initMode) {
throw new IllegalStateException("Error, action type info locked");
}
ERROR_INFOS.clear();
}
/**
* Enable action type initialization.
*/
public static void enableInit() {
initMode = true;
}
/**
* Disable action type initialization.
*/
public static void disableInit() {
initMode = false;
}
/**
* Invoked once at system initialization time. <p> It can be used to register error information for the expected
* exceptions. Exceptions should be register from subclasses to superclasses to ensure proper detection, same thing
* that it is done in a normal catch. <p> This method should invoke the {@link #registerError} method to register
* all its possible errors. <p> Subclasses overriding must invoke super.
*/
public void initActionType() {
XLog.getLog(getClass()).trace(" Init Action Type : [{0}]", getType());
ERROR_INFOS.put(getType(), new LinkedHashMap<String, ErrorInfo>());
}
/**
* Return the system ID, this ID is defined in Oozie configuration.
*
* @return the system ID.
*/
public String getOozieSystemId() {
return Services.get().getSystemId();
}
/**
* Return the runtime directory of the Oozie instance. <p> The directory is created under TMP and it is always a
* new directory per system initialization.
*
* @return the runtime directory of the Oozie instance.
*/
public String getOozieRuntimeDir() {
return Services.get().getRuntimeDir();
}
/**
* Return Oozie configuration. <p> This is useful for actions that need access to configuration properties.
*
* @return Oozie configuration.
*/
public Configuration getOozieConf() {
return Services.get().getConf();
}
/**
* Register error handling information for an exception.
*
* @param exClass excpetion class name (to work in case of a particular exception not being in the classpath, needed
* to be able to handle multiple version of Hadoop or other JARs used by executors with the same codebase).
* @param errorType error type for the exception.
* @param errorCode error code for the exception.
*/
protected void registerError(String exClass, ActionExecutorException.ErrorType errorType, String errorCode) {
if (!initMode) {
throw new IllegalStateException("Error, action type info locked");
}
try {
Class errorClass = Thread.currentThread().getContextClassLoader().loadClass(exClass);
Map<String, ErrorInfo> executorErrorInfo = ERROR_INFOS.get(getType());
executorErrorInfo.put(exClass, new ErrorInfo(errorType, errorCode, errorClass));
}
catch (ClassNotFoundException cnfe) {
XLog.getLog(getClass()).warn(
"Exception [{0}] not in classpath, ActionExecutor [{1}] will handle it as ERROR", exClass,
getType());
}
catch (java.lang.NoClassDefFoundError err) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
err.printStackTrace(new PrintStream(baos));
XLog.getLog(getClass()).warn(baos.toString());
}
}
/**
* Return the action executor type.
*
* @return the action executor type.
*/
public String getType() {
return type;
}
/**
* Return the maximum number of retries for the action executor.
*
* @return the maximum number of retries for the action executor.
*/
public int getMaxRetries() {
return maxRetries;
}
/**
* Set the maximum number of retries for the action executor.
*
* @param maxRetries the maximum number of retries.
*/
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
/**
* Return the retry policy for the action executor.
*
* @return the retry policy for the action executor.
*/
public RETRYPOLICY getRetryPolicy() {
return retryPolicy;
}
/**
* Sets the retry policy for the action executor.
*
* @param retryPolicy retry policy for the action executor.
*/
public void setRetryPolicy(RETRYPOLICY retryPolicy) {
this.retryPolicy = retryPolicy;
}
/**
* Return the retry interval for the action executor in seconds.
*
* @return the retry interval for the action executor in seconds.
*/
public long getRetryInterval() {
return retryInterval;
}
/**
* Sets the retry interval for the action executor.
*
* @param retryInterval retry interval in seconds.
*/
public void setRetryInterval(long retryInterval) {
this.retryInterval = retryInterval;
}
/**
* Utility method to handle exceptions in the {@link #start}, {@link #end}, {@link #kill} and {@link #check} methods
* <p> It uses the error registry to convert exceptions to {@link ActionExecutorException}s.
*
* @param ex exception to convert.
* @return ActionExecutorException converted exception.
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
protected ActionExecutorException convertException(Exception ex) {
if (ex instanceof ActionExecutorException) {
return (ActionExecutorException) ex;
}
ActionExecutorException aee = null;
// Check the cause of the exception first
if (ex.getCause() != null) {
aee = convertExceptionHelper(ex.getCause());
}
// If the cause isn't registered or doesn't exist, check the exception itself
if (aee == null) {
aee = convertExceptionHelper(ex);
// If the cause isn't registered either, then just create a new ActionExecutorException
if (aee == null) {
String exClass = ex.getClass().getName();
String errorCode = exClass.substring(exClass.lastIndexOf(".") + 1);
aee = new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, errorCode, "{0}", ex.getMessage(), ex);
}
}
return aee;
}
private ActionExecutorException convertExceptionHelper(Throwable ex) {
Map<String, ErrorInfo> executorErrorInfo = ERROR_INFOS.get(getType());
// Check if we have registered ex
ErrorInfo classErrorInfo = executorErrorInfo.get(ex.getClass().getName());
if (classErrorInfo != null) {
return new ActionExecutorException(classErrorInfo.errorType, classErrorInfo.errorCode, "{0}", ex.getMessage(), ex);
}
// Else, check if a parent class of ex is registered
else {
for (ErrorInfo errorInfo : executorErrorInfo.values()) {
if (errorInfo.errorClass.isInstance(ex)) {
return new ActionExecutorException(errorInfo.errorType, errorInfo.errorCode, "{0}", ex.getMessage(), ex);
}
}
}
return null;
}
/**
* Convenience method that return the signal for an Action based on the action status.
*
* @param status action status.
* @return the action signal.
*/
protected String getActionSignal(WorkflowAction.Status status) {
switch (status) {
case OK:
return "OK";
case ERROR:
case KILLED:
return "ERROR";
default:
throw new IllegalArgumentException("Action status for signal can only be OK or ERROR");
}
}
/**
* Return the path that will be used to store action specific data
*
* @param jobId Worfklow ID
* @param action Action
* @param key An Identifier
* @param temp temp directory flag
* @return A string that has the path
*/
protected String getActionDirPath(String jobId, WorkflowAction action, String key, boolean temp) {
String name = jobId + "/" + action.getName() + "--" + key;
if (temp) {
name += ".temp";
}
return getOozieSystemId() + "/" + name;
}
/**
* Return the path that will be used to store action specific data.
*
* @param jobId Workflow ID
* @param action Action
* @param key An identifier
* @param temp Temp directory flag
* @return Path to the directory
*/
public Path getActionDir(String jobId, WorkflowAction action, String key, boolean temp) {
return new Path(getActionDirPath(jobId, action, key, temp));
}
/**
* Start an action. <p> The {@link Context#setStartData} method must be called within this method. <p> If the
* action has completed, the {@link Context#setExecutionData} method must be called within this method.
*
* @param context executor context.
* @param action the action to start.
* @throws ActionExecutorException thrown if the action could not start.
*/
public abstract void start(Context context, WorkflowAction action) throws ActionExecutorException;
/**
* End an action after it has executed. <p> The {@link Context#setEndData} method must be called within this
* method.
*
* @param context executor context.
* @param action the action to end.
* @throws ActionExecutorException thrown if the action could not end.
*/
public abstract void end(Context context, WorkflowAction action) throws ActionExecutorException;
/**
* Check if an action has completed. This method must be implemented by Async Action Executors. <p> If the action
* has completed, the {@link Context#setExecutionData} method must be called within this method. <p> If the action
* has not completed, the {@link Context#setExternalStatus} method must be called within this method.
*
* @param context executor context.
* @param action the action to end.
* @throws ActionExecutorException thrown if the action could not be checked.
*/
public abstract void check(Context context, WorkflowAction action) throws ActionExecutorException;
/**
* Kill an action. <p> The {@link Context#setEndData} method must be called within this method.
*
* @param context executor context.
* @param action the action to kill.
* @throws ActionExecutorException thrown if the action could not be killed.
*/
public abstract void kill(Context context, WorkflowAction action) throws ActionExecutorException;
/**
* Return if the external status indicates that the action has completed.
*
* @param externalStatus external status to check.
* @return if the external status indicates that the action has completed.
*/
public abstract boolean isCompleted(String externalStatus);
/**
* Returns true if this action type requires a NameNode and JobTracker. These can either be specified directly in the action
* via <name-node> and <job-tracker>, from the fields in the global section, or from their default values. If
* false, Oozie won't ensure (i.e. won't throw an Exception if non-existant) that this action type has these values.
*
* @return true if a NameNode and JobTracker are required; false if not
*/
public boolean requiresNameNodeJobTracker() {
return false;
}
/**
* Returns true if this action type supports a Configuration and JobXML. In this case, Oozie will include the
* <configuration> and <job-xml> elements from the global section (if provided) with the action. If false, Oozie
* won't add these.
*
* @return true if the global section's Configuration and JobXML should be given; false if not
*/
public boolean supportsConfigurationJobXML() {
return false;
}
}
| 36.42906
| 130
| 0.647741
|
5e6a1f70be36cbe5af564141aca657509be056db
| 450
|
package com.hamonize.restApi.hamonikros.service.vo;
import java.sql.Date;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class RestHamonikrOsVO {
private Integer seq;
private String name;
private String gubun;
private String version;
private String status;
private Date reg_date;
private Date updt_date;
/* 페이징 */
private int firstRecordIndex;
private int recordCountPerPage;
}
| 15.517241
| 51
| 0.78
|
49410758230ad829b4ee1fc26101dd8f8a99c54b
| 2,299
|
/*******************************************************************************
* Copyright by Dr. Bianca Hoffmann, Ruman Gerst, Dr. Zoltán Cseresnyés and Prof. Dr. Marc Thilo Figge
*
* Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge
* https://www.leibniz-hki.de/en/applied-systems-biology.html
* HKI-Center for Systems Biology of Infection
* Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI)
* Adolf-Reichwein-Straße 23, 07745 Jena, Germany
*
* The project code is licensed under BSD 2-Clause.
* See the LICENSE file provided with the code for the full license.
******************************************************************************/
package org.hkijena.mcat.extension.datatypes;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import org.hkijena.mcat.api.MCATData;
import org.hkijena.mcat.api.MCATDocumentation;
/**
* Contains a derivation matrix
*/
@MCATDocumentation(name = "Derivative matrix")
public class DerivativeMatrixData implements MCATData {
private double[][] derivativeMatrix;
public DerivativeMatrixData(double[][] derivativeMatrix) {
super();
this.derivativeMatrix = derivativeMatrix;
}
public double[][] getDerivativeMatrix() {
return derivativeMatrix;
}
public void setDerivativeMatrix(double[][] derivativeMatrix) {
this.derivativeMatrix = derivativeMatrix;
}
@Override
public void saveTo(Path folder, Path fileName) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(folder.resolve(fileName).toString())));
for (int i = 0; i < derivativeMatrix.length; i++) {
String out = "";
double[] line = derivativeMatrix[i];
for (int j = 0; j < line.length; j++) {
out += j == 0 ? String.valueOf(line[j]) : ";" + String.valueOf(line[j]);
}
bw.write(out);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 33.808824
| 115
| 0.581122
|
61b718537e31633ae247d62dcf0ac029239b1629
| 2,805
|
/*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT 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 org.conqat.engine.model_clones.metrics;
import java.util.List;
import org.conqat.engine.core.core.AConQATKey;
import org.conqat.engine.core.core.AConQATProcessor;
import org.conqat.engine.model_clones.model.IDirectedEdge;
import org.conqat.engine.model_clones.model.INode;
/**
* {@ConQAT.Doc}
*
* @author hummelb
* @author $Author: deissenb $
* @version $Rev: 34252 $
* @levd.rating GREEN Hash: 0899F58497EB7C405934D46421AFFC87
*/
@AConQATProcessor(description = "Calculates the relative weight of the clone group, "
+ "which is defined as the average of weight/size over all clone instances.")
public class RelativeWeightModelCloneMetric extends
ModelCloneMetricProcessorBase {
/**
* We use the key annotation here, so the key becomes visible in ConQATDoc
* and cq.edit.
*/
@AConQATKey(description = "The key used for storing the metric.", type = "java.lang.Double")
public static final String KEY = "rel_weight";
/** The sum of weight/size. */
private double metricSum = 0;
/** The number of occurrences. */
private int occurrences = 0;
/** {@inheritDoc} */
@Override
protected void resetCounters() {
metricSum = 0;
occurrences = 0;
}
/** {@inheritDoc} */
@Override
public void addCloneInstance(List<INode> nodes, List<IDirectedEdge> edges) {
metricSum += getNodesWeight(nodes) / (double) nodes.size();
occurrences += 1;
}
/** {@inheritDoc} */
@Override
public double calculateMetricValue() {
return metricSum / occurrences;
}
/** {@inheritDoc} */
@Override
public String getName() {
return KEY;
}
}
| 36.428571
| 93
| 0.562567
|
28b0629a7282a72009ab0a282f5a9f535e2b2428
| 994
|
package com.data;
import com.data.common.AwesomeUtils;
import com.data.service.ZtreeService;
import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.SQLException;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FunctionTests {
@Test
public void justTest() throws Exception {
String params = "{\"url\":\"jdbc:mysql://139.129.67.219:3306/\",\"dbname\":\"zhstjj\",\"parameter\":\"?serverTimezone=UTC\",\"username\":\"zhsdevelop\",\"password\":\"southnet\",\"sql\":\"select * from channel\",\"commitTime\":\"2019-10-14 12:51\"}";
String s = ZtreeService.dealZtreeData(params);
System.out.println(s);
}
@Test
public void justAnotherTest() {
System.out.println(AwesomeUtils.getCurrentDate(1));
}
}
| 34.275862
| 258
| 0.717304
|
9946cf159edf6a30916ca661762d0a4a9f53d76e
| 668
|
package org.rlcommunity.rlviz.app.frames;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
@Override
public void handleAbout(ApplicationEvent event) {
GenericVizFrame.showAboutBox();
event.setHandled(true);
}
@Override
public void handleQuit(ApplicationEvent ae) {
ae.setHandled(true);
}
}
}
| 25.692308
| 57
| 0.667665
|
4e030bda8c4236a7dea17f21052be13971376e0b
| 3,543
|
package cnic.pip.impl;
import java.io.Serializable;
import com.google.common.base.Objects;
/**
*
* @author kaichao
*
* Parameters for PIP operation
* envelope of the area
*/
public abstract class EnvelopeExt implements Serializable{
private static final long serialVersionUID = -3032526397343688842L;
protected double x0,x1,y0,y1;
// points per degree
protected int ppd;
// tolerance precision
private static double tolerance = 1e-8;
protected static double roundingError = 1e-11;
protected long nx, nx0, nx1, ny0, ny1;
/**
*
* @param x0
* @param x1
* @param y0
* @param y1
* @param ppd resolution, points per degree
*/
public EnvelopeExt(double x0, double x1, double y0, double y1, int ppd) {
setParameter(x0,x1,y0,y1,ppd);
}
public EnvelopeExt(double x0, double x1, double y0, double y1) {
this(x0,x1,y0,y1,10);
}
public EnvelopeExt() {
this(-180,180,-90,90);
}
public static EnvelopeExt getInstance(String type){
if("esri".equals(type)){
return new EnvelopeExtEsri();
} else if("esri-v2".equals(type)){
return new EnvelopeExtEsri_v2();
} else if("jts".equals(type)){
return new EnvelopeExtJts();
} else {
return null;
}
}
public void setParameter(double x0, double x1, double y0, double y1, int ppd){
this.x0 = x0;
this.x1 = x1;
this.y0 = y0;
this.y1 = y1;
this.ppd = ppd;
nx1 = (int)Math.ceil((x1)*ppd)-1;
ny1 = (int)Math.ceil((y1)*ppd)-1;
nx0 = (int)Math.floor((x0)*ppd);
ny0 = (int)Math.floor((y0)*ppd);
nx = nx1 - nx0 + 1;
}
/**
* get indexes of 4 points
* @param x
* @param y
* @return
*/
public long[] getIndexes(double x, double y){
try {
idx[0] = getIndex(x - tolerance, y - tolerance);
idx[1] = getIndex(x - tolerance, y + tolerance);
idx[2] = getIndex(x + tolerance, y - tolerance);
idx[3] = getIndex(x + tolerance, y + tolerance);
} catch (OutOfRangeException ex) {
String msg = String.format("out of range:x=%s,y=%s",
Double.toString(x), Double.toString(y));
throw new OutOfRangeException(msg);
}
// delete duplicated elements
// int n = 4;
// for(int i=0;i<n-1;i++){
// for(int j=i+1;j<n;j++){
// if(idx[i] == idx[j]){
// for(int k=i+1;k<n;k++){
// idx[k-1] = idx[k];
// }
// n--,i--;
// break;
// }
// }
// }
// return Arrays.copyOf(idx, n);
if(idx[0] == idx[3] && idx[1] == idx[3] && idx[2] == idx[3] ){
return new long[]{idx[0]};
} else {
}
return idx;
}
private long[] idx = new long[4];
public long getIndex(double x, double y){
long ix = Math.round(x*ppd-0.5);
long iy = Math.round(y*ppd-0.5);
// long ix = mathFloor(x*ppd);
// long iy = mathFloor(y*ppd);
if(ix<nx0 || ix >= nx1 || iy<ny0 || iy>=ny1){
throw new OutOfRangeException();
}
return ix + iy * nx;
}
/*
* High performance version of Math.floor(d)
*/
public long mathFloor(double d){
if (d >= 0) { // positive number
return (long) d;
} else if ((long) d == d) { //negative integer
return (long) d;
} else {
return -((long) (-d) + 1);
}
}
public abstract long[][] makeBorderData(String wkt);
@Override
public String toString(){
return String.format("x0=%s, x1=%s, y0=%s, y1=%s, ppd=%d"
,Double.toString(x0),Double.toString(x1),Double.toString(y0),Double.toString(y1)
, ppd);
}
@Override
public boolean equals(Object o){
EnvelopeExt a = (EnvelopeExt) o;
return x0==a.x0 && x1==a.x1 && y0==a.y0 && y1==a.y1 && ppd==a.ppd;
}
@Override
public int hashCode(){
return Objects.hashCode(x0,x1,y0,y1,ppd);
}
}
| 24.776224
| 84
| 0.611629
|
a73256abbd4d982a485f88471e0bf05fc5be2379
| 524
|
package com.google.android.gms.internal.ads;
import android.os.Bundle;
import com.google.android.gms.ads.internal.zzk;
/* renamed from: com.google.android.gms.internal.ads.dj */
final /* synthetic */ class C9384dj implements zzbal {
/* renamed from: a */
private final zzcvs f22183a;
C9384dj(zzcvs zzcvs) {
this.f22183a = zzcvs;
}
/* renamed from: a */
public final zzbbh mo26658a(Object obj) {
return this.f22183a.mo29265a().mo31269a(zzk.zzlg().mo30228a((Bundle) obj));
}
}
| 24.952381
| 83
| 0.671756
|
585beb95fed608e9fe295031406609a5df6cf975
| 63
|
package com.cl.blogv2.entity.query;
public class BanQuery {
}
| 12.6
| 35
| 0.761905
|
e358269eeaa7c8ef40f891dcec9f3031cbc75b68
| 2,702
|
package zmq;
import java.nio.channels.SelectableChannel;
// Simple base class for objects that live in I/O threads.
// It makes communication with the poller object easier and
// makes defining unneeded event handlers unnecessary.
public class IOObject implements IPollEvents
{
private Poller poller;
private IPollEvents handler;
public IOObject(IOThread ioThread)
{
if (ioThread != null) {
plug(ioThread);
}
}
// When migrating an object from one I/O thread to another, first
// unplug it, then migrate it, then plug it to the new thread.
public void plug(IOThread ioThread)
{
assert (ioThread != null);
assert (poller == null);
// Retrieve the poller from the thread we are running in.
poller = ioThread.getPoller();
}
public void unplug()
{
assert (poller != null);
// Forget about old poller in preparation to be migrated
// to a different I/O thread.
poller = null;
handler = null;
}
public final void addHandle(SelectableChannel handle)
{
poller.addHandle(handle, this);
}
public final void removeHandle(SelectableChannel handle)
{
poller.removeHandle(handle);
}
public final void setPollIn(SelectableChannel handle)
{
poller.setPollIn(handle);
}
public final void setPollOut(SelectableChannel handle)
{
poller.setPollOut(handle);
}
public final void setPollConnect(SelectableChannel handle)
{
poller.setPollConnect(handle);
}
public final void setPollAccept(SelectableChannel handle)
{
poller.setPollAccept(handle);
}
public final void resetPollIn(SelectableChannel handle)
{
poller.resetPollOn(handle);
}
public final void resetPollOut(SelectableChannel handle)
{
poller.resetPollOut(handle);
}
@Override
public final void inEvent()
{
handler.inEvent();
}
@Override
public final void outEvent()
{
handler.outEvent();
}
@Override
public final void connectEvent()
{
handler.connectEvent();
}
@Override
public final void acceptEvent()
{
handler.acceptEvent();
}
@Override
public final void timerEvent(int id)
{
handler.timerEvent(id);
}
public final void addTimer(long timeout, int id)
{
poller.addTimer(timeout, this, id);
}
public final void setHandler(IPollEvents handler)
{
this.handler = handler;
}
public void cancelTimer(int id)
{
poller.cancelTimer(this, id);
}
}
| 21.109375
| 70
| 0.622502
|
2bbf7d19f2de36b524abdd14d4cf4d2abec080b1
| 6,941
|
/*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.mappingsplugin.ui.db;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext;
import org.eclipse.persistence.tools.workbench.framework.ui.dialog.AbstractValidatingDialog;
import org.eclipse.persistence.tools.workbench.framework.uitools.RegexpDocument;
import org.eclipse.persistence.tools.workbench.framework.uitools.Spacer;
import org.eclipse.persistence.tools.workbench.framework.uitools.SwingComponentFactory;
import org.eclipse.persistence.tools.workbench.mappingsmodel.project.relational.MWRelationalProject;
import org.eclipse.persistence.tools.workbench.utility.NameTools;
final class DescriptorGenerationDialog extends AbstractValidatingDialog {
private MWRelationalProject project;
private JTextField packageNameTextField;
private JCheckBox generateAccessorsCheckBox;
public DescriptorGenerationDialog(MWRelationalProject project, WorkbenchContext workbenchContext) {
super(workbenchContext);
this.project = project;
initializeDialog();
}
public boolean getGenerateAccessors() {
return this.generateAccessorsCheckBox.isSelected();
}
public String getPackageName() {
return this.packageNameTextField.getText();
}
protected String helpTopicId() {
return "dialog.descriptorGeneration";
}
private void initializeDialog() {
// Set help and title string
String titleString = null;
titleString = "DescriptorGenerationDialog_class.title";
setResizable(true);
setTitle(resourceRepository().getString(titleString));
}
protected Component buildMainPanel() {
GridBagConstraints constraints = new GridBagConstraints();
JPanel mainPanel = new JPanel(new GridBagLayout());
// Create the package name label and text field
JLabel packageNameLabel = SwingComponentFactory.buildLabel("DescriptorGenerationDialog_packageName", resourceRepository());
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 0;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.LINE_START;
constraints.insets = new Insets(0, 0, 0, 0);
mainPanel.add(packageNameLabel, constraints);
this.packageNameTextField = new JTextField();
this.packageNameTextField.setColumns(30);
Document packageNameDocument = new RegexpDocument(RegexpDocument.RE_PACKAGE);
packageNameDocument.addDocumentListener(this.buildPackageNameDocumentListener());
this.packageNameTextField.setDocument(packageNameDocument);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(0, 5, 0, 0);
mainPanel.add(this.packageNameTextField, constraints);
packageNameLabel.setLabelFor(this.packageNameTextField);
this.generateAccessorsCheckBox = new JCheckBox(resourceRepository().getString("DescriptorGenerationDialog_generateAccessingMethods"), true);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weightx = 0;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.LINE_START;
constraints.insets = new Insets(5, 0, 0, 0);
mainPanel.add(this.generateAccessorsCheckBox, constraints);
// Push everything to the top
Spacer spacer = new Spacer();
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 0;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(0, 0, 0, 0);
mainPanel.add(spacer, constraints);
return mainPanel;
}
void showNoRelationshipSupportDialog() {
JOptionPane.showMessageDialog(
this,
resourceRepository().getString("DescriptorGenerationDialog_noRelationshipSupport.message"),
resourceRepository().getString("DescriptorGenerationDialog_noRelationshipSupport.title"),
JOptionPane.WARNING_MESSAGE
);
}
protected DocumentListener buildPackageNameDocumentListener() {
return new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
DescriptorGenerationDialog.this.packageNameDocumentChanged();
}
public void insertUpdate(DocumentEvent e) {
DescriptorGenerationDialog.this.packageNameDocumentChanged();
}
public void changedUpdate(DocumentEvent e) {
// this probably will never happen...
}
};
}
void packageNameDocumentChanged() {
if (this.isVisible()) {
this.validatePackageName();
}
}
private void validatePackageName() {
String pkgName = this.packageNameTextField.getText();
if (this.packageNameIsIllegal(pkgName)) {
this.setErrorMessageKey("NEW_NAME_DIALOG.ILLEGAL_VALUE");
return;
}
// no problems...
this.clearErrorMessage();
}
private boolean packageNameIsIllegal(String name) {
String[] segments = name.split("\\.");
for (int i = 0; i < segments.length; i++) {
if (NameTools.javaReservedWordsContains(segments[i])) {
return true;
}
}
return false;
}
protected void setErrorMessageKey(String key) {
super.setErrorMessageKey(key);
this.getOKAction().setEnabled(false);
}
protected void clearErrorMessage() {
super.clearErrorMessage();
this.getOKAction().setEnabled(true);
}
}
| 34.705
| 143
| 0.736061
|
10ab74f106d2bd5d8f24da7895e470db06bb906e
| 446
|
package fr.redstonneur1256.redutilities.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class IOUtils {
public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int count;
while((count = input.read(buf, 0, buf.length)) != -1) {
output.write(buf, 0, count);
}
}
}
| 24.777778
| 104
| 0.661435
|
148384e458bea94c17c2e3ec36ffbda9b450d6e1
| 5,018
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.centelon.finnate.template;
import com.centelon.finnate.template.api.v1.client.TemplateManager;
import com.centelon.finnate.template.api.v1.domain.Sample;
import com.centelon.finnate.template.api.v1.events.EventConstants;
import com.centelon.finnate.template.service.TemplateConfiguration;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.fineract.cn.anubis.test.v1.TenantApplicationSecurityEnvironmentTestRule;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.test.fixture.TenantDataStoreContextTestRule;
import org.apache.fineract.cn.test.listener.EnableEventRecording;
import org.apache.fineract.cn.test.listener.EventRecorder;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class TestSample extends SuiteTestEnvironment {
private static final String LOGGER_NAME = "test-logger";
private static final String TEST_USER = "homer";
@Configuration
@EnableEventRecording
@EnableFeignClients(basePackages = {"com.centelon.finnate.template.api.v1.client"})
@RibbonClient(name = APP_NAME)
@Import({TemplateConfiguration.class})
@ComponentScan("com.centelon.finnate.template.listener")
public static class TestConfiguration {
public TestConfiguration() {
super();
}
@Bean(name = LOGGER_NAME)
public Logger logger() {
return LoggerFactory.getLogger(LOGGER_NAME);
}
}
@ClassRule
public final static TenantDataStoreContextTestRule tenantDataStoreContext = TenantDataStoreContextTestRule.forRandomTenantName(cassandraInitializer, postgreSQLInitializer);
@Rule
public final TenantApplicationSecurityEnvironmentTestRule tenantApplicationSecurityEnvironment
= new TenantApplicationSecurityEnvironmentTestRule(testEnvironment, this::waitForInitialize);
private AutoUserContext userContext;
@Autowired
private TemplateManager testSubject;
@Autowired
private EventRecorder eventRecorder;
@SuppressWarnings("WeakerAccess")
@Autowired
@Qualifier(LOGGER_NAME)
Logger logger;
public TestSample() {
super();
}
@Before
public void prepTest() {
userContext = tenantApplicationSecurityEnvironment.createAutoUserContext(TestSample.TEST_USER);
}
@After
public void cleanTest() {
userContext.close();
eventRecorder.clear();
}
public boolean waitForInitialize() {
try {
return this.eventRecorder.wait(EventConstants.INITIALIZE, APP_VERSION);
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
}
@Test
public void shouldCreateSample() throws InterruptedException {
logger.info("Running test shouldCreateSample.");
final Sample sample = Sample.create(RandomStringUtils.randomAlphanumeric(8), RandomStringUtils.randomAlphanumeric(512));
this.testSubject.createEntity(sample);
Assert.assertTrue(this.eventRecorder.wait(EventConstants.POST_SAMPLE, sample.getIdentifier()));
final Sample createdSample = this.testSubject.getEntity(sample.getIdentifier());
Assert.assertEquals(sample, createdSample);
}
@Test
public void shouldListSamples() {
logger.info("Running test shouldListSamples.");
final List<Sample> allEntities = this.testSubject.findAllEntities();
Assert.assertNotNull(allEntities);
}
}
| 36.362319
| 174
| 0.790355
|
7370d31409095c518c68c7c16b90173c9ff0ea72
| 1,183
|
package com.app.base.activity;
import android.view.ViewStub;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.app.base.R;
import com.app.base.view.TopBarType;
import static com.app.base.view.TopBarType.TitleBar;
/**
* @param <DB> ViewDataBinding
* @Description
* @Author Zhenhui
* @Time 2019/8/19 11:22
*/
public abstract class LibBaseBindingActivity<DB extends ViewDataBinding> extends LibBaseActivity {
protected DB mDataBinding;
@Override
protected final void initContentView() {
super.setContentView(R.layout.base_root_layout);
ViewStub viewStub = findViewById(R.id.contentVs);
// viewStub.setLayoutResource(getContentLayoutId());
// View contentVs = viewStub.inflate();
ViewStub toolbarVs = findViewById(R.id.toolbarVs);
TopBarType topBarType = getTopBarType();
if (topBarType == TitleBar) {
toolbarVs.setLayoutResource(getTitleLayoutId());
mToolbarView = toolbarVs.inflate();
}
mDataBinding = DataBindingUtil.setContentView(this, getContentLayoutId());
mContentView = mDataBinding.getRoot();
}
}
| 31.131579
| 98
| 0.71344
|
0a4c62a5663c23e62de4413023aa1a9b3381f0b7
| 859
|
package com.sample.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the UserAccountType database table.
*
*/
@Entity
@Table(name="UserAccountType")
@NamedQuery(name="UserAccountType.findAll", query="SELECT u FROM UserAccountType u")
public class UserAccountType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private byte id;
@Column(length=45)
private String accountType;
public UserAccountType() {
}
public byte getId() {
return this.id;
}
public void setId(byte id) {
this.id = id;
}
public String getAccountType() {
return this.accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
}
| 19.088889
| 84
| 0.745052
|
0374fe7710b5dad1ef97f58b8496411b595bafaf
| 2,443
|
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("4")
class Record_3446 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 3446: FirstName is Michel")
void FirstNameOfRecord3446() {
assertEquals("Michel", customers.get(3445).getFirstName());
}
@Test
@DisplayName("Record 3446: LastName is Shover")
void LastNameOfRecord3446() {
assertEquals("Shover", customers.get(3445).getLastName());
}
@Test
@DisplayName("Record 3446: Company is Fairfield Executive Inn")
void CompanyOfRecord3446() {
assertEquals("Fairfield Executive Inn", customers.get(3445).getCompany());
}
@Test
@DisplayName("Record 3446: Address is Charles")
void AddressOfRecord3446() {
assertEquals("Charles", customers.get(3445).getAddress());
}
@Test
@DisplayName("Record 3446: City is Baltimore")
void CityOfRecord3446() {
assertEquals("Baltimore", customers.get(3445).getCity());
}
@Test
@DisplayName("Record 3446: County is Baltimore City")
void CountyOfRecord3446() {
assertEquals("Baltimore City", customers.get(3445).getCounty());
}
@Test
@DisplayName("Record 3446: State is MD")
void StateOfRecord3446() {
assertEquals("MD", customers.get(3445).getState());
}
@Test
@DisplayName("Record 3446: ZIP is 21201")
void ZIPOfRecord3446() {
assertEquals("21201", customers.get(3445).getZIP());
}
@Test
@DisplayName("Record 3446: Phone is 410-659-4590")
void PhoneOfRecord3446() {
assertEquals("410-659-4590", customers.get(3445).getPhone());
}
@Test
@DisplayName("Record 3446: Fax is 410-659-7273")
void FaxOfRecord3446() {
assertEquals("410-659-7273", customers.get(3445).getFax());
}
@Test
@DisplayName("Record 3446: Email is michel@shover.com")
void EmailOfRecord3446() {
assertEquals("michel@shover.com", customers.get(3445).getEmail());
}
@Test
@DisplayName("Record 3446: Web is http://www.michelshover.com")
void WebOfRecord3446() {
assertEquals("http://www.michelshover.com", customers.get(3445).getWeb());
}
}
| 25.447917
| 76
| 0.734752
|
0d5a6bd8a5a1383e83665ba22f78270862f8a70a
| 2,368
|
package com.huaweicloud.sdk.vpcep.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/** RoutetableInfoErrorDetial */
public class RoutetableInfoErrorDetial {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "id")
private String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "error_message")
private String errorMessage;
public RoutetableInfoErrorDetial withId(String id) {
this.id = id;
return this;
}
/** 路由表ID。
*
* @return id */
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public RoutetableInfoErrorDetial withErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
/** 详细错误信息。
*
* @return errorMessage */
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RoutetableInfoErrorDetial routetableInfoErrorDetial = (RoutetableInfoErrorDetial) o;
return Objects.equals(this.id, routetableInfoErrorDetial.id)
&& Objects.equals(this.errorMessage, routetableInfoErrorDetial.errorMessage);
}
@Override
public int hashCode() {
return Objects.hash(id, errorMessage);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class RoutetableInfoErrorDetial {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" errorMessage: ").append(toIndentedString(errorMessage)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 26.311111
| 106
| 0.624155
|
9109e51eede820999ffe061e58ef4921cd92d170
| 2,634
|
package com.example.fourpdareader;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This class is used through the application because:
* 1) it outputs additional information like time and thread name;
* 2) all logging in the application may be controlled via this class;
* 3) in particular, all logging may be disabled by setting ENABLED to false.
*/
public class Log {
private final static boolean ENABLED = true;
/**
* Print a String to the log.
* The tag will include "BipTest", thread name, and timestamp.
* @param s
*/
public static void d(String s) {
if(ENABLED) {
android.util.Log.d(tag(), s);
}
}
/**
* Make a string to be used as the tag for android.util.Log.d(tag,message)
* @return a tag
*/
static private String tag() {
return "4pda[" + Thread.currentThread().getName()+"]"+getTimestamp();
}
/**
* @return current time as a string
*/
private static String getTimestamp() {
long time = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String date = sdf.format(new Date(time)).toString();
return date;
}
/**
* Print a Throwable to the log.
* The tag will include "BipTest", thread name, and timestamp.
* @param t
*/
public static void d(Throwable t) {
if (ENABLED) {
d("---...--- " + t + " ---...---");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(bos);
t.printStackTrace(pw);
pw.close();
d(bos.toString());
d("---'''--- " + t + " ---'''---");
}
}
/**
* Get the name of method specified by depth in the call stack.
* @param depth depth in the call stack (0 means current method, 1 means calling method, etc.)
* @return class name . method name ()
*/
public static String getMethodInfo(final int depth)
{
final StackTraceElement[] ste = new Throwable().getStackTrace();
return ste[depth].getClassName()+"."+ste[depth].getMethodName()+"()";
}
/**
* Print the class name and the method name of the caller to the log.
*/
public static void f() {
d("### "+ getMethodInfo(2));
}
/**
* Print the class and the method names of the caller and the caller's caller to the log.
*/
public static void ff() {
d("### "+ getMethodInfo(2));
d("### <"+ getMethodInfo(3));
}
/**
* Print the class and method names of the last 3 functions on the call stack to the log.
*/
public static void fff() {
d("### "+ getMethodInfo(2));
d("### <"+ getMethodInfo(3));
d("### <<"+ getMethodInfo(4));
}
}
| 27.726316
| 95
| 0.637813
|
bd3599044e4cf6a43371202f331818732b52d3b8
| 7,289
|
/*
* 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.commons.math3.genetics;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
/**
* Cycle Crossover [CX] builds offspring from <b>ordered</b> chromosomes by identifying cycles
* between two parent chromosomes. To form the children, the cycles are copied from the
* respective parents.
* <p>
* To form a cycle the following procedure is applied:
* <ol>
* <li>start with the first gene of parent 1</li>
* <li>look at the gene at the same position of parent 2</li>
* <li>go to the position with the same gene in parent 1</li>
* <li>add this gene index to the cycle</li>
* <li>repeat the steps 2-5 until we arrive at the starting gene of this cycle</li>
* </ol>
* The indices that form a cycle are then used to form the children in alternating order, i.e.
* in cycle 1, the genes of parent 1 are copied to child 1, while in cycle 2 the genes of parent 1
* are copied to child 2, and so forth ...
* </p>
*
* Example (zero-start cycle):
* <pre>
* p1 = (8 4 7 3 6 2 5 1 9 0) X c1 = (8 1 2 3 4 5 6 7 9 0)
* p2 = (0 1 2 3 4 5 6 7 8 9) X c2 = (0 4 7 3 6 2 5 1 8 9)
*
* cycle 1: 8 0 9
* cycle 2: 4 1 7 2 5 6
* cycle 3: 3
* </pre>
*
* This policy works only on {@link AbstractListChromosome}, and therefore it
* is parameterized by T. Moreover, the chromosomes must have same lengths.
*
* @see <a href="http://www.rubicite.com/Tutorials/GeneticAlgorithms/CrossoverOperators/CycleCrossoverOperator.aspx">
* Cycle Crossover Operator</a>
*
* @param <T> generic type of the {@link AbstractListChromosome}s for crossover
* @since 3.1
* @version $Id$
*/
public class CycleCrossover<T> implements CrossoverPolicy {
/** If the start index shall be chosen randomly. */
private final boolean randomStart;
/**
* Creates a new {@link CycleCrossover} policy.
*/
public CycleCrossover() {
this(false);
}
/**
* Creates a new {@link CycleCrossover} policy using the given {@code randomStart} behavior.
*
* @param randomStart whether the start index shall be chosen randomly or be set to 0
*/
public CycleCrossover(final boolean randomStart) {
this.randomStart = randomStart;
}
/**
* Returns whether the starting index is chosen randomly or set to zero.
*
* @return {@code true} if the starting index is chosen randomly, {@code false} otherwise
*/
public boolean isRandomStart() {
return randomStart;
}
/**
* {@inheritDoc}
*
* @throws MathIllegalArgumentException if the chromosomes are not an instance of {@link AbstractListChromosome}
* @throws DimensionMismatchException if the length of the two chromosomes is different
*/
@SuppressWarnings("unchecked")
public ChromosomePair crossover(final Chromosome first, final Chromosome second)
throws DimensionMismatchException, MathIllegalArgumentException {
if (!(first instanceof AbstractListChromosome<?> && second instanceof AbstractListChromosome<?>)) {
throw new MathIllegalArgumentException(LocalizedFormats.INVALID_FIXED_LENGTH_CHROMOSOME);
}
return mate((AbstractListChromosome<T>) first, (AbstractListChromosome<T>) second);
}
/**
* Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
*
* @param first the first chromosome
* @param second the second chromosome
* @return the pair of new chromosomes that resulted from the crossover
* @throws DimensionMismatchException if the length of the two chromosomes is different
*/
protected ChromosomePair mate(final AbstractListChromosome<T> first, final AbstractListChromosome<T> second)
throws DimensionMismatchException {
final int length = first.getLength();
if (length != second.getLength()) {
throw new DimensionMismatchException(second.getLength(), length);
}
// array representations of the parents
final List<T> parent1Rep = first.getRepresentation();
final List<T> parent2Rep = second.getRepresentation();
// and of the children: do a crossover copy to simplify the later processing
final List<T> child1Rep = new ArrayList<T>(second.getRepresentation());
final List<T> child2Rep = new ArrayList<T>(first.getRepresentation());
// the set of all visited indices so far
final Set<Integer> visitedIndices = new HashSet<Integer>(length);
// the indices of the current cycle
final List<Integer> indices = new ArrayList<Integer>(length);
// determine the starting index
int idx = randomStart ? GeneticAlgorithm.getRandomGenerator().nextInt(length) : 0;
int cycle = 1;
while (visitedIndices.size() < length) {
indices.add(idx);
T item = parent2Rep.get(idx);
idx = parent1Rep.indexOf(item);
while (idx != indices.get(0)) {
// add that index to the cycle indices
indices.add(idx);
// get the item in the second parent at that index
item = parent2Rep.get(idx);
// get the index of that item in the first parent
idx = parent1Rep.indexOf(item);
}
// for even cycles: swap the child elements on the indices found in this cycle
if (cycle++ % 2 != 0) {
for (int i : indices) {
T tmp = child1Rep.get(i);
child1Rep.set(i, child2Rep.get(i));
child2Rep.set(i, tmp);
}
}
visitedIndices.addAll(indices);
// find next starting index: last one + 1 until we find an unvisited index
idx = (indices.get(0) + 1) % length;
while (visitedIndices.contains(idx) && visitedIndices.size() < length) {
idx++;
if (idx >= length) {
idx = 0;
}
}
indices.clear();
}
return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
second.newFixedLengthChromosome(child2Rep));
}
}
| 39.61413
| 117
| 0.65249
|
86c47dfd4d039bd5a834facc46880f9fd1512e56
| 2,635
|
/***********************************************************************************************************************
* Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.nephele.template;
import java.util.Iterator;
import eu.stratosphere.core.io.InputSplit;
/**
* The input split iterator allows an {@link AbstractInputTask} to iterator over all input splits it is supposed to
* consume. Internally, the input split iterator calls an {@link InputSplitProvider} on each <code>next</code> call in
* order to facilitate lazy split assignment.
*
* @param <T>
*/
public class InputSplitIterator<T extends InputSplit> implements Iterator<T> {
/**
* The {@link InputSplitProvider} that is called to provide new input splits.
*/
private final InputSplitProvider inputSplitProvider;
/**
* Buffers the next input split to be returned by this iterator or <code>null</code> it no split is buffered.
*/
private T nextInputSplit = null;
/**
* Constructs a new input split iterator.
*
* @param inputSplitProvider
* the input split provider to be called for new input splits
*/
public InputSplitIterator(final InputSplitProvider inputSplitProvider) {
this.inputSplitProvider = inputSplitProvider;
}
@SuppressWarnings("unchecked")
@Override
public boolean hasNext() {
if (this.nextInputSplit == null) {
this.nextInputSplit = (T) inputSplitProvider.getNextInputSplit();
}
if (this.nextInputSplit == null) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public T next() {
T retVal = null;
if (this.nextInputSplit == null) {
this.nextInputSplit = (T) inputSplitProvider.getNextInputSplit();
}
retVal = this.nextInputSplit;
this.nextInputSplit = null;
return retVal;
}
@Override
public void remove() {
throw new RuntimeException("The InputSplitIterator does not implement the remove method");
}
}
| 29.277778
| 120
| 0.665275
|
c9080d2b1e66a097aa261eb6df77828773165aaa
| 6,513
|
package moze_intel.projecte.gameObjs.entity;
import java.util.Comparator;
import java.util.List;
import javax.annotation.Nonnull;
import moze_intel.projecte.gameObjs.registries.PEEntityTypes;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.projectile.ArrowEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.network.IPacket;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
public class EntityHomingArrow extends ArrowEntity {
private static final DataParameter<Integer> DW_TARGET_ID = EntityDataManager.createKey(EntityHomingArrow.class, DataSerializers.VARINT);
private static final int NO_TARGET = -1;
private int newTargetCooldown = 0;
public EntityHomingArrow(EntityType<EntityHomingArrow> type, World world) {
super(type, world);
}
public EntityHomingArrow(World world, LivingEntity shooter, float damage) {
super(world, shooter);
this.setDamage(damage);
this.pickupStatus = PickupStatus.CREATIVE_ONLY;
}
@Nonnull
@Override
public EntityType<?> getType() {
return PEEntityTypes.HOMING_ARROW.get();
}
@Override
public void registerData() {
super.registerData();
dataManager.register(DW_TARGET_ID, NO_TARGET); // Target entity id
}
@Override
protected void arrowHit(@Nonnull LivingEntity living) {
super.arrowHit(living);
// Strip damage vulnerability
living.hurtResistantTime = 0;
}
@Override
public void tick() {
if (!world.isRemote && this.ticksExisted > 3) {
if (hasTarget() && (!getTarget().isAlive() || this.inGround)) {
dataManager.set(DW_TARGET_ID, NO_TARGET);
}
if (!hasTarget() && !this.inGround && newTargetCooldown <= 0) {
findNewTarget();
} else {
newTargetCooldown--;
}
}
if (ticksExisted > 3 && hasTarget() && !this.inGround) {
double mX = getMotion().getX();
double mY = getMotion().getY();
double mZ = getMotion().getZ();
this.getEntityWorld().addParticle(ParticleTypes.FLAME, getPosX() + mX / 4.0D, getPosY() + mY / 4.0D, getPosZ() + mZ / 4.0D, -mX / 2, -mY / 2 + 0.2D, -mZ / 2);
this.getEntityWorld().addParticle(ParticleTypes.FLAME, getPosX() + mX / 4.0D, getPosY() + mY / 4.0D, getPosZ() + mZ / 4.0D, -mX / 2, -mY / 2 + 0.2D, -mZ / 2);
Entity target = getTarget();
Vector3d arrowLoc = new Vector3d(getPosX(), getPosY(), getPosZ());
Vector3d targetLoc = new Vector3d(target.getPosX(), target.getPosY() + target.getHeight() / 2, target.getPosZ());
// Get the vector that points straight from the arrow to the target
Vector3d lookVec = targetLoc.subtract(arrowLoc);
Vector3d arrowMotion = new Vector3d(mX, mY, mZ);
// Find the angle between the direct vec and arrow vec, and then clamp it so it arcs a bit
double theta = wrap180Radian(angleBetween(arrowMotion, lookVec));
theta = clampAbs(theta, Math.PI / 2); // Dividing by higher numbers kills accuracy
// Find the cross product to determine the axis of rotation
Vector3d crossProduct = arrowMotion.crossProduct(lookVec).normalize();
// Create the rotation using the axis and our angle and adjust the vector to it
Vector3d adjustedLookVec = transform(crossProduct, theta, arrowMotion);
// Tell mc to adjust our rotation accordingly
shoot(adjustedLookVec.x, adjustedLookVec.y, adjustedLookVec.z, 1.0F, 0);
}
super.tick();
}
private Vector3d transform(Vector3d axis, double angle, Vector3d normal) {
//Trimmed down math of javax vecmath calculations, potentially should be rewritten at some point
double m00 = 1;
double m01 = 0;
double m02 = 0;
double m10 = 0;
double m11 = 1;
double m12 = 0;
double m20 = 0;
double m21 = 0;
double m22 = 1;
double mag = Math.sqrt(axis.x * axis.x + axis.y * axis.y + axis.z * axis.z);
if (mag >= 1.0E-10) {
mag = 1.0 / mag;
double ax = axis.x * mag;
double ay = axis.y * mag;
double az = axis.z * mag;
double sinTheta = Math.sin(angle);
double cosTheta = Math.cos(angle);
double t = 1.0 - cosTheta;
double xz = ax * az;
double xy = ax * ay;
double yz = ay * az;
m00 = t * ax * ax + cosTheta;
m01 = t * xy - sinTheta * az;
m02 = t * xz + sinTheta * ay;
m10 = t * xy + sinTheta * az;
m11 = t * ay * ay + cosTheta;
m12 = t * yz - sinTheta * ax;
m20 = t * xz - sinTheta * ay;
m21 = t * yz + sinTheta * ax;
m22 = t * az * az + cosTheta;
}
return new Vector3d(m00 * normal.x + m01 * normal.y + m02 * normal.z,
m10 * normal.x + m11 * normal.y + m12 * normal.z,
m20 * normal.x + m21 * normal.y + m22 * normal.z);
}
@Nonnull
@Override
protected ItemStack getArrowStack() {
return new ItemStack(Items.ARROW);
}
private void findNewTarget() {
List<MobEntity> candidates = world.getEntitiesWithinAABB(MobEntity.class, this.getBoundingBox().grow(8, 8, 8));
if (!candidates.isEmpty()) {
candidates.sort(Comparator.comparing(EntityHomingArrow.this::getDistanceSq, Double::compare));
dataManager.set(DW_TARGET_ID, candidates.get(0).getEntityId());
}
newTargetCooldown = 5;
}
private MobEntity getTarget() {
return (MobEntity) world.getEntityByID(dataManager.get(DW_TARGET_ID));
}
private boolean hasTarget() {
return getTarget() != null;
}
private double angleBetween(Vector3d v1, Vector3d v2) {
double vDot = v1.dotProduct(v2) / (v1.length() * v2.length());
if (vDot < -1.0) {
vDot = -1.0;
}
if (vDot > 1.0) {
vDot = 1.0;
}
return Math.acos(vDot);
}
private double wrap180Radian(double radian) {
radian %= 2 * Math.PI;
while (radian >= Math.PI) {
radian -= 2 * Math.PI;
}
while (radian < -Math.PI) {
radian += 2 * Math.PI;
}
return radian;
}
private double clampAbs(double param, double maxMagnitude) {
if (Math.abs(param) > maxMagnitude) {
//System.out.println("CLAMPED");
if (param < 0) {
param = -Math.abs(maxMagnitude);
} else {
param = Math.abs(maxMagnitude);
}
}
return param;
}
@Nonnull
@Override
public IPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
public boolean isImmuneToExplosions() {
return true;
}
}
| 29.604545
| 161
| 0.690312
|
f1d20cc5e97b2ec3970a98e92d0c5d84767e8b01
| 1,170
|
package io.github.kavahub.learnjava;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/**
*
* {@link Supplier} 包装 {@link Stream}
*
* @author PinWei Wan
* @since 1.0.0
*/
public class SupplierStreamTest {
@Test // (expected = IllegalStateException.class)
public void givenStream_whenStreamUsedTwice_thenThrowException() {
Stream<String> stringStream = Stream.of("A", "B", "C", "D");
Optional<String> result1 = stringStream.findAny();
System.out.println(result1.get());
// stream 只能使用一次
assertThrows(IllegalStateException.class, () -> stringStream.findFirst());
}
@Test
public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() {
Supplier<Stream<String>> streamSupplier = () -> Stream.of("A", "B", "C", "D");
Optional<String> result1 = streamSupplier.get().findAny();
System.out.println(result1.get());
Optional<String> result2 = streamSupplier.get().findFirst();
System.out.println(result2.get());
}
}
| 30.789474
| 86
| 0.677778
|
ee97c23e38a4fa573f28022348f3b0bad244de9d
| 3,803
|
/*
* Copyright (C) 2006 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 libcore.java.lang;
import junit.framework.TestCase;
public class OldAndroidInstanceofTest extends TestCase {
protected A mA;
protected ChildOfAOne mOne;
protected ChildOfAOne mTwo;
protected ChildOfAOne mThree;
protected ChildOfAOne mFour;
protected ChildOfAFive mFive;
@Override
protected void setUp() throws Exception {
super.setUp();
mA = new A();
mOne = new ChildOfAOne();
mTwo = new ChildOfATwo();
mThree = new ChildOfAThree();
mFour = new ChildOfAFour();
mFive = new ChildOfAFive();
}
public void testNoInterface() throws Exception {
A a = mA;
for (int i = 0; i < 100000; i++) {
assertFalse("m_a should not be a ChildOfAFive", a instanceof ChildOfAFive);
}
}
public void testDerivedOne() throws Exception {
InterfaceOne one = mOne;
for (int i = 0; i < 100000; i++) {
assertFalse("m_one should not be a ChildOfAFive", one instanceof ChildOfAFive);
}
}
public void testDerivedTwo() throws Exception {
InterfaceTwo two = mTwo;
for (int i = 0; i < 100000; i++) {
assertFalse("m_two should not be a ChildOfAFive", two instanceof ChildOfAFive);
}
}
public void testDerivedThree() throws Exception {
InterfaceThree three = mThree;
for (int i = 0; i < 100000; i++) {
assertFalse("m_three should not be a ChildOfAFive", three instanceof ChildOfAFive);
}
}
public void testDerivedFour() throws Exception {
InterfaceFour four = mFour;
for (int i = 0; i < 100000; i++) {
assertFalse("m_four should not be a ChildOfAFive", four instanceof ChildOfAFive);
}
}
public void testSuccessClass() throws Exception {
ChildOfAOne five = mFive;
for (int i = 0; i < 100000; i++) {
assertTrue("m_five is suppose to be a ChildOfAFive", five instanceof ChildOfAFive);
}
}
public void testSuccessInterface() throws Exception {
ChildOfAFive five = mFive;
for (int i = 0; i < 100000; i++) {
assertTrue("m_five is suppose to be a InterfaceFour", five instanceof InterfaceFour);
}
}
public void testFailInterface() throws Exception {
InterfaceOne one = mFive;
for (int i = 0; i < 100000; i++) {
assertFalse("m_five does not implement InterfaceFive", one instanceof InterfaceFive);
}
}
private interface InterfaceOne {
}
private interface InterfaceTwo {
}
private interface InterfaceThree {
}
private interface InterfaceFour {
}
private interface InterfaceFive {
}
private static class A {
}
private static class ChildOfAOne extends A implements InterfaceOne, InterfaceTwo, InterfaceThree, InterfaceFour {
}
private static class ChildOfATwo extends ChildOfAOne {
}
private static class ChildOfAThree extends ChildOfATwo {
}
private static class ChildOfAFour extends ChildOfAThree {
}
private static class ChildOfAFive extends ChildOfAFour {
}
}
| 28.810606
| 117
| 0.643439
|
fb684fd93a61bf3a83820be533e98aab9b0a3800
| 9,838
|
package org.kohsuke.graphviz;
import java.awt.*;
/**
* Type safe representation of graph attributes.
*
* <p>
* See http://www.graphviz.org/doc/info/attrs.html
* for more documentation and what each attribute means.
*
* @author Kohsuke Kawaguchi
*/
public abstract class Attribute<V> {
public final String name;
Attribute(String name) {
this.name = name;
}
public abstract String toString(V value);
public abstract V fromString(String value);
private static final class EnumAttribute<T extends Enum<T>> extends Attribute<T> {
private final Class<T> type;
EnumAttribute(String name, Class<T> type) {
super(name);
this.type = type;
}
public String toString(T value) {
if(value==null) return null;
return value.toString().toLowerCase();
}
public T fromString(String value) {
if(value==null) return null;
return Enum.valueOf(type,name.toUpperCase());
}
}
private static final class StringAttribute extends Attribute<String> {
StringAttribute(String name) {
super(name);
}
public String toString(String value) {
return value;
}
public String fromString(String value) {
return value;
}
}
private static final class FloatAttribute extends Attribute<Float> {
FloatAttribute(String name) {
super(name);
}
public String toString(Float value) {
if(value==null) return null;
return value.toString();
}
public Float fromString(String value) {
if(value==null) return null;
return Float.valueOf(value);
}
}
private static final class IntAttribute extends Attribute<Integer> {
IntAttribute(String name) {
super(name);
}
public String toString(Integer value) {
if(value==null) return null;
return value.toString();
}
public Integer fromString(String value) {
if(value==null) return null;
return Integer.valueOf(value);
}
}
private static final class BooleanAttribute extends Attribute<Boolean> {
BooleanAttribute(String name) {
super(name);
}
public String toString(Boolean value) {
if(value==null) return null;
return value.toString();
}
public Boolean fromString(String value) {
if(value==null) return null;
return Boolean.valueOf(value);
}
}
private static final class ColorAttribute extends Attribute<Color> {
ColorAttribute(String name) {
super(name);
}
public String toString(Color value) {
if(value==null) return null;
return String.format("#%02x%02x%02x",value.getRed(), value.getGreen(), value.getBlue());
}
public Color fromString(String value) {
if(value==null) return null;
return Color.decode(value.substring(1));
}
}
//
// Node attributes
//
public static final ColorAttribute COLOR = new ColorAttribute("color");
public static final StringAttribute COMMENT = new StringAttribute("comment");
public static final FloatAttribute DISTORTION = new FloatAttribute("distortion");
public static final ColorAttribute FILLCOLOR = new ColorAttribute("fillcolor");
public static final BooleanAttribute FIXEDSIZE = new BooleanAttribute("fixedsize");
public static final ColorAttribute FONTCOLOR = new ColorAttribute("fontcolor");
public static final StringAttribute FONTNAME = new StringAttribute("fontname");
public static final FloatAttribute FONTSIZE = new FloatAttribute("fontsize");
public static final StringAttribute GROUP = new StringAttribute("group");
public static final FloatAttribute HEIGHT = new FloatAttribute("height");
public static final StringAttribute LABEL = new StringAttribute("label");
public static final StringAttribute LAYER = new StringAttribute("layer");
public static final FloatAttribute NODE_ORIENTATION = new FloatAttribute("orientation");
public static final BooleanAttribute REGULAR = new BooleanAttribute("regular");
public static final EnumAttribute<Shape> SHAPE = new EnumAttribute<Shape>("shape",Shape.class);
public static final IntAttribute SIDES = new IntAttribute("sides");
public static final FloatAttribute SKEW = new FloatAttribute("skew");
public static final EnumAttribute<StyleAttr> STYLE = new EnumAttribute<StyleAttr>("style",StyleAttr.class);
public static final StringAttribute URL = new StringAttribute("URL");
public static final FloatAttribute WIDTH = new FloatAttribute("width");
public static final FloatAttribute Z = new FloatAttribute("z");
//
// Edge attributes
//
public static final EnumAttribute<Arrow> ARROWHEAD = new EnumAttribute<Arrow>("arrowhead",Arrow.class);
public static final FloatAttribute ARROWSIZE = new FloatAttribute("arrowsize");
public static final EnumAttribute<Arrow> ARROWTAIL = new EnumAttribute<Arrow>("arrowtail",Arrow.class);
// COLOR
// COMMENT
public static final BooleanAttribute CONSTRAINT = new BooleanAttribute("constraint");
public static final BooleanAttribute DECORATE = new BooleanAttribute("decorate");
public static final EnumAttribute<Dir> DIR = new EnumAttribute<Dir>("dir",Dir.class);
// FONTCOLOR
// FONTNAME
// FONTSIZE
public static final StringAttribute HEADLABEL = new StringAttribute("headlabel");
public static final EnumAttribute<Port> HEADPORT = new EnumAttribute<Port>("headport",Port.class);
public static final StringAttribute HEADURL = new StringAttribute("headurl");
// LABEL
public static final FloatAttribute LABELANGLE = new FloatAttribute("labelangle");
public static final FloatAttribute LABELDISTANCE = new FloatAttribute("labeldistance");
public static final BooleanAttribute LABELFLOAT = new BooleanAttribute("labelfloat");
public static final ColorAttribute LABELFONTCOLOR = new ColorAttribute("labelfontcolor");
public static final StringAttribute LABELFONTNAME = new StringAttribute("labelfontname");
public static final FloatAttribute LABELFONTSIZE = new FloatAttribute("labelfontsize");
// LAYER
public static final StringAttribute LHEAD = new StringAttribute("lhead");
public static final StringAttribute LTAIL = new StringAttribute("ltail");
public static final IntAttribute MINLEN = new IntAttribute("minlen");
public static final StringAttribute SAMEHEAD = new StringAttribute("samehead");
public static final StringAttribute SAMETAIL = new StringAttribute("sametail");
// STYLE
public static final StringAttribute TAILLABEL = new StringAttribute("taillabel");
public static final EnumAttribute<Port> TAILPORT = new EnumAttribute<Port>("tailport",Port.class);
public static final StringAttribute TAILURL = new StringAttribute("tailurl");
public static final IntAttribute WEIGHT = new IntAttribute("weight");
//
// Graph attributes
//
public static final ColorAttribute BGCOLOR = new ColorAttribute("bgcolor");
public static final BooleanAttribute CENTER = new BooleanAttribute("center");
public static final EnumAttribute<ClusterRank> CLUSTERRANK = new EnumAttribute<ClusterRank>("clusterrank",ClusterRank.class);
// COLOR
// COMMENT
public static final BooleanAttribute COMPOUND = new BooleanAttribute("compund");
// CONCENTRATE
// FILLCOLOR
// FONTCOLOR
// FONTNAME
public static final StringAttribute FONTPATH = new StringAttribute("fontpath");
// FONTSIZE
// LABEL
public static final StringAttribute LABELJUST = new StringAttribute("labeljust");
public static final StringAttribute LABELLOC = new StringAttribute("labelloc");
// LAYERS
public static final FloatAttribute MARGIN = new FloatAttribute("margin");
public static final FloatAttribute MCLIMIT = new FloatAttribute("mclimit");
public static final FloatAttribute NODESEP = new FloatAttribute("nodesep");
public static final FloatAttribute NSLIMIT = new FloatAttribute("nslimit");
public static final FloatAttribute NSLIMIT1 = new FloatAttribute("nslimit1");
public static final StringAttribute ORDERING = new StringAttribute("ordering");
public static final EnumAttribute<Orientation> GRAPH_ORIENTATION = new EnumAttribute<Orientation>("orientation",Orientation.class);
public static final StringAttribute PAGE = new StringAttribute("page");
public static final EnumAttribute<PageDir> PAGEDIR = new EnumAttribute<PageDir>("pagedir",PageDir.class);
public static final EnumAttribute<Rank> RANK = new EnumAttribute<Rank>("rank",Rank.class);
public static final EnumAttribute<RankDir> RANKDIR = new EnumAttribute<RankDir>("rankdir",RankDir.class);
public static final FloatAttribute RANKSEP = new FloatAttribute("ranksep");
// RATIO??
public static final BooleanAttribute REMINCROSS = new BooleanAttribute("remincross");
public static final BooleanAttribute ROTATE = new BooleanAttribute("rotate");
public static final IntAttribute SAMPLEPOINTS = new IntAttribute("samplepoints");
public static final IntAttribute SEARCHSIZE = new IntAttribute("searchsize");
public static final FloatAttribute SIZE = new FloatAttribute("size");
// STYLE
// URL
}
| 43.724444
| 136
| 0.680118
|
baf25d48d29819a5a1f991c4f501417d36f74e24
| 10,108
|
/*
Copyright 2015 Ant Kutschera
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 ch.maxant.generic_jca_adapter;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.resource.ResourceException;
import javax.resource.spi.ConfigProperty;
import javax.resource.spi.ConnectionDefinition;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterAssociation;
import javax.security.auth.Subject;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
/**
* A class which the container uses to create "connection" factories. It contains the info that the container needs.
* The client doesn't use this class. This class is referenced in the module/resource adapter declaration (xml).
* It is associated with the resource adapter.
*/
@ConnectionDefinition(connectionFactory = TransactionAssistanceFactory.class, //the thing injected into say a servlet/EJB
connectionFactoryImpl = TransactionAssistanceFactoryImpl.class, //impl of the factory
connection = TransactionAssistant.class, //the connection interface to the EIS, exposing its business interface. the factory creates these.
connectionImpl = TransactionAssistantImpl.class //the impl of the business interface
)
public class ManagedTransactionAssistanceFactory implements ManagedConnectionFactory, ResourceAdapterAssociation {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_MIN_AGE_OF_TRANSACTION_BEFORE_RELEVANT_FOR_RECOVERY = 30000;
private final Logger log = Logger.getLogger(this.getClass().getName());
private PrintWriter logWriter;
private ResourceAdapter resourceAdapter;
@ConfigProperty(supportsDynamicUpdates=false, defaultValue="false")
private String handleRecoveryInternally;
@ConfigProperty(supportsDynamicUpdates=false, defaultValue=""+DEFAULT_MIN_AGE_OF_TRANSACTION_BEFORE_RELEVANT_FOR_RECOVERY)
private String minAgeOfTransactionBeforeRelevantForRecovery;
@ConfigProperty(supportsDynamicUpdates=false, defaultValue="")
private String recoveryStatePersistenceDirectory;
@ConfigProperty(supportsDynamicUpdates=false)
private String id;
private File recoveryStatePersistenceDirectoryFile;
private boolean initialised = false;
private synchronized void lazyInit(){
if(initialised) return;
if(isHandleRecoveryInternally()){
if(recoveryStatePersistenceDirectory == null || recoveryStatePersistenceDirectory.isEmpty()){
log.log(Level.SEVERE, "The '" + id + "' adapter has been configured to handle recovery state internally, but the configuration property 'recoveryStatePersistenceDirectoryConfig' has not been set!");
}else{
log.log(Level.WARNING, "The '" + id + "' adapter WILL track transaction state internally. The associated EIS does NOT need to be able to return incomplete transactions and there is NO need to provide an implementation of CommitRollbackRecoveryCallback#getTransactionsInNeedOfRecovery().");
recoveryStatePersistenceDirectoryFile = new File(recoveryStatePersistenceDirectory);
if(!recoveryStatePersistenceDirectoryFile.exists()){
if(!recoveryStatePersistenceDirectoryFile.mkdirs()){
String msg = "FAILED TO CREATE DIRECTORY '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "' - the resource adapter will be unable to track state. Throwing exception now...";
log.log(Level.SEVERE, msg);
throw new RuntimeException(msg);
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in new directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in existing directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}
}else{
log.log(Level.WARNING, "The '" + id + "' adapter will NOT track transaction state internally. The associated EIS MUST be able to return incomplete transactions and you MUST provide an implementation of CommitRollbackRecoveryCallback#getTransactionsInNeedOfRecovery()!");
}
initialised = true;
}
@Override
public Object createConnectionFactory() throws ResourceException {
lazyInit();
throw new ResourceException("This resource adapter doesn't support non-managed environments");
}
@Override
public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
lazyInit();
return new TransactionAssistanceFactoryImpl(this, cxManager);
}
@Override
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
lazyInit();
CommitRollbackRecoveryCallback callback = ((GenericResourceAdapter)this.resourceAdapter).getCommitRollbackRecoveryCallback(id);
return new ManagedTransactionAssistance(callback, isHandleRecoveryInternally(), getMinAgeOfTransactionBeforeRelevantForRecovery(), recoveryStatePersistenceDirectoryFile, id);
}
private Boolean isHandleRecoveryInternally() {
return Boolean.valueOf(handleRecoveryInternally);
}
private int getMinAgeOfTransactionBeforeRelevantForRecovery(){
if(minAgeOfTransactionBeforeRelevantForRecovery == null){
return DEFAULT_MIN_AGE_OF_TRANSACTION_BEFORE_RELEVANT_FOR_RECOVERY;
}
try{
return Integer.parseInt(minAgeOfTransactionBeforeRelevantForRecovery);
}catch(Exception e){
log.warning("Unable to parse value '" + minAgeOfTransactionBeforeRelevantForRecovery + "' for minAgeOfTransactionBeforeRelevantForRecovery from generic resource adapter configuration. using valueu " + DEFAULT_MIN_AGE_OF_TRANSACTION_BEFORE_RELEVANT_FOR_RECOVERY + " instead.");
return DEFAULT_MIN_AGE_OF_TRANSACTION_BEFORE_RELEVANT_FOR_RECOVERY;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
lazyInit();
ManagedConnection result = null;
Iterator<ManagedConnection> it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = it.next();
if (mc instanceof ManagedTransactionAssistance) {
if(cxRequestInfo != null /*&& TODO future: it contains the ID*/){
ManagedTransactionAssistance mta = (ManagedTransactionAssistance)mc;
/*
if(cxRequestInfo.requiredMCFId().equals(mta.getManagedConnectionFactoryId()){
result = mc;
}
*/
}
}
}
return result;
}
@Override
public PrintWriter getLogWriter() throws ResourceException {
return logWriter;
}
@Override
public void setLogWriter(PrintWriter logWriter) throws ResourceException {
this.logWriter = logWriter;
}
@Override
public ResourceAdapter getResourceAdapter() {
return resourceAdapter;
}
@Override
public void setResourceAdapter(ResourceAdapter resourceAdapter)
throws ResourceException {
this.resourceAdapter = resourceAdapter;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ManagedTransactionAssistanceFactory other = (ManagedTransactionAssistanceFactory) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public void setHandleRecoveryInternally(
String handleRecoveryInternally) {
this.handleRecoveryInternally = handleRecoveryInternally;
}
public void setMinAgeOfTransactionBeforeRelevantForRecovery(
String minAgeOfTransactionBeforeRelevantForRecovery) {
this.minAgeOfTransactionBeforeRelevantForRecovery = minAgeOfTransactionBeforeRelevantForRecovery;
}
public void setRecoveryStatePersistenceDirectory(
String recoveryStatePersistenceDirectory) {
this.recoveryStatePersistenceDirectory = recoveryStatePersistenceDirectory;
}
public void setId(String id){
this.id = id;
}
public String getId() {
return id;
}
}
| 44.139738
| 306
| 0.697269
|
788a181c0de3986902140e2e06e8f0aed75aa32b
| 4,582
|
/*
Copyright (C) GridGain Systems. 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 org.gridgain.grid.kernal.processors.cache.distributed;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import org.gridgain.testframework.junits.common.*;
import java.util.*;
import static org.gridgain.grid.cache.GridCacheTxConcurrency.*;
import static org.gridgain.grid.cache.GridCacheTxIsolation.*;
/**
* Simple cache test.
*/
public class GridCacheTxTimeoutAbstractTest extends GridCommonAbstractTest {
/** Random number generator. */
private static final Random RAND = new Random();
/** Grid count. */
private static final int GRID_COUNT = 2;
/** Grid instances. */
private static final List<Grid> grids = new ArrayList<>();
/** Transaction timeout. */
private static final long TIMEOUT = 50;
/**
* @throws Exception If failed.
*/
@Override protected void beforeTestsStarted() throws Exception {
for (int i = 0; i < GRID_COUNT; i++)
grids.add(startGrid(i));
}
/**
* @throws Exception If failed.
*/
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
grids.clear();
}
/**
* @param i Grid index.
* @return Cache.
*/
@Override protected <K, V> GridCache<K, V> cache(int i) {
return grids.get(i).cache(null);
}
/**
* @throws GridException If test failed.
*/
public void testPessimisticReadCommitted() throws Exception {
checkTransactionTimeout(PESSIMISTIC, READ_COMMITTED);
}
/**
* @throws GridException If test failed.
*/
public void testPessimisticRepeatableRead() throws Exception {
checkTransactionTimeout(PESSIMISTIC, REPEATABLE_READ);
}
/**
* @throws GridException If test failed.
*/
public void testPessimisticSerializable() throws Exception {
checkTransactionTimeout(PESSIMISTIC, SERIALIZABLE);
}
/**
* @throws GridException If test failed.
*/
public void testOptimisticReadCommitted() throws Exception {
checkTransactionTimeout(OPTIMISTIC, READ_COMMITTED);
}
/**
* @throws GridException If test failed.
*/
public void testOptimisticRepeatableRead() throws Exception {
checkTransactionTimeout(OPTIMISTIC, REPEATABLE_READ);
}
/**
* @throws GridException If test failed.
*/
public void testOptimisticSerializable() throws Exception {
checkTransactionTimeout(OPTIMISTIC, SERIALIZABLE);
}
/**
* @param concurrency Concurrency.
* @param isolation Isolation.
* @throws GridException If test failed.
*/
private void checkTransactionTimeout(GridCacheTxConcurrency concurrency,
GridCacheTxIsolation isolation) throws Exception {
int idx = RAND.nextInt(GRID_COUNT);
GridCache<Integer, String> cache = cache(idx);
GridCacheTx tx = cache.txStart(concurrency, isolation, TIMEOUT, 0);
try {
info("Storing value in cache [key=1, val=1]");
cache.put(1, "1");
long sleep = TIMEOUT * 2;
info("Going to sleep for (ms): " + sleep);
Thread.sleep(sleep);
info("Storing value in cache [key=1, val=2]");
cache.put(1, "2");
info("Committing transaction: " + tx);
tx.commit();
assert false : "Timeout never happened for transaction: " + tx;
}
catch (GridCacheTxTimeoutException e) {
info("Received expected timeout exception [msg=" + e.getMessage() + ", tx=" + tx + ']');
}
finally {
tx.close();
}
}
}
| 28.459627
| 100
| 0.625709
|
d113de71d5e853370637a749e4c2c1f52e5b6803
| 2,230
|
package queuesAndWorkers;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
// TODO: Auto-generated Javadoc
/**
* The Class AddTaksWorker.
*/
public class AddTaksWorker extends HttpServlet {
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String taskName = request.getParameter("taskName");
String taskInfo = request.getParameter("taskInfo");
String user = request.getParameter("userID");
String course = request.getParameter("course");
String file = request.getParameter("file");
// Do something with key.
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity task = new Entity("Tasks");//Removed key
Date date = new Date();
task.setProperty("date", date);
task.setProperty("taskName", taskName);
task.setProperty("user", user);
task.setProperty("course",course);
task.setProperty("taskInfo",taskInfo);
task.setProperty("file",file);
datastore.put(task);
MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
syncCache.put(course+taskName+user,task);
syncCache.delete(course+user+"task");
System.out.println("Putting " + taskName + " in memcache, with key: "+course+taskName+user+" . Deleting tasklist from memcache");
}
}
| 36.557377
| 132
| 0.735874
|
c1117e348ddabbbcb12f9eb1d623de777f84b1cc
| 2,627
|
package com.xpl.multidownloader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private EditText ed_url;
private Button bt_down;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_url=(EditText) findViewById(R.id.ed_url);
bt_down=(Button) findViewById(R.id.bt_down);
bt_down.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String path = ed_url.getText().toString().trim();
// String path = "http://192.168.110.74/text/PCQQ2020.exe";
if (TextUtils.isEmpty(path)){
Toast.makeText(MainActivity.this,"地址不能为空",Toast.LENGTH_SHORT).show();
return;
}
/**
* 用第三方控件xutils进行下载
*/
HttpUtils http = new HttpUtils();
http.download(path, "/data/data/com.xpl.multidownloader/cache/" + getDownloadFileName(path)
, true, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
Toast.makeText(MainActivity.this,"下载成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(HttpException e, String s) {
Toast.makeText(MainActivity.this,"下载失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
// 显示进度
Log.d(TAG, "onLoading: "+current);
super.onLoading(total, current, isUploading);
}
});
}
});
}
private String getDownloadFileName(String path) {
//取最后一个斜杠 / 后面的内容作为名称
return path.substring(path.lastIndexOf("/") + 1);
}
}
| 35.5
| 107
| 0.584697
|
3d4735e40863c481a584806049bbf076e8fe07f9
| 762
|
package io.minimum.minecraft.alien.network.util;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.base.Preconditions.checkNotNull;
public class AlienNettyThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger();
private final String nameFormat;
public AlienNettyThreadFactory(String nameFormat) {
this.nameFormat = checkNotNull(nameFormat, "nameFormat");
}
@Override
public Thread newThread(Runnable r) {
String name = String.format(nameFormat, threadNumber.incrementAndGet());
return new FastThreadLocalThread(r, name);
}
}
| 30.48
| 80
| 0.769029
|
8e47248c23a30066e2a4581e857dfd5f1b3f79a7
| 581
|
package LoginScreen;
import java.sql.*;
import javax.swing.*;
public class MySqlConnect {
Connection conn=null;
public static Connection ConnectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbms_phone1","root","applesauce");
JOptionPane.showMessageDialog(null,"Connected to database");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
return null;
}
}
}
| 32.277778
| 120
| 0.616179
|
47a99b239243f74318671b486c990b2d5691a821
| 475
|
package org.rockyang.blockj.client.rpc;
import org.rockyang.blockj.base.model.Message;
import org.rockyang.blockj.base.model.Wallet;
import java.math.BigDecimal;
import java.util.List;
/**
* @author yangjian
*/
public interface BlockjService {
String newWallet();
List<Wallet> walletList();
BigDecimal getBalance(String address);
String sendMessage(String from, String to, BigDecimal value, String param);
Message getMessage(String cid);
Long chainHead();
}
| 18.269231
| 76
| 0.762105
|
1a4d9a44ee41a6f9f14c2a5325ddf1f4d82b046e
| 634
|
package com.iterlife.zeus.leetcode.dp;
/**
* @desc:https://leetcode-cn.com/problems/contiguous-sequence-lcci/
* @author: lujie
* @version: V1.0.0
* @datetime: 2021/8/21 23:53
**/
public class ContiguousSequenceLcci {
}
class ContiguousSequenceLcciSolution {
public int maxSubArray(int[] nums) {
int sum = nums[0], result = nums[0];
for (int i = 1; i < nums.length; ++i) {
if (sum + nums[i] > nums[i]) {
sum += nums[i];
} else {
sum = nums[i];
}
result = result > sum ? result : sum;
}
return result;
}
}
| 21.862069
| 67
| 0.525237
|
7d60a0dfde6a329ba1201c4dec07a60e65178448
| 4,169
|
package com.faithfulmc.hardcorefactions.faction.argument;
import com.faithfulmc.hardcorefactions.ConfigurationService;
import com.faithfulmc.hardcorefactions.HCF;
import com.faithfulmc.hardcorefactions.faction.claim.Claim;
import com.faithfulmc.hardcorefactions.faction.type.ClaimableFaction;
import com.faithfulmc.hardcorefactions.faction.type.Faction;
import com.faithfulmc.hardcorefactions.faction.type.PlayerFaction;
import com.faithfulmc.util.command.CommandArgument;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class FactionClaimsArgument extends CommandArgument {
private final HCF plugin;
public FactionClaimsArgument(HCF plugin) {
super("claims", "View all claims for a faction.");
this.plugin = plugin;
}
public String getUsage(String label) {
return "" + '/' + label + ' ' + this.getName() + " [factionName]";
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Faction targetFaction;
PlayerFaction selfFaction = sender instanceof Player ? plugin.getFactionManager().getPlayerFaction((Player) sender) : null;
if (args.length < 2) {
if (!(sender instanceof Player)) {
sender.sendMessage(ConfigurationService.RED + "Usage: " + getUsage(label));
return true;
}
else if (selfFaction == null) {
sender.sendMessage(ConfigurationService.RED + "You are not in a faction.");
return true;
}
else {
targetFaction = selfFaction;
}
} else {
Faction faction = plugin.getFactionManager().getContainingFaction(args[1]);
if (faction == null) {
sender.sendMessage(ConfigurationService.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found.");
return true;
} else if (!(faction instanceof ClaimableFaction)) {
sender.sendMessage(ConfigurationService.RED + "You can only check the claims of factions that can have claims.");
return true;
} else {
targetFaction = faction;
}
}
Collection<Claim> claims = ((ClaimableFaction) targetFaction).getClaims();
if (claims.isEmpty()) {
sender.sendMessage(ConfigurationService.RED + "Faction " + targetFaction.getDisplayName(sender) + ConfigurationService.RED + " has no claimed land.");
} else if (sender instanceof Player && !sender.isOp() && targetFaction instanceof PlayerFaction && ((PlayerFaction) targetFaction).getHome() == null && (selfFaction == null || !selfFaction.equals(targetFaction))) {
sender.sendMessage(ConfigurationService.RED + "You cannot view the claims of " + targetFaction.getDisplayName(sender) + ConfigurationService.RED + " because their home is unset.");
} else {
sender.sendMessage(ConfigurationService.YELLOW + "Claims of " + targetFaction.getDisplayName(sender));
for (Claim claim : claims) {
sender.sendMessage(ConfigurationService.GRAY + " " + claim.getFormattedName());
}
}
return true;
}
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
if (args.length != 2 || !(sender instanceof Player)) {
return Collections.emptyList();
}
if (args[1].isEmpty()) {
return null;
}
Player player = (Player) sender;
ArrayList<String> results = new ArrayList<String>(this.plugin.getFactionManager().getFactionNameMap().keySet());
for (Player target : Bukkit.getOnlinePlayers()) {
if (!player.canSee(target) || results.contains(target.getName())) {
continue;
}
results.add(target.getName());
}
return results;
}
}
| 46.322222
| 222
| 0.646198
|
b82e5f10f13eab949f6c0f5f83b619bc42c3c6fb
| 719
|
package se.bluebrim.desktop.jdbc.connect;
import java.util.List;
import org.junit.Test;
import se.bluebrim.crud.client.AbstractPanel;
import se.bluebrim.crud.client.AbstractPanelTest;
/**
*
* @author GStack
*
*/
public class JdbcConnectionPanelTest extends AbstractPanelTest
{
public static void main(String[] args)
{
new JdbcConnectionPanelTest().testCreateGui();
}
@Test
public void testCreateGui()
{
List<AbstractPanel> panels = openTestWindow(JdbcConnectionPanel.class);
JdbcConnectionModel jdbcConnection = new JdbcConnectionModel();
((AbstractPanel)panels.get(0)).setModel(jdbcConnection);
((AbstractPanel)panels.get(1)).setModel(jdbcConnection);
}
}
| 22.46875
| 74
| 0.730181
|
4b013db196958fec7f7b6edd04464dcb08a4a64a
| 2,104
|
package mad.location.manager.lib.Filters;
/**
* Created by lezh1k on 2/13/18.
*/
public class GeoHash {
private static long interleave(long x, long y) {
x = (x | (x << 16)) & 0x0000ffff0000ffffL;
x = (x | (x << 8)) & 0x00ff00ff00ff00ffL;
x = (x | (x << 4)) & 0x0f0f0f0f0f0f0f0fL;
x = (x | (x << 2)) & 0x3333333333333333L;
x = (x | (x << 1)) & 0x5555555555555555L;
y = (y | (y << 16)) & 0x0000ffff0000ffffL;
y = (y | (y << 8)) & 0x00ff00ff00ff00ffL;
y = (y | (y << 4)) & 0x0f0f0f0f0f0f0f0fL;
y = (y | (y << 2)) & 0x3333333333333333L;
y = (y | (y << 1)) & 0x5555555555555555L;
return x | (y << 1);
//use pdep instructions
// return _pdep_u64(x, 0x5555555555555555) | _pdep_u64(y, 0xaaaaaaaaaaaaaaaa);
}
public static long encode_u64(double lat, double lon, int prec) {
lat = lat/180.0 + 1.5;
lon = lon/360.0 + 1.5;
long ilat = Double.doubleToRawLongBits(lat);
long ilon = Double.doubleToRawLongBits(lon);
ilat >>= 20;
ilon >>= 20;
ilat &= 0x00000000ffffffffL;
ilon &= 0x00000000ffffffffL;
return interleave(ilat, ilon) >> (GEOHASH_MAX_PRECISION-prec)*5;
}
static final char base32Table[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
public static final int GEOHASH_MAX_PRECISION = 12;
public static String geohash_str(long geohash, int prec /*hack. we don't need it, but java hasn't unsigned values*/) {
StringBuffer buff = new StringBuffer(GEOHASH_MAX_PRECISION);
geohash >>= 4; //cause we don't need last 4 bits. that's strange, I thought we don't need first 4 bits %)
geohash &= 0x0fffffffffffffffl; //we don't need sign here
while (prec-- > 0){
buff.append(base32Table[(int)(geohash & 0x1f)]);
geohash >>= 5;
}
return buff.reverse().toString();
}
}
| 36.275862
| 122
| 0.534696
|
fa793f3d414f1ca8958f21e2bdb589c2bd517f03
| 1,872
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.metron.performance.load;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SendToKafkaTest {
@Test
public void testWritesCorrectNumber() {
ExecutorService executor = ForkJoinPool.commonPool();
AtomicLong numSent = new AtomicLong(0);
long expectedSent = 100;
SendToKafka sender = new SendToKafka(null, expectedSent, 10, () -> "msg", executor, numSent, ThreadLocal.withInitial(() -> null) ) {
@Override
protected Future<?> sendToKafka(KafkaProducer producer, String kafkaTopic, String message) {
assertEquals(message, "msg");
return ForkJoinPool.commonPool().submit(() -> {
numSent.incrementAndGet();
});
}
};
sender.run();
assertEquals(numSent.get(), expectedSent);
}
}
| 36.705882
| 136
| 0.73344
|
4bb7ff3bc5a1c0110ba18f461c930fa9c64dcae9
| 96
|
package uk.gov.companieshouse.api.accounts.enumeration;
public enum Parent {
SMALL_FULL
}
| 13.714286
| 55
| 0.770833
|
1fdbd3ed64b7f0bd955594d3a114df62fe5f3cb1
| 1,991
|
package org.rcsb.cif.schema.mm;
import org.rcsb.cif.model.*;
import org.rcsb.cif.schema.*;
import javax.annotation.Generated;
/**
* Data items in the CHEM_COMP_PLANE_ATOM category enumerate the
* atoms in a plane within a chemical component.
*/
@Generated("org.rcsb.cif.schema.generator.SchemaGenerator")
public class ChemCompPlaneAtom extends DelegatingCategory {
public ChemCompPlaneAtom(Category delegate) {
super(delegate);
}
@Override
protected Column createDelegate(String columnName, Column column) {
switch (columnName) {
case "atom_id":
return getAtomId();
case "comp_id":
return getCompId();
case "plane_id":
return getPlaneId();
case "dist_esd":
return getDistEsd();
default:
return new DelegatingColumn(column);
}
}
/**
* The ID of an atom involved in the plane.
*
* This data item is a pointer to _chem_comp_atom.atom_id in the
* CHEM_COMP_ATOM category.
* @return StrColumn
*/
public StrColumn getAtomId() {
return delegate.getColumn("atom_id", DelegatingStrColumn::new);
}
/**
* This data item is a pointer to _chem_comp.id in the CHEM_COMP
* category.
* @return StrColumn
*/
public StrColumn getCompId() {
return delegate.getColumn("comp_id", DelegatingStrColumn::new);
}
/**
* This data item is a pointer to _chem_comp_plane.id in the
* CHEM_COMP_PLANE category.
* @return StrColumn
*/
public StrColumn getPlaneId() {
return delegate.getColumn("plane_id", DelegatingStrColumn::new);
}
/**
* This data item is the standard deviation of the
* out-of-plane distance for this atom.
* @return FloatColumn
*/
public FloatColumn getDistEsd() {
return delegate.getColumn("dist_esd", DelegatingFloatColumn::new);
}
}
| 27.652778
| 74
| 0.624812
|
78074bd08bbad28ffc765eab728a3879373a7419
| 2,225
|
package com.sample.tests.testng;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.sample.beans.ITestData;
import com.sample.framework.Configuration;
import com.sample.framework.Driver;
import com.sample.framework.ui.PageFactory;
import com.sample.tests.pages.SearchPage;
import com.sample.tests.pages.SearchResultsPage;
@Test
@ContextConfiguration(locations = { "classpath:spring-config.xml" })
public class SampleSpringTestNGTest extends AbstractTestNGSpringContextTests {
private WebDriver driver;
@Autowired
ITestData testData;
@DataProvider(name = "spring_provider")
public Object[][] createData() {
return testData.getData();
}
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
DesiredCapabilities cap = new DesiredCapabilities();
Driver.add(Configuration.get("browser"), cap);
driver = Driver.current();
driver.get(Configuration.get("url"));
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
driver.quit();
}
@Test(dataProvider = "spring_provider")
public void testSampleSpringSearch(String destination, boolean isBusiness) throws Exception {
SearchPage searchPage = PageFactory.init(driver, SearchPage.class);
searchPage.editDestination.setText(destination);
searchPage.buttonDownShevron.click();
searchPage.buttonTodaysDate.click();
SearchResultsPage searchResultsPage = searchPage
.setTravelPurpose(isBusiness).buttonSubmit.click(SearchResultsPage.class);
searchResultsPage.editDestination.click();
Assert.assertTrue(searchResultsPage.isTextPresent(destination));
searchResultsPage.captureScreenShot("./image-" + destination + ".png");
}
}
| 39.035088
| 97
| 0.754157
|
b4ab07d511ca79090c656ac84ab242731ccd1d87
| 1,957
|
package jp.ysrken.kacs.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import jp.ysrken.kacs.DatabaseService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
@WebServlet(name = "WeaponTypes", urlPatterns = { "/weapon-types" })
public class WeaponTypes extends HttpServlet {
/**
* 装備の種類一覧を返す
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// データベースを確認する
DatabaseService.initialize(getServletContext());
DatabaseService database = DatabaseService.getDatabase();
if (database == null) {
response.sendError(500);
return;
}
// パラメーターを確認する
String category = request.getParameter("category");
String short_name_flg = request.getParameter("short_name_flg");
System.out.println("/weapon-types?category=" + category + "&short_name_flg=" + short_name_flg);
// クエリを実行する
String tempQuery1 = (short_name_flg != null && short_name_flg.equals("1") ? "short_name as name" : "name");
String tempQuery2 = "WHERE weapon_type.name IN (SELECT type FROM weapon_category WHERE category=?)";
List<Map<String, Object>> result;
if (category == null || category.equals("Normal")){
result = database.select("SELECT id, " + tempQuery1 + " FROM weapon_type WHERE name <> 'なし' ORDER BY id");
} else {
String query = "SELECT id, " + tempQuery1 + " FROM weapon_type " + tempQuery2 + "ORDER BY id";
result = database.select(query, category);
}
// 結果をJSONで返却する
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
ObjectMapper mapper = new ObjectMapper();
response.getWriter().println(mapper.writeValueAsString(result));
}
}
| 34.333333
| 109
| 0.73582
|
aadfc1a553a803684ae0161dc51620e300ba64ac
| 1,052
|
package com.sequenceiq.cloudbreak.template.views;
public class CustomConfigurationPropertyView {
private String name;
private String value;
private String roleType;
private String serviceType;
public CustomConfigurationPropertyView(String name, String value, String roleType, String serviceType) {
this.name = name;
this.value = value;
this.roleType = roleType;
this.serviceType = serviceType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getRoleType() {
return roleType;
}
public void setRoleType(String roleType) {
this.roleType = roleType;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
}
| 20.230769
| 108
| 0.636882
|
51f63524c1c83665ab972a02ff95ee27ddbe3987
| 599
|
package org.moe.libgdxmissilecommand.ios;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.iosmoe.IOSApplication;
import com.badlogic.gdx.backends.iosmoe.IOSApplicationConfiguration;
public class MyIOSApplication extends IOSApplication {
public MyIOSApplication(ApplicationListener listener, IOSApplicationConfiguration config) {
super(listener, config);
}
@Override
public void setApplicationLogger(ApplicationLogger applicationLogger) {
super.setApplicationLogger(new MyLogger());
}
}
| 31.526316
| 95
| 0.797997
|
0f9f0f41e038a6da0d60a569780bc947ab276b74
| 5,105
|
/*
* Copyright 2012-2018, the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.flux.guice.module;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import javax.inject.Named;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jersey2.InstrumentedResourceMethodApplicationListener;
import com.codahale.metrics.jetty9.InstrumentedHandler;
import com.codahale.metrics.jmx.JmxReporter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.flipkart.flux.filter.CORSFilter;
import com.flipkart.flux.filter.RequestLoggingFilter;
import com.flipkart.flux.metrics.MetricsClientImpl;
import com.flipkart.flux.metrics.iface.MetricsClient;
import com.flipkart.flux.resource.DeploymentUnitResource;
import com.flipkart.flux.resource.ExecutionApiResource;
import com.flipkart.flux.resource.StatusResource;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
/*
* ExecutionContainer Module prepares execution node FluxRuntime. It prepares api servers and resources at startup.
* */
public class ExecutionContainerModule extends AbstractModule {
@Override
public void configure() {
bind(MetricsClient.class).to(MetricsClientImpl.class).in(Singleton.class);
}
/**
* Creates the Jetty server instance for the Flux Execution API endpoint.
*
* @return Jetty Server instance
*/
@Named("ExecutionAPIJettyServer")
@Provides
@Singleton
Server getExecutionAPIJettyServer(@Named("Execution.Node.Api.service.port") int port,
@Named("ExecutionAPIResourceConfig") ResourceConfig resourceConfig,
@Named("Execution.Node.Api.service.acceptors") int acceptorThreads,
@Named("Execution.Node.Api.service.selectors") int selectorThreads,
@Named("Execution.Node.Api.service.workers") int maxWorkerThreads,
ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
provider.setMapper(objectMapper);
resourceConfig.register(provider);
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(maxWorkerThreads);
Server server = new Server(threadPool);
ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
http.setPort(port);
server.addConnector(http);
ServletContextHandler context = new ServletContextHandler(server, "/*");
ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
context.addServlet(servlet, "/*");
final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
handler.setName("Execution-Runtime-Metrics-"); // give a unique name that doesnot conflict with other webapps registered in the same metrics registry
handler.setHandler(context);
server.setHandler(handler);
server.setStopAtShutdown(true);
return server;
}
@Named("ExecutionAPIResourceConfig")
@Provides
@Singleton
public ResourceConfig getAPIResourceConfig(ExecutionApiResource executionApiResource, DeploymentUnitResource deploymentUnitResource,
StatusResource statusResource, MetricRegistry metricRegistry) {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(new InstrumentedResourceMethodApplicationListener(metricRegistry));
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
resourceConfig.register(executionApiResource);
resourceConfig.register(deploymentUnitResource);
resourceConfig.register(statusResource);
resourceConfig.register(CORSFilter.class);
resourceConfig.register(RequestLoggingFilter.class);
jmxReporter.start();
return resourceConfig;
}
}
| 45.176991
| 157
| 0.74143
|
31a580eaa57dd116122750aaa53a5ba2a73d7ee4
| 4,004
|
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
public class Main {
public static void main(String[] args) throws Exception {
JSONParser parser = new JSONParser();
JSONObject jsonObject;
JSONArray nodes;
JSONArray links;
Map<String,Vertex> vertices = new HashMap<>();
Graph g;
try {
jsonObject = (JSONObject) parser.parse(new FileReader("C:\\Users\\ibrah\\Desktop\\Uunet.json"));
// save the results from reading nodes and links into a JSON arrays
nodes = (JSONArray) jsonObject.get("nodes");
links =(JSONArray) jsonObject.get("links") ;
// create a map that has id as a key and json object
Map<String, JSONObject> mappedNodes = new HashMap<String, JSONObject>();
for (Object tmpNode : nodes){
JSONObject tmpNode1 = (JSONObject) tmpNode;
mappedNodes.put(tmpNode1.get("id").toString(), tmpNode1);
vertices.put(tmpNode1.get("id").toString(),new Vertex( Double.parseDouble(tmpNode1.get("Latitude").toString()),
Double.parseDouble(tmpNode1.get("Longitude").toString()),
tmpNode1.get("id").toString()));
}
g= new Graph(vertices);
for(Object linkObj : links) {
JSONObject link = (JSONObject) linkObj;
JSONObject source = mappedNodes.get(link.get("source").toString());
JSONObject target = mappedNodes.get(link.get("target").toString());
double srcLatitude = Double.parseDouble(source.get("Latitude").toString());
double srcLongitude = Double.parseDouble(source.get("Longitude").toString());
double dstLatitude = Double.parseDouble(target.get("Latitude").toString());
double dstLongitude = Double.parseDouble(target.get("Longitude").toString());
double distance = getDistance(srcLatitude, srcLongitude, dstLatitude, dstLongitude);
System.out.println("Distance between "+ " source " + source.get("id")+ "----- and destination -----> "
+ target.get("id") + " ------ " + distance);
//ReadUnorientedGraphFromEdgeList need to take more parameters
g.addUnorientedEdge(source.get("id").toString(),target.get("id").toString(),distance );
long start=System.currentTimeMillis();
/*needs to be changed so that it doesn't take node numbers*/
LinkedList<String> res=Dijkstra.doDijkstra(g,source.get("id").toString(), target.get("id").toString());
long end = System.currentTimeMillis();
if(res!=null){
System.out.println("length="+res.pollLast());
System.out.println("path");
for(String i:res)
System.out.println(i);
System.out.println("Time to find shortest path (first time) :" + (end-start) + "ms");
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static double getDistance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(degreeToRadiens(lat1)) * Math.sin(degreeToRadiens(lat2)) + Math.cos(degreeToRadiens(lat1)) * Math.cos(degreeToRadiens(lat2)) * Math.cos( degreeToRadiens(theta));
dist = Math.acos(dist);
dist =radiensTodegrees(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
return (dist);
}
private static double degreeToRadiens(double degree) {
return (degree * Math.PI / 180.0);
}
private static double radiensTodegrees(double radines) {
return (radines * 180 / Math.PI);
}
}
| 44.988764
| 192
| 0.581668
|
fb75240035159b8b5ffe9861316394af1e8db179
| 11,388
|
package com.synopsys.integration.alert.channel.jira.server.environment;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.env.Environment;
import com.synopsys.integration.alert.api.common.model.AlertConstants;
import com.synopsys.integration.alert.channel.jira.server.database.accessor.JiraServerGlobalConfigAccessor;
import com.synopsys.integration.alert.channel.jira.server.validator.JiraServerGlobalConfigurationValidator;
import com.synopsys.integration.alert.descriptor.api.model.ChannelKeys;
import com.synopsys.integration.alert.environment.EnvironmentProcessingResult;
import com.synopsys.integration.alert.environment.EnvironmentVariableUtility;
import com.synopsys.integration.alert.test.common.EnvironmentVariableMockingUtil;
class JiraServerEnvironmentVariableHandlerTest {
@Test
void testSetInEnvironment() {
Environment environment = Mockito.mock(Environment.class);
JiraServerGlobalConfigAccessor configAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(configAccessor.getConfigurationCount()).thenReturn(0L);
Set<String> expectedVariableNames = JiraServerEnvironmentVariableHandler.VARIABLE_NAMES;
String disablePluginCheck = "true";
String url = "http://test.jira.server.example.com";
String passwordValue = "a test value";
String username = "testuser";
Predicate<String> hasEnvVarCheck = (variableName) -> !JiraServerEnvironmentVariableHandler.VARIABLE_NAMES.contains(variableName);
Mockito.when(environment.containsProperty(Mockito.anyString())).thenReturn(Boolean.TRUE);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.DISABLE_PLUGIN_KEY, disablePluginCheck);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.URL_KEY, url);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.PASSWORD_KEY, passwordValue);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.USERNAME_KEY, username);
EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
JiraServerGlobalConfigAccessor jiraServerGlobalConfigAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(jiraServerGlobalConfigAccessor.getConfigurationByName(Mockito.anyString())).thenReturn(Optional.empty());
JiraServerGlobalConfigurationValidator validator = new JiraServerGlobalConfigurationValidator(jiraServerGlobalConfigAccessor);
JiraServerEnvironmentVariableHandler jiraServerEnvironmentVariableHandler = new JiraServerEnvironmentVariableHandler(configAccessor, environmentVariableUtility, validator);
EnvironmentProcessingResult result = jiraServerEnvironmentVariableHandler.updateFromEnvironment();
assertEquals(ChannelKeys.JIRA_SERVER.getDisplayName(), jiraServerEnvironmentVariableHandler.getName());
assertEquals(expectedVariableNames, jiraServerEnvironmentVariableHandler.getVariableNames());
assertTrue(result.hasValues());
assertEquals(disablePluginCheck, result.getVariableValue(JiraServerEnvironmentVariableHandler.DISABLE_PLUGIN_KEY).orElse("Disable plugin check value missing"));
assertEquals(url, result.getVariableValue(JiraServerEnvironmentVariableHandler.URL_KEY).orElse("Url value missing"));
assertEquals(AlertConstants.MASKED_VALUE, result.getVariableValue(JiraServerEnvironmentVariableHandler.PASSWORD_KEY).orElse("Password value missing"));
assertEquals(username, result.getVariableValue(JiraServerEnvironmentVariableHandler.USERNAME_KEY).orElse("Username value missing"));
}
@Test
void testSetInEnvironmentURLMissing() {
Environment environment = Mockito.mock(Environment.class);
JiraServerGlobalConfigAccessor configAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(configAccessor.getConfigurationCount()).thenReturn(0L);
Set<String> expectedVariableNames = JiraServerEnvironmentVariableHandler.VARIABLE_NAMES;
String disablePluginCheck = "true";
String passwordValue = "a test value";
String username = "testuser";
Predicate<String> hasEnvVarCheck = (variableName) -> !JiraServerEnvironmentVariableHandler.VARIABLE_NAMES.contains(variableName);
Mockito.when(environment.containsProperty(Mockito.anyString())).thenReturn(Boolean.TRUE);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.DISABLE_PLUGIN_KEY, disablePluginCheck);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.PASSWORD_KEY, passwordValue);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.USERNAME_KEY, username);
EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
JiraServerGlobalConfigAccessor jiraServerGlobalConfigAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(jiraServerGlobalConfigAccessor.getConfigurationByName(Mockito.anyString())).thenReturn(Optional.empty());
JiraServerGlobalConfigurationValidator validator = new JiraServerGlobalConfigurationValidator(jiraServerGlobalConfigAccessor);
JiraServerEnvironmentVariableHandler jiraServerEnvironmentVariableHandler = new JiraServerEnvironmentVariableHandler(configAccessor, environmentVariableUtility, validator);
EnvironmentProcessingResult result = jiraServerEnvironmentVariableHandler.updateFromEnvironment();
assertEquals(ChannelKeys.JIRA_SERVER.getDisplayName(), jiraServerEnvironmentVariableHandler.getName());
assertEquals(expectedVariableNames, jiraServerEnvironmentVariableHandler.getVariableNames());
assertFalse(result.hasValues());
}
@Test
void testSetInEnvironmentUserNameMissing() {
Environment environment = Mockito.mock(Environment.class);
JiraServerGlobalConfigAccessor configAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(configAccessor.getConfigurationCount()).thenReturn(0L);
Set<String> expectedVariableNames = JiraServerEnvironmentVariableHandler.VARIABLE_NAMES;
String disablePluginCheck = "true";
String url = "http://test.jira.server.example.com";
String passwordValue = "a test value";
Predicate<String> hasEnvVarCheck = (variableName) -> !JiraServerEnvironmentVariableHandler.VARIABLE_NAMES.contains(variableName);
Mockito.when(environment.containsProperty(Mockito.anyString())).thenReturn(Boolean.TRUE);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.DISABLE_PLUGIN_KEY, disablePluginCheck);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.URL_KEY, url);
EnvironmentVariableMockingUtil.addEnvironmentVariableValueToMock(environment, hasEnvVarCheck, JiraServerEnvironmentVariableHandler.PASSWORD_KEY, passwordValue);
EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
JiraServerGlobalConfigAccessor jiraServerGlobalConfigAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(jiraServerGlobalConfigAccessor.getConfigurationByName(Mockito.anyString())).thenReturn(Optional.empty());
JiraServerGlobalConfigurationValidator validator = new JiraServerGlobalConfigurationValidator(jiraServerGlobalConfigAccessor);
JiraServerEnvironmentVariableHandler jiraServerEnvironmentVariableHandler = new JiraServerEnvironmentVariableHandler(configAccessor, environmentVariableUtility, validator);
EnvironmentProcessingResult result = jiraServerEnvironmentVariableHandler.updateFromEnvironment();
assertEquals(ChannelKeys.JIRA_SERVER.getDisplayName(), jiraServerEnvironmentVariableHandler.getName());
assertEquals(expectedVariableNames, jiraServerEnvironmentVariableHandler.getVariableNames());
assertFalse(result.hasValues());
}
@Test
void testMissingFromEnvironment() {
Environment environment = Mockito.mock(Environment.class);
JiraServerGlobalConfigAccessor configAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(configAccessor.getConfigurationCount()).thenReturn(0L);
EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
JiraServerGlobalConfigAccessor jiraServerGlobalConfigAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(jiraServerGlobalConfigAccessor.getConfigurationByName(Mockito.anyString())).thenReturn(Optional.empty());
JiraServerGlobalConfigurationValidator validator = new JiraServerGlobalConfigurationValidator(jiraServerGlobalConfigAccessor);
JiraServerEnvironmentVariableHandler jiraServerEnvironmentVariableHandler = new JiraServerEnvironmentVariableHandler(configAccessor, environmentVariableUtility, validator);
EnvironmentProcessingResult result = jiraServerEnvironmentVariableHandler.updateFromEnvironment();
assertEquals(ChannelKeys.JIRA_SERVER.getDisplayName(), jiraServerEnvironmentVariableHandler.getName());
assertFalse(result.hasValues());
}
@Test
void testConfigPresent() {
Environment environment = Mockito.mock(Environment.class);
JiraServerGlobalConfigAccessor configAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(configAccessor.getConfigurationCount()).thenReturn(1L);
EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
JiraServerGlobalConfigAccessor jiraServerGlobalConfigAccessor = Mockito.mock(JiraServerGlobalConfigAccessor.class);
Mockito.when(jiraServerGlobalConfigAccessor.getConfigurationByName(Mockito.anyString())).thenReturn(Optional.empty());
JiraServerGlobalConfigurationValidator validator = new JiraServerGlobalConfigurationValidator(jiraServerGlobalConfigAccessor);
JiraServerEnvironmentVariableHandler jiraServerEnvironmentVariableHandler = new JiraServerEnvironmentVariableHandler(configAccessor, environmentVariableUtility, validator);
EnvironmentProcessingResult result = jiraServerEnvironmentVariableHandler.updateFromEnvironment();
assertEquals(ChannelKeys.JIRA_SERVER.getDisplayName(), jiraServerEnvironmentVariableHandler.getName());
assertFalse(result.hasValues());
}
}
| 78.537931
| 180
| 0.820864
|
13ad81eff2a3fdb20d98937553afe9d76f337a88
| 172
|
package nc.scap.dsm.material;
import java.io.Serializable;
public class MaterialListWinCtrl implements Serializable {
private static final long serialVersionUID = -1;
}
| 34.4
| 58
| 0.80814
|
800b4599c6c1f456afc6e029bc59b69ad76dc6f1
| 17,207
|
package com.lazybattley.phonetracker.Dashboard.GoToMap;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.lazybattley.phonetracker.HelperClasses.CurrentLocationHelperClass;
import com.lazybattley.phonetracker.HelperClasses.SignUpHelperClass;
import com.lazybattley.phonetracker.R;
import com.lazybattley.phonetracker.RecyclerViewAdapters.CurrentLocationAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.lazybattley.phonetracker.Dashboard.MainDashBoardActivity.ACTIVATED;
import static com.lazybattley.phonetracker.Dashboard.MainDashBoardActivity.USERS;
import static com.lazybattley.phonetracker.Dashboard.MainDashBoardActivity.USER_DETAIL;
public class MapCurrentLocationActivity extends FragmentActivity implements OnMapReadyCallback, CurrentLocationAdapter.OnPersonClick, MapViewCurrentLocationInterface, PhoneCurrentLocationInterface {
private static final String TAG = "MapCurrentLocationActiv";
private GoogleMap mMap;
private List<CurrentLocationHelperClass> locationDetails;
private CurrentLocationAdapter adapter;
private MarkerOptions[] markers;
private final String ZOOM_LEVEL = "zoom";
private SharedPreferences.Editor editor;
private MapCurrentLocationRecyclerView recyclerViewData;
private Toast toast;
private ProgressBar currentLocation_progressBar;
private int prevActivated = -1, activatedUserIndex = -1 ,zoomLevel;
private CurrentPhoneLocationMap currentPhoneLocationMap;
private boolean multipleMarker, swapButtonImage, activatedAUser, tracking, dataReady;
private FloatingActionButton currentLocation_getCurrentLocation;
private boolean first = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_current_location);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
currentLocation_getCurrentLocation = findViewById(R.id.currentLocation_getCurrentLocation);
currentPhoneLocationMap = new CurrentPhoneLocationMap(this, this);
markers = new MarkerOptions[2];
currentLocation_progressBar = findViewById(R.id.currentLocation_progressBar);
Log.i(TAG, "onCreate: ");
locationDetails = new ArrayList<>();
recyclerViewInit();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
zoomLevel = preferences.getInt(ZOOM_LEVEL, 16);
editor = preferences.edit();
initializeSeekBar();
}
@Override
public void ownerCurrentLocation(LatLng location) {
markers[1] = new MarkerOptions().position(location).title("Current Location");
markers[1].icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
multipleMarkerManager();
}
public void ownPhoneLocationTracker(View view) {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
handleClickCurrentLocation();
}else{
if(toast != null){
toast.cancel();
}
toast = Toast.makeText(this, "Please turn on your GPS", Toast.LENGTH_SHORT);
toast.show();
}
}
private void handleClickCurrentLocation() {
if (!swapButtonImage) {
currentLocation_getCurrentLocation.setImageResource(R.drawable.cancel_button);
swapButtonImage = true;
currentPhoneLocationMap.trackOwnDevice();
multipleMarker = true;
} else {
currentLocation_getCurrentLocation.setImageResource(R.drawable.ic_current_location);
swapButtonImage = false;
currentPhoneLocationMap.stopTrackingOwnDevice();
multipleMarker = false;
}
}
private void multipleMarkerManager() {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear();
mMap.addMarker(markers[1]);
if (markers[0] != null) {
mMap.addMarker(markers[0]);
builder.include(markers[0].getPosition());
}
builder.include(markers[1].getPosition());
LatLngBounds bounds = builder.build();
if (activatedAUser) {
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100), 2000, null);
} else {
mMap.moveCamera(CameraUpdateFactory.newLatLng(markers[1].getPosition()));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markers[1].getPosition(), zoomLevel));
}
}
private void recyclerViewInit() {
// Log.i(TAG, "recyclerViewInit: ");
RecyclerView currentLocation_summary = findViewById(R.id.currentLocation_summary);
adapter = new CurrentLocationAdapter(this);
currentLocation_summary.setAdapter(adapter);
currentLocation_summary.setLayoutManager(new LinearLayoutManager(this));
recyclerViewData = new MapCurrentLocationRecyclerView(this);
recyclerViewData.beginInitializeRecyclerViewData();
}
private void initializeSeekBar() {
// Log.i(TAG, "initializeSeekBar: ");
SeekBar currentLocation_zoom = findViewById(R.id.currentLocation_zoom);
currentLocation_zoom.setProgress(zoomLevel);
currentLocation_zoom.setMax(19);
currentLocation_zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
zoomLevel = i + 1;
editor.putInt(ZOOM_LEVEL, zoomLevel);
editor.apply();
if (activatedUserIndex != -1) {
updateMapFocus();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
@Override
public void setRecyclerViewData(List<CurrentLocationHelperClass> newCurrentLocation) {
currentLocation_progressBar.setVisibility(View.INVISIBLE);
locationDetails.clear();
locationDetails.addAll(newCurrentLocation);
adapter.updateRecyclerView(locationDetails);
dataReady = true;
if (tracking) {
updateMapFocus();
}
}
@Override
public void onPersonClick(int position) {
// Log.i(TAG, "onPersonClick: ");
if (dataReady) {
// mMap.clear();
activatedUserIndex = position;
updateMapFocus();
tracking = true;
activateTracking();
recyclerViewData.trackDevice(position);
} else {
Toast.makeText(this, R.string.current_location_summary_loading, Toast.LENGTH_SHORT).show();
}
}
private void activateTracking() {
// Log.i(TAG, "activateTracking: ");
if (prevActivated != -1) {
deactivateTracker(prevActivated);
recyclerViewData.removeTracking(prevActivated);
}
prevActivated = activatedUserIndex;
activatedAUser = true;
String email = locationDetails.get(activatedUserIndex).getFullName();
DatabaseReference reference = FirebaseDatabase.getInstance()
.getReference(USERS).child(email).child(USER_DETAIL);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
SignUpHelperClass userDetail = snapshot.getValue(SignUpHelperClass.class);
boolean isTraceable = userDetail.isTraceable();
if (isTraceable) {
Map<String, Object> tempMap = new HashMap<>();
tempMap.put(ACTIVATED, true);
reference.updateChildren(tempMap);
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(MapCurrentLocationActivity.this, userDetail.getFullName() + " is now activated.", Toast.LENGTH_SHORT);
adapter.setLiveTracking(activatedUserIndex);
} else {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(MapCurrentLocationActivity.this, userDetail.getFullName() + " did not turn on application.", Toast.LENGTH_SHORT);
adapter.setLiveTracking(-1);
}
toast.show();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void deactivateTracker() {
Log.i(TAG, "deactivateTracker: ");
String email = locationDetails.get(activatedUserIndex).getFullName();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(USERS)
.child(email).child(USER_DETAIL);
Map<String, Object> deactivate = new HashMap<>();
deactivate.put(ACTIVATED, false);
reference.updateChildren(deactivate);
}
private void deactivateTracker(int prevNumber) {
Log.i(TAG, "deactivateTracker: ");
String email = locationDetails.get(prevNumber).getFullName();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(USERS)
.child(email).child(USER_DETAIL);
Map<String, Object> deactivate = new HashMap<>();
deactivate.put(ACTIVATED, false);
reference.updateChildren(deactivate);
}
private void updateMapFocus() {
LatLng loc = locationDetails.get((activatedUserIndex)).getCoordinates();
markers[0] = new MarkerOptions().position(loc).title(locationDetails.get(activatedUserIndex).getFullName());
if (!multipleMarker) {
mMap.clear();
mMap.addMarker(markers[0]);
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, zoomLevel));
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
Log.i(TAG, "onMapReady: ");
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
@Override
public void onBackPressed() {
super.onBackPressed();
Log.i(TAG, "onBackPressed: ");
}
@Override
protected void onPause() {
super.onPause();
if (activatedAUser) {
deactivateTracker();
activatedAUser = false;
}
if(prevActivated != -1){
recyclerViewData.removeTracking(prevActivated);
}
recyclerViewData.removeAvailableLocationCallback();
recyclerViewData.removeAvailabilityChecker();
currentPhoneLocationMap.stopTrackingOwnDevice();
prevActivated = -1;
Log.i(TAG, "onPause: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
currentPhoneLocationMap.stopTrackingOwnDevice();
Log.i(TAG, "onDestroy: ");
}
@Override
protected void onResume() {
super.onResume();
if (!activatedAUser && activatedUserIndex != -1) {
activateTracking();
}
if (multipleMarker) {
currentPhoneLocationMap.trackOwnDevice();
}
if(!first && activatedUserIndex != -1){
recyclerViewData.trackDevice(activatedUserIndex);
}
if(!first){
recyclerViewData.attachAvailabilityChecker();
}
first = false;
Log.i(TAG, "onResume: ");
}
public void backPressed(View view) {
Log.i(TAG, "backPressed: ");
onBackPressed();
}
// ******************************************************* ******************************************************* *******************************************************
public static class CurrentPhoneLocationMap {
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private Context context;
private LocationCallback locationCallback;
private PhoneCurrentLocationInterface currentLocation;
public CurrentPhoneLocationMap(Context context, PhoneCurrentLocationInterface currentLocation) {
this.currentLocation = currentLocation;
this.context = context;
locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
callback();
}
private void callback() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
currentLocation.ownerCurrentLocation(new LatLng(locationResult.getLastLocation().getLatitude(), locationResult.getLastLocation().getLongitude()));
}
};
}
private void trackOwnDevice() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
private void stopTrackingOwnDevice() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
}
}
interface MapViewCurrentLocationInterface {
void setRecyclerViewData(List<CurrentLocationHelperClass> currentLocationList);
}
interface PhoneCurrentLocationInterface {
void ownerCurrentLocation(LatLng location);
}
| 40.678487
| 199
| 0.655198
|
e5e91d4102929ba455b2b917cb324738eb1cd404
| 3,432
|
package collections.RedBlack;
import model.Player;
import java.io.Serializable;
import java.util.ArrayList;
public class RedAndBlackNode <K extends Comparable<K>, V> implements Serializable {
private static final long serialVersionUID = 400003;
/*
private static final int BLACK = 0; // The colors are constant
private static final int RED = 1;
//Crear un enum para los colores, investigar más
private K key;
private V value;
private int color;
private RedAndBlackNode<K, V> parent;
private RedAndBlackNode<K, V> left;
private RedAndBlackNode<K, V> right;
private int numLeft;
private int numRight;
RedAndBlackNode(){
color = BLACK; //El arbol siempre tiene raiz negra
numLeft = 0;
numRight = 0;
parent = null;
left = null;
right = null;
}
RedAndBlackNode(K key,V value){
this();
this.key = key;
this.value = value;
}
//_______________Getters and Setters_______________
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public RedAndBlackNode<K, V> getParent() {
return parent;
}
public void setParent(RedAndBlackNode<K, V> parent) {
this.parent = parent;
}
public RedAndBlackNode<K, V> getLeft() {
return left;
}
public void setLeft(RedAndBlackNode<K, V> left) {
this.left = left;
}
public RedAndBlackNode<K, V> getRight() {
return right;
}
public void setRight(RedAndBlackNode<K, V> right) {
this.right = right;
}
public int getNumLeft() {
return numLeft;
}
public void setNumLeft(int numLeft) {
this.numLeft = numLeft;
}
public int getNumRight() {
return numRight;
}
public void setNumRight(int numRight) {
this.numRight = numRight;
}
//Jamás se usa pero evita Warnings XD
public int getColorRed(){
return RED;
}*/
public Color color;
public K key;
public V val;
public RedAndBlackNode<K, V> parent;
public RedAndBlackNode<K, V> left;
public RedAndBlackNode<K, V> right;
private ArrayList<Player> samePlayers;
public RedAndBlackNode(){
// set RED as default
this.color = Color.RED;
this.key = null;
this.val = null;
this.left = null;
this.right = null;
this.samePlayers = new ArrayList<Player>();
}
public RedAndBlackNode(Color color, K key, V val) {
this.color = color;
this.key = key;
this.val = val;
this.left = null;
this.right = null;
this.samePlayers = new ArrayList<Player>();
}
public ArrayList<Player> getPlayers(){
return samePlayers;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getVal() {
return val;
}
public void setVal(V val) {
this.val = val;
}
public RedAndBlackNode<K, V> getParent() {
return parent;
}
public void setParent(RedAndBlackNode<K, V> parent) {
this.parent = parent;
}
public RedAndBlackNode<K, V> getLeft() {
return left;
}
public void setLeft(RedAndBlackNode<K, V> left) {
this.left = left;
}
public RedAndBlackNode<K, V> getRight() {
return right;
}
public void setRight(RedAndBlackNode<K, V> right) {
this.right = right;
}
}
| 17.510204
| 83
| 0.668706
|
0091a861c23c79f3013940b198591f01ce678bf0
| 2,383
|
/*
* Copyright 2021 DataCanvas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dingodb.calcite.mock;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import io.dingodb.common.table.TableDefinition;
import io.dingodb.meta.Location;
import io.dingodb.meta.MetaService;
import io.dingodb.meta.MetaServiceProvider;
import org.mockito.Mockito;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@AutoService(MetaServiceProvider.class)
public class Mock1MetaServiceProvider implements MetaServiceProvider {
public static final String SCHEMA_NAME = "MOCK1";
public static final String TABLE_1_NAME = "TEST1";
public static final Location LOC_0 = new Location("host1", 26535, "/path1");
public static final Location LOC_1 = new Location("host2", 26535, "/path2");
@Override
public MetaService get() {
MetaService metaService = Mockito.spy(MetaService.class);
try {
when(metaService.getName()).thenReturn(SCHEMA_NAME);
when(metaService.getTableDefinitions()).thenReturn(ImmutableMap.of(
TABLE_1_NAME, TableDefinition.readJson(getClass().getResourceAsStream("/table-test1.json"))
));
when(metaService.getTableKey(anyString())).then(args -> {
String tableName = args.getArgument(0);
return tableName.getBytes(StandardCharsets.UTF_8);
});
} catch (IOException e) {
e.printStackTrace();
}
when(metaService.getPartLocations(TABLE_1_NAME)).thenReturn(ImmutableMap.of(
"0", LOC_0,
"1", LOC_1
));
when(metaService.currentLocation()).thenReturn(LOC_0);
return metaService;
}
}
| 37.234375
| 107
| 0.704574
|
57ad1674fae33cc33ea3ba4cfe1c473b65582c75
| 2,473
|
package com.breiter.seatswapper.model;
import androidx.annotation.NonNull;
public class FlightPassenger implements Comparable<FlightPassenger> {
private String passengerId;
private String passengerSeat;
private String search;
private String flightId;
private boolean isawaiting;
public FlightPassenger(String passengerId, String passengerSeat, String search, String flightId, boolean isawaiting) {
this.passengerId = passengerId;
this.passengerSeat = passengerSeat;
this.search = search;
this.flightId = flightId;
this.isawaiting = isawaiting;
}
public FlightPassenger() {
}
public String getPassengerId() {
return passengerId;
}
public void setPassengerId(String passengerId) {
this.passengerId = passengerId;
}
public String getPassengerSeat() {
return passengerSeat;
}
public void setPassengerSeat(String passengerSeat) {
this.passengerSeat = passengerSeat;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public boolean isIsawaiting() {
return isawaiting;
}
public void setIswaiting(boolean isawaiting) {
this.isawaiting = isawaiting;
}
public String getFlightId() {
return flightId;
}
public void setFlightId(String flightId) {
this.flightId = flightId;
}
//Compare by seat
@Override
public int compareTo(@NonNull FlightPassenger other) {
String seatNumberThis = this.getSearch();
String seatNumberOther = other.getSearch();
//If the seat starts with the same numbers, then sort alphabetically in ascending order (12A, 12B etc.)
if (getDigits(seatNumberThis) == getDigits(seatNumberOther))
return getNonDigits(seatNumberThis).compareTo(getNonDigits(seatNumberOther));
//If the seat numbers start with various numbers then sort them in ascending order (1F, 2B, 12C etc)
else
return getDigits(seatNumberThis) - getDigits(seatNumberOther);
}
//Remove all digits from the string
private String getNonDigits(String s) {
return s.replaceAll("\\d", "");
}
//Remove all digits from the string
private int getDigits(String s) {
String digits = s.replaceAll("\\D+", "");
return Integer.parseInt(digits);
}
}
| 23.330189
| 122
| 0.659927
|
2f65d31ce6698f45fc403af66751d2fb9eef1bb0
| 9,904
|
/*
* Copyright 2012-2019 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.hub.mapping;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.marklogic.hub.HubTestBase;
import com.marklogic.hub.MappingManager;
import com.marklogic.hub.ApplicationConfig;
import com.marklogic.hub.util.FileUtil;
import com.marklogic.hub.util.HubModuleManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ApplicationConfig.class)
public class MappingManagerTest extends HubTestBase {
static Path projectPath = Paths.get(PROJECT_PATH).toAbsolutePath();
private static File projectDir = projectPath.toFile();
private String mappingName = "my-fun-test";
@BeforeEach
public void setup() {
basicSetup();
//clearDatabases(HubConfig.DEFAULT_STAGING_NAME, HubConfig.DEFAULT_FINAL_NAME, HubConfig.DEFAULT_MODULES_DB_NAME);
//installHubModules();
//getPropsMgr().deletePropertiesFile();
adminHubConfig.initHubProject();
}
@AfterEach
public void teardown() {
deleteProjectDir();
}
@Test
public void createMapping() {
//Create our mapping via the exposed java api
ObjectMapper mapper = new ObjectMapper();
Mapping testMap = Mapping.create(mappingName);
testMap.setDescription("This is a test.");
testMap.setSourceContext("/fake/path");
testMap.setTargetEntityType("http://marklogic.com/example/Schema-0.0.2/Person");
HashMap<String, ObjectNode> properties = new HashMap<>();
ObjectNode id = mapper.createObjectNode();
id.put("sourcedFrom", "id");
properties.put("id", id);
ObjectNode name = mapper.createObjectNode();
name.put("sourcedFrom", "name");
properties.put("name", name);
testMap.setProperties(properties);
//we should now have a fully fleshed out, in memory mapping object that was created
//So let's try saving it!
mappingManager.saveMapping(testMap);
//now let's see if it's on disk!
String mappingFileName = testMap.getName() + "-" + testMap.getVersion() + MappingManager.MAPPING_FILE_EXTENSION;
assertTrue(Paths.get((getHubAdminConfig().getHubMappingsDir().toString()), mappingName, mappingFileName).toFile().exists());
}
@Test
public void getMapping() {
copyTestMap();
//here, we're going to get the mapping we just made
Mapping testMap = mappingManager.getMapping(mappingName);
assertTrue(testMap != null);
assertTrue(testMap.getName().equalsIgnoreCase(mappingName));
}
@Test
public void getMappingNames() {
copyTestMap();
//get a list of names to be returned of exiting mappings
ArrayList<String> mappingNames = mappingManager.getMappingsNames();
assertTrue(mappingNames.size() > 0);
}
@Test
public void getMappingFromJSON() {
copyTestMap();
//Now let's get the same mapping, but out of band off disk as JSON
String json = mappingManager.getMappingAsJSON(mappingName);
logger.debug(json);
// is this appropriate, a length check on the json?
//assertTrue(json.length() == 253);
//now let's see if this parses properly
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode node = mapper.readTree(json);
assertTrue(node.get("name").asText().equalsIgnoreCase(mappingName));
} catch (IOException e) {
fail("Can not parse json response.");
}
}
@Test
public void updateMapping() {
copyTestMap();
//Get the mapping, update it, and save the new version back
Mapping testMap = mappingManager.getMapping(mappingName);
//make sure it's the right map
assertTrue(testMap.getVersion() == 1);
assertTrue(testMap.getName().equalsIgnoreCase(mappingName));
//Manipulate it
String newDesc = "This is a new Description.";
testMap.setDescription(newDesc);
String newContext = "/path/is/updated";
testMap.setSourceContext(newContext);
ObjectMapper mapper = new ObjectMapper();
ObjectNode newNode = mapper.createObjectNode();
newNode.put("sourcedFrom", "test");
testMap.getProperties().put("test", newNode);
//Let's save it and auto increment version
mappingManager.saveMapping(testMap, true);
//now let's check the in memory instance
assertTrue(testMap.getVersion() == 2);
assertTrue(testMap.getDescription().equalsIgnoreCase(newDesc));
assertTrue(testMap.getProperties().size() == 3);
assertTrue(testMap.getSourceContext().equalsIgnoreCase(newContext));
//now let's pull the map back from disk and compare it to our in memory
Mapping testMapDisk = mappingManager.getMapping(mappingName);
assertTrue(testMapDisk.getVersion() == testMap.getVersion());
assertTrue(testMapDisk.getDescription().equalsIgnoreCase(newDesc));
assertTrue(testMapDisk.getDescription().equalsIgnoreCase(testMap.getDescription()));
}
@Test
public void getMostRecentMapping() {
copyTestMap();
//add a new version of the map
copySecondTestMap();
//get most recent version of the mapping
Mapping testMap = mappingManager.getMapping(mappingName);
assertTrue(testMap.getVersion() == 2);
}
@Test
public void getMappingByVersion() {
copyTestMap();
//add a new version of the map
copySecondTestMap();
//get an older version of the mapping
Mapping testMap = mappingManager.getMapping(mappingName, 1);
assertTrue(testMap.getVersion() == 1);
}
@Test
public void deleteMapping() {
//reput that mapping from create there
copyTestMap();
//now let's erase the mapping
//check to see if its there
Mapping testMap = mappingManager.getMapping(mappingName);
assertTrue(testMap != null);
//check to make sure its on disk
String mappingFileName = testMap.getName() + "-" + testMap.getVersion() + MappingManager.MAPPING_FILE_EXTENSION;
assertTrue(Paths.get((getHubAdminConfig().getHubMappingsDir().toString()), mappingName, mappingFileName).toFile().exists());
//now let's delete it
mappingManager.deleteMapping(mappingName);
//make sure it's gone off disk
assertFalse(Paths.get((getHubAdminConfig().getHubMappingsDir().toString()), mappingName, mappingFileName).toFile().exists());
}
private void copyTestMap() {
FileUtil.copy(getResourceStream("scaffolding-test/"+mappingName+"-1"+MappingManager.MAPPING_FILE_EXTENSION), getHubAdminConfig().getHubMappingsDir().resolve(mappingName+"/"+mappingName+"-1"+MappingManager.MAPPING_FILE_EXTENSION).toFile());
}
private void copySecondTestMap() {
FileUtil.copy(getResourceStream("scaffolding-test/"+mappingName+"-2"+MappingManager.MAPPING_FILE_EXTENSION), getHubAdminConfig().getHubMappingsDir().resolve(mappingName+"/"+mappingName+"-2"+MappingManager.MAPPING_FILE_EXTENSION).toFile());
}
private void installMappings() {
Path employeeDir = project.getEntityDir("employee");
employeeDir.toFile().mkdirs();
assertTrue(employeeDir.toFile().exists());
FileUtil.copy(getResourceStream("scaffolding-test/employee.entity.json"),
employeeDir.resolve("employee.entity.json").toFile());
Path managerDir = project.getEntityDir("manager");
managerDir.toFile().mkdirs();
assertTrue(managerDir.toFile().exists());
FileUtil.copy(getResourceStream("scaffolding-test/manager.entity.json"), managerDir.resolve("manager.entity.json").toFile());
}
private void updateManagerEntity() {
Path managerDir = project.getEntityDir("manager");
assertTrue(managerDir.toFile().exists());
File targetFile = managerDir.resolve("manager.entity.json").toFile();
FileUtil.copy(getResourceStream("scaffolding-test/manager2.entity.json"), targetFile);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
targetFile.setLastModified(System.currentTimeMillis());
}
private HubModuleManager getPropsMgr() {
String timestampFile = getHubAdminConfig().getHubProject().getUserModulesDeployTimestampFile();
HubModuleManager propertiesModuleManager = new HubModuleManager(timestampFile);
return propertiesModuleManager;
}
}
| 39.146245
| 247
| 0.688106
|
3a2ac36125574f6caedc0d78cfb343024e2cc542
| 1,127
|
package HackerRank.src.Tracks.CoreCS.Algorithms.Warmup.TimeConversion.Java;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] twelvehourtime = scan.next().split(":");
String hour = twelvehourtime[0];
String min = twelvehourtime[1];
String second = twelvehourtime[2].substring(0, 2);
String amOrPm = twelvehourtime[2].substring(2, 4);
scan.close();
if(amOrPm.equals("AM")){
String newHour;
if (hour.equals("12")){
newHour = "00";
}
else{
newHour = hour;
}
System.out.println(newHour + ":" + min + ":" + second);
}
else if (amOrPm.equals("PM")){
int newHour;
int oldHour = Integer.parseInt(hour);
if (oldHour == 12){
newHour = 12;
}
else{
newHour = 12 + oldHour;
}
System.out.println(newHour + ":" + min + ":" + second);
}
}
}
| 29.657895
| 75
| 0.492458
|
39c5861f66ceb8d9e62beced57bd3ba9f89df75a
| 9,826
|
package com.amadeus.jenkins.plugins.unbreakablebuild;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.model.Failure;
import hudson.model.Result;
import hudson.model.Run;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* This object contains the minimal information needed for the unbreakable build
*/
public class UbJenkinsEnvBean {
static final String BITBUCKET_API_VERSION = "1.0";
private static final Logger LOGGER = LoggerFactory.getLogger(UbJenkinsEnvBean.class);
private static final int HTTP_CODE_LOWER_RANGE_OK = 200;
private static final int HTTP_CODE_UPPER_RANGE_KO = 300;
private String bitbucketUrl;
private String projectKey;
private String repositorySlug;
private String refSpec;
private String commitId;
private String jobUrl;
private String isolationZone;
/**
* Build status
*/
enum Status {
SUCCESS, FAILURE
}
/**
* Mandatory environment variables so that the unbreakablebuild works
*/
enum EnvVarName {
SCM_URL, BITBUCKET_PROJECT, BITBUCKET_REPOSITORY, UNBREAKABLE_REFSPEC, COMMIT, JOB_DISPLAY_URL, JOB_NAME,
}
/**
* This constructor will attempt to initialize a UbJenkinsEnvBean with all the
* environment variables.
* <p>
* If one of the env variable is missing, it will fail with
* a @{hudson.model.Failure}
*
* @param envVars the environment variables available in the Run
*/
UbJenkinsEnvBean(EnvVars envVars, Run<?, ?> run) {
List<String> missingEnv = Arrays.stream(EnvVarName.values())
.filter(name -> !envVars.containsKey(name.toString()))
.map(Enum::toString)
.collect(Collectors.toList());
if (!missingEnv.isEmpty()) {
run.setResult(Result.FAILURE);
String message = "These environment variables are missing "
+ String.join(", ", missingEnv) + " and are needed for the unbreakable "
+ "build feature. Please, make sure that your project-repository is registered as an "
+ "Unbreakable build in Bitbucket, and make sure that your instance of the SWB pipeline"
+ " is correctly configured, the build has been marked has failed.";
throw new Failure(message);
}
// this is from the BB plugin (added by SWB change)
bitbucketUrl = envVars.get(EnvVarName.SCM_URL.toString());
projectKey = envVars.get(EnvVarName.BITBUCKET_PROJECT.toString());
repositorySlug = envVars.get(EnvVarName.BITBUCKET_REPOSITORY.toString());
// looks like this : refs/ubuilds/9999
refSpec = envVars.get(EnvVarName.UNBREAKABLE_REFSPEC.toString());
// this is the commit from unbreakable build (already Fast Forward
// Merge)
// From my understanding this code is called from special branch which
// is the actual merge
// So, the commit_id should be the one to use
// and this commit id is coming from the BB plugin (added by SWB change)
// --> from the BitbucketSCMSourceBranch plugin
commitId = envVars.get(EnvVarName.COMMIT.toString());
// --> from the display-url-api plugin
jobUrl = envVars.get(EnvVarName.JOB_DISPLAY_URL.toString());
// the isolation correspond to the parent project
isolationZone = UbUtils.getIsolationZoneName(envVars.get(EnvVarName.JOB_NAME.toString()));
}
/**
* This method will contact bitbucket to notify whether it should merge or
* mark the build result as failed
*
* @param status SUCCEED or FAILURE
* @param logger the Jenkins logger to print in the jenkins console
* @param credentials bitbucket credentials to use UB verbs
* @throws AbortException Will be thrown if the branchName of the UbJenkinsEnvBean is not
* matching the convention
*/
void notifyBitbucket(Status status,
PrintStream logger,
org.apache.http.auth.UsernamePasswordCredentials credentials,
Run<?, ?> run)
throws AbortException {
UbUtils.jenkinsLog(logger, "\n ----- UNBREAKABLE BUILD VERB CALLED ----- \n");
UbBranchPojo ubPojo = UbBranchPojo.fromUbBranchName(refSpec);
if (ubPojo == null) {
throw new AbortException(
"Unbreakable build actions should only be called from "
+ "Unbreakable Build branches (name should match: '"
+ UbBranchPojo.UB_BRANCH_REGEX + "'. Current branch refSpec is '" + refSpec + "'");
}
String mergeRequestId = ubPojo.getMergeRequestId();
String url = generateBitbucketUrl();
UbUtils.jenkinsLog(logger, "calling URL: " + url);
// build payload
String payload = UbUtils.generateBitbucketPayload(jobUrl, isolationZone, mergeRequestId, status.name());
UbUtils.jenkinsLog(logger, "With Payload: \n" + payload);
// query Bitbucket
UbUtils.BitbucketQueryResult bbResult = UbUtils.sendBitbucketNotification(url, payload, credentials);
// analyze the results --> will throw Failure if not OK
analyseBbQueryResult(bbResult, status, logger, run);
// finally manage the failure of the build
if (Status.FAILURE.equals(status)) {
run.setResult(Result.FAILURE);
throw new Failure("Unbreakable build marks the build as failed");
}
}
/**
* Put business logic of handling the bitbucket response
*
* @param bbResult result of the notification
* @param buildStatus status of the build
* @param logger Jenkins logger
*/
private static void analyseBbQueryResult(
UbUtils.BitbucketQueryResult bbResult, Status buildStatus, PrintStream logger, Run<?, ?> run) {
// read results
int statusCode = bbResult.getStatusCode();
String message = bbResult.getMessage();
LOGGER.trace("status Code: {}", statusCode);
boolean isHttpCodeInRangeOk = statusCode >= HTTP_CODE_LOWER_RANGE_OK && statusCode < HTTP_CODE_UPPER_RANGE_KO;
// SUCCESS CASE
if (isHttpCodeInRangeOk && bbResult.getException() == null) {
UbUtils.jenkinsLog(logger, String.format(
"Notification of UB buildStatus: '%s' sent successfully to bitbucket, "
+ "status code: %d, message: '%s'", buildStatus, statusCode, message));
UbUtils.jenkinsLog(logger, "\n ----- UNBREAKABLE BUILD FINISHED ----- \n");
} else if (isHttpCodeInRangeOk) {
UbUtils.jenkinsLog(logger, String.format(
"Notification of UB buildStatus: '%s' sent successfully to bitbucket but with Exception. "
+ "Status code: %d, message: '%s', exception: %s",
buildStatus, statusCode, message, bbResult.getException()));
UbUtils.jenkinsLog(logger, "\n ----- UNBREAKABLE BUILD FINISHED ----- \n");
} else {
run.setResult(Result.FAILURE);
String errorMessage = String.format(
"The notification to bitbucket went wrong, build marked as failed. "
+ "Status code: %d, message: %s, exception: %s",
statusCode, message, bbResult.getException());
LOGGER.error(errorMessage, bbResult.getException());
UbUtils.jenkinsLog(logger, "\n" + errorMessage + "\n");
throw new Failure(errorMessage);
}
}
private String generateBitbucketUrl() {
// POST
// http://example.org/rest/ubuild/1.0/projects/{projectKey}/repos/
// {repositorySlug}/pull-requests/{pullRequestId}/commits/{commitId}/notify
return String.format(
"%s/rest/ubuild/%s/projects/%s/repos/%s/commits/%s/notify",
bitbucketUrl, BITBUCKET_API_VERSION, projectKey, repositorySlug, commitId);
}
/**
* Core function of the unbreakable build.
*
* @param actionName ubValidate, or ubFail (only logging purposes)
* @param envVars environment variables provided by jenkins during the run
* @param logger jenkins logger (provided during the run)
* @param status either passed or failed
* @param credentials the credentialsId to use ?
* @param run
* @throws AbortException
*/
static void collectEnvAndNotifyBitbucket(String actionName,
EnvVars envVars,
PrintStream logger,
UbJenkinsEnvBean.Status status,
org.apache.http.auth.UsernamePasswordCredentials credentials,
Run<?, ?> run) throws AbortException {
LOGGER.info("{} - Collecting environment variables", actionName);
UbJenkinsEnvBean ubJenkinsEnvBean = new UbJenkinsEnvBean(envVars, run);
ubJenkinsEnvBean.notifyBitbucket(status, logger, credentials, run);
LOGGER.info("{} - execution finished", actionName);
}
/**
* Will return true in case of in unbreakable build context.
*
* @param envVars Environment variables map.
* @return true in case of envVars.get(EnvVarName.UNBREAKABLE_REFSPEC) not null
*/
static boolean isUnbreakableBuild(EnvVars envVars) {
return envVars.containsKey(EnvVarName.UNBREAKABLE_REFSPEC.toString());
}
}
| 41.285714
| 118
| 0.628537
|
e2fc85414ef7a6e285c247a205dcfeebf74ee344
| 9,864
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/services/ad_group_feed_service.proto
package com.google.ads.googleads.v8.services;
public final class AdGroupFeedServiceProto {
private AdGroupFeedServiceProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_GetAdGroupFeedRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_GetAdGroupFeedRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_AdGroupFeedOperation_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_AdGroupFeedOperation_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedResult_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedResult_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n<google/ads/googleads/v8/services/ad_gr" +
"oup_feed_service.proto\022 google.ads.googl" +
"eads.v8.services\0329google/ads/googleads/v" +
"8/enums/response_content_type.proto\0325goo" +
"gle/ads/googleads/v8/resources/ad_group_" +
"feed.proto\032\034google/api/annotations.proto" +
"\032\027google/api/client.proto\032\037google/api/fi" +
"eld_behavior.proto\032\031google/api/resource." +
"proto\032 google/protobuf/field_mask.proto\032" +
"\027google/rpc/status.proto\"\\\n\025GetAdGroupFe" +
"edRequest\022C\n\rresource_name\030\001 \001(\tB,\340A\002\372A&" +
"\n$googleads.googleapis.com/AdGroupFeed\"\241" +
"\002\n\031MutateAdGroupFeedsRequest\022\030\n\013customer" +
"_id\030\001 \001(\tB\003\340A\002\022O\n\noperations\030\002 \003(\01326.goo" +
"gle.ads.googleads.v8.services.AdGroupFee" +
"dOperationB\003\340A\002\022\027\n\017partial_failure\030\003 \001(\010" +
"\022\025\n\rvalidate_only\030\004 \001(\010\022i\n\025response_cont" +
"ent_type\030\005 \001(\0162J.google.ads.googleads.v8" +
".enums.ResponseContentTypeEnum.ResponseC" +
"ontentType\"\352\001\n\024AdGroupFeedOperation\022/\n\013u" +
"pdate_mask\030\004 \001(\0132\032.google.protobuf.Field" +
"Mask\022@\n\006create\030\001 \001(\0132..google.ads.google" +
"ads.v8.resources.AdGroupFeedH\000\022@\n\006update" +
"\030\002 \001(\0132..google.ads.googleads.v8.resourc" +
"es.AdGroupFeedH\000\022\020\n\006remove\030\003 \001(\tH\000B\013\n\top" +
"eration\"\233\001\n\032MutateAdGroupFeedsResponse\0221" +
"\n\025partial_failure_error\030\003 \001(\0132\022.google.r" +
"pc.Status\022J\n\007results\030\002 \003(\01329.google.ads." +
"googleads.v8.services.MutateAdGroupFeedR" +
"esult\"w\n\027MutateAdGroupFeedResult\022\025\n\rreso" +
"urce_name\030\001 \001(\t\022E\n\rad_group_feed\030\002 \001(\0132." +
".google.ads.googleads.v8.resources.AdGro" +
"upFeed2\210\004\n\022AdGroupFeedService\022\301\001\n\016GetAdG" +
"roupFeed\0227.google.ads.googleads.v8.servi" +
"ces.GetAdGroupFeedRequest\032..google.ads.g" +
"oogleads.v8.resources.AdGroupFeed\"F\202\323\344\223\002" +
"0\022./v8/{resource_name=customers/*/adGrou" +
"pFeeds/*}\332A\rresource_name\022\346\001\n\022MutateAdGr" +
"oupFeeds\022;.google.ads.googleads.v8.servi" +
"ces.MutateAdGroupFeedsRequest\032<.google.a" +
"ds.googleads.v8.services.MutateAdGroupFe" +
"edsResponse\"U\202\323\344\223\0026\"1/v8/customers/{cust" +
"omer_id=*}/adGroupFeeds:mutate:\001*\332A\026cust" +
"omer_id,operations\032E\312A\030googleads.googlea" +
"pis.com\322A\'https://www.googleapis.com/aut" +
"h/adwordsB\376\001\n$com.google.ads.googleads.v" +
"8.servicesB\027AdGroupFeedServiceProtoP\001ZHg" +
"oogle.golang.org/genproto/googleapis/ads" +
"/googleads/v8/services;services\242\002\003GAA\252\002 " +
"Google.Ads.GoogleAds.V8.Services\312\002 Googl" +
"e\\Ads\\GoogleAds\\V8\\Services\352\002$Google::Ad" +
"s::GoogleAds::V8::Servicesb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.ads.googleads.v8.enums.ResponseContentTypeProto.getDescriptor(),
com.google.ads.googleads.v8.resources.AdGroupFeedProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
com.google.rpc.StatusProto.getDescriptor(),
});
internal_static_google_ads_googleads_v8_services_GetAdGroupFeedRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v8_services_GetAdGroupFeedRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_GetAdGroupFeedRequest_descriptor,
new java.lang.String[] { "ResourceName", });
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsRequest_descriptor,
new java.lang.String[] { "CustomerId", "Operations", "PartialFailure", "ValidateOnly", "ResponseContentType", });
internal_static_google_ads_googleads_v8_services_AdGroupFeedOperation_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_ads_googleads_v8_services_AdGroupFeedOperation_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_AdGroupFeedOperation_descriptor,
new java.lang.String[] { "UpdateMask", "Create", "Update", "Remove", "Operation", });
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsResponse_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedsResponse_descriptor,
new java.lang.String[] { "PartialFailureError", "Results", });
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedResult_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedResult_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_MutateAdGroupFeedResult_descriptor,
new java.lang.String[] { "ResourceName", "AdGroupFeed", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
com.google.ads.googleads.v8.enums.ResponseContentTypeProto.getDescriptor();
com.google.ads.googleads.v8.resources.AdGroupFeedProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
com.google.rpc.StatusProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 58.714286
| 121
| 0.768856
|
d1085447550cacc6deae20dfaf8c80f011c621b4
| 22,168
|
package org.ripple.power.utils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.UUID;
public class ByteUtils {
private final static int SIZE_IN_BITS = 8;
private static final String hexChars = "0123456789ABCDEF";
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private ByteUtils() {
}
public static byte[] reverse(final byte[] x) {
int i, j;
final int n;
if ((n = x.length) > 0) {
final byte[] ret = new byte[n];
for (i = 0, j = n - 1; j >= 0;)
ret[i++] = x[j--];
return ret;
}
return x;
}
public static short leb2short(final byte[] x, final int offset) {
return (short) ((x[offset] & 0xFF) | (x[offset + 1] << 8));
}
public static short beb2short(final byte[] x, final int offset) {
return (short) ((x[offset] << 8) | (x[offset + 1] & 0xFF));
}
public static short leb2short(final InputStream is) throws IOException {
return (short) ((readByte(is) & 0xFF) | (readByte(is) << 8));
}
public static short beb2short(final InputStream is) throws IOException {
return (short) ((readByte(is) << 8) | (readByte(is) & 0xFF));
}
public static int leb2int(final byte[] x, final int offset) {
return (x[offset] & 0xFF) | ((x[offset + 1] & 0xFF) << 8) | ((x[offset + 2] & 0xFF) << 16)
| (x[offset + 3] << 24);
}
public static int beb2int(final byte[] x, final int offset) {
return (x[offset] << 24) | ((x[offset + 1] & 0xFF) << 16) | ((x[offset + 2] & 0xFF) << 8)
| (x[offset + 3] & 0xFF);
}
public static int leb2int(final InputStream is) throws IOException {
return (readByte(is) & 0xFF) | ((readByte(is) & 0xFF) << 8) | ((readByte(is) & 0xFF) << 16)
| (readByte(is) << 24);
}
public static int beb2int(final InputStream is) throws IOException {
return (readByte(is) << 24) | ((readByte(is) & 0xFF) << 16) | ((readByte(is) & 0xFF) << 8)
| (readByte(is) & 0xFF);
}
public static int leb2int(final byte[] x, final int offset, final int n)
throws IndexOutOfBoundsException, IllegalArgumentException {
switch (n) {
case 1:
return x[offset] & 0xFF;
case 2:
return (x[offset] & 0xFF) | ((x[offset + 1] & 0xFF) << 8);
case 3:
return (x[offset] & 0xFF) | ((x[offset + 1] & 0xFF) << 8) | ((x[offset + 2] & 0xFF) << 16);
case 4:
return (x[offset] & 0xFF) | ((x[offset + 1] & 0xFF) << 8) | ((x[offset + 2] & 0xFF) << 16)
| (x[offset + 3] << 24);
default:
throw new IllegalArgumentException("No bytes specified");
}
}
public static long leb2long(final byte[] x, final int offset, final int n)
throws IndexOutOfBoundsException, IllegalArgumentException {
switch (n) {
case 1:
return x[offset] & 0xFFL;
case 2:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8);
case 3:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16);
case 4:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24);
case 5:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24) | ((x[offset + 4] & 0xFFL) << 32);
case 6:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24) | ((x[offset + 4] & 0xFFL) << 32)
| ((x[offset + 5] & 0xFFL) << 40);
case 7:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24) | ((x[offset + 4] & 0xFFL) << 32)
| ((x[offset + 5] & 0xFFL) << 40) | ((x[offset + 6] & 0xFFL) << 48);
case 8:
return (x[offset] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24) | ((x[offset + 4] & 0xFFL) << 32)
| ((x[offset + 5] & 0xFFL) << 40) | ((x[offset + 6] & 0xFFL) << 48) | ((long) x[offset + 7] << 56);
default:
throw new IllegalArgumentException("No bytes specified");
}
}
public static long leb2long(InputStream is) throws IOException {
return (readByte(is) & 0xFFL) | ((readByte(is) & 0xFFL) << 8) | ((readByte(is) & 0xFFL) << 16)
| ((readByte(is) & 0xFFL) << 24) | ((readByte(is) & 0xFFL) << 32) | ((readByte(is) & 0xFFL) << 40)
| ((readByte(is) & 0xFFL) << 48) | (readByte(is) << 56);
}
public static int beb2int(final byte[] x, final int offset, final int n)
throws IndexOutOfBoundsException, IllegalArgumentException {
switch (n) {
case 1:
return x[offset] & 0xFF;
case 2:
return ((x[offset] & 0xFF) << 8) | (x[offset + 1] & 0xFF);
case 3:
return ((x[offset] & 0xFF) << 16) | ((x[offset + 1] & 0xFF) << 8) | (x[offset + 2] & 0xFF);
case 4:
return (x[offset] << 24) | ((x[offset + 1] & 0xFF) << 16) | ((x[offset + 2] & 0xFF) << 8)
| (x[offset + 3] & 0xFF);
default:
throw new IllegalArgumentException("No bytes specified");
}
}
public static void short2leb(final short x, final byte[] buf, final int offset) {
buf[offset] = (byte) x;
buf[offset + 1] = (byte) (x >> 8);
}
public static void short2beb(final short x, final byte[] buf, final int offset) {
buf[offset] = (byte) (x >> 8);
buf[offset + 1] = (byte) x;
}
public static void short2leb(final short x, final OutputStream os) throws IOException {
os.write((byte) x);
os.write((byte) (x >> 8));
}
public static void short2beb(final short x, final OutputStream os) throws IOException {
os.write((byte) (x >> 8));
os.write((byte) x);
}
public static void int2leb(final int x, final byte[] buf, final int offset) {
buf[offset] = (byte) x;
buf[offset + 1] = (byte) (x >> 8);
buf[offset + 2] = (byte) (x >> 16);
buf[offset + 3] = (byte) (x >> 24);
}
public static void long2beb(final long x, final byte[] buf, final int offset) {
buf[offset] = (byte) (x >> 56);
buf[offset + 1] = (byte) (x >> 48);
buf[offset + 2] = (byte) (x >> 40);
buf[offset + 3] = (byte) (x >> 32);
buf[offset + 4] = (byte) (x >> 24);
buf[offset + 5] = (byte) (x >> 16);
buf[offset + 6] = (byte) (x >> 8);
buf[offset + 7] = (byte) x;
}
public static void long2leb(final long x, final byte[] buf, final int offset) {
buf[offset] = (byte) x;
buf[offset + 1] = (byte) (x >> 8);
buf[offset + 2] = (byte) (x >> 16);
buf[offset + 3] = (byte) (x >> 24);
buf[offset + 4] = (byte) (x >> 32);
buf[offset + 5] = (byte) (x >> 40);
buf[offset + 6] = (byte) (x >> 48);
buf[offset + 7] = (byte) (x >> 56);
}
public static byte[] long2bytes(long i, int byteCount) {
byte[] b = new byte[8];
b[7] = (byte) (i);
i >>>= 8;
b[6] = (byte) (i);
i >>>= 8;
b[5] = (byte) (i);
i >>>= 8;
b[4] = (byte) (i);
i >>>= 8;
b[3] = (byte) (i);
i >>>= 8;
b[2] = (byte) (i);
i >>>= 8;
b[1] = (byte) (i);
i >>>= 8;
b[0] = (byte) (i);
byte[] bytes = new byte[byteCount];
System.arraycopy(b, 8 - byteCount, bytes, 0, byteCount);
return bytes;
}
public static void int2beb(final int x, final byte[] buf, final int offset) {
buf[offset] = (byte) (x >> 24);
buf[offset + 1] = (byte) (x >> 16);
buf[offset + 2] = (byte) (x >> 8);
buf[offset + 3] = (byte) x;
}
public static void int2beb(final int x, OutputStream out, final int n) throws IOException {
switch (n) {
case 1:
out.write((byte) x);
break;
case 2:
out.write((byte) (x >> 8));
out.write((byte) x);
break;
case 3:
out.write((byte) (x >> 16));
out.write((byte) (x >> 8));
out.write((byte) x);
break;
case 4:
out.write((byte) (x >> 24));
out.write((byte) (x >> 16));
out.write((byte) (x >> 8));
out.write((byte) x);
break;
default:
throw new IllegalArgumentException("invalid n: " + n);
}
}
public static void int2leb(final int x, final OutputStream os) throws IOException {
os.write((byte) x);
os.write((byte) (x >> 8));
os.write((byte) (x >> 16));
os.write((byte) (x >> 24));
}
public static void int2beb(final int x, final OutputStream os) throws IOException {
os.write((byte) (x >> 24));
os.write((byte) (x >> 16));
os.write((byte) (x >> 8));
os.write((byte) x);
}
public static byte[] int2minLeb(final int x) throws IllegalArgumentException {
if (x <= 0xFFFF) {
if (x <= 0xFF) {
if (x < 0)
throw new IllegalArgumentException();
return new byte[] { (byte) x };
}
return new byte[] { (byte) x, (byte) (x >> 8) };
}
if (x <= 0xFFFFFF)
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16) };
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24) };
}
public static byte[] long2minLeb(final long x) throws IllegalArgumentException {
if (x <= 0xFFFFFFFFFFFFFFL) {
if (x <= 0xFFFFFFFFFFFFL) {
if (x <= 0xFFFFFFFFFFL) {
if (x <= 0xFFFFFFFFL) {
if (x <= 0xFFFFFFL) {
if (x <= 0xFFFFL) {
if (x <= 0xFFL) {
if (x < 0)
throw new IllegalArgumentException();
return new byte[] { (byte) x };
}
return new byte[] { (byte) x, (byte) (x >> 8) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24),
(byte) (x >> 32) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24), (byte) (x >> 32),
(byte) (x >> 40) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24), (byte) (x >> 32),
(byte) (x >> 40), (byte) (x >> 48) };
}
return new byte[] { (byte) x, (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24), (byte) (x >> 32),
(byte) (x >> 40), (byte) (x >> 48), (byte) (x >> 56) };
}
public static byte[] int2minBeb(final int x) throws IllegalArgumentException {
if (x <= 0xFFFF) {
if (x <= 0xFF) {
if (x < 0)
throw new IllegalArgumentException();
return new byte[] { (byte) x };
}
return new byte[] { (byte) (x >> 8), (byte) x };
}
if (x <= 0xFFFFFF)
return new byte[] { (byte) (x >> 16), (byte) (x >> 8), (byte) x };
return new byte[] { (byte) (x >> 24), (byte) (x >> 16), (byte) (x >> 8), (byte) x };
}
public static int ubyte2int(final byte x) {
return x & 0xFF;
}
public static int ushort2int(final short x) {
return x & 0xFFFF;
}
public static long uint2long(final int x) {
return x & 0xFFFFFFFFL;
}
public static int long2int(final long l) {
int m;
if (l < (m = Integer.MAX_VALUE) && l > (m = Integer.MIN_VALUE))
return (int) l;
return m;
}
public static long beb2long(final byte[] x, final int offset, final int n)
throws IndexOutOfBoundsException, IllegalArgumentException {
switch (n) {
case 1:
return x[offset] & 0xFFL;
case 2:
return (x[offset + 1] & 0xFFL) | ((x[offset] & 0xFFL) << 8);
case 3:
return (x[offset + 2] & 0xFFL) | ((x[offset + 1] & 0xFFL) << 8) | ((x[offset] & 0xFFL) << 16);
case 4:
return (x[offset + 3] & 0xFFL) | ((x[offset + 2] & 0xFFL) << 8) | ((x[offset + 1] & 0xFFL) << 16)
| ((x[offset] & 0xFFL) << 24);
case 5:
return (x[offset + 4] & 0xFFL) | ((x[offset + 3] & 0xFFL) << 8) | ((x[offset + 2] & 0xFFL) << 16)
| ((x[offset + 1] & 0xFFL) << 24) | ((x[offset] & 0xFFL) << 32);
case 6:
return (x[offset + 5] & 0xFFL) | ((x[offset + 4] & 0xFFL) << 8) | ((x[offset + 3] & 0xFFL) << 16)
| ((x[offset + 2] & 0xFFL) << 24) | ((x[offset + 1] & 0xFFL) << 32) | ((x[offset] & 0xFFL) << 40);
case 7:
return (x[offset + 6] & 0xFFL) | ((x[offset + 5] & 0xFFL) << 8) | ((x[offset + 4] & 0xFFL) << 16)
| ((x[offset + 3] & 0xFFL) << 24) | ((x[offset + 2] & 0xFFL) << 32)
| ((x[offset + 1] & 0xFFL) << 40) | ((x[offset] & 0xFFL) << 48);
case 8:
return (x[offset + 7] & 0xFFL) | ((x[offset + 6] & 0xFFL) << 8) | ((x[offset + 5] & 0xFFL) << 16)
| ((x[offset + 4] & 0xFFL) << 24) | ((x[offset + 3] & 0xFFL) << 32)
| ((x[offset + 2] & 0xFFL) << 40) | ((x[offset + 1] & 0xFFL) << 48) | ((x[offset] & 0xFFL) << 56);
default:
throw new IllegalArgumentException("No bytes specified");
}
}
private static int readByte(InputStream is) throws IOException {
int ret = is.read();
if (ret == -1) {
throw new EOFException();
}
return ret;
}
public static byte[] smallIntToByteArray(int v) {
if (v > 65535) {
throw new IllegalArgumentException("value is too big");
}
return new byte[] { (byte) ((v >>> 8) & 0xFF), (byte) ((v >>> 0) & 0xFF) };
}
public static int byteArrayToSmallInt(byte[] arr, int offset) {
if (arr == null || arr.length - offset < 2) {
throw new IllegalArgumentException("Invalid arguments");
}
return ((arr[offset] & 0xFF) << 8) + (arr[1 + offset] & 0xFF);
}
public static byte[] smallIntToTripleByteArray(int v) {
if (v > 16777215) {
throw new IllegalArgumentException("value is too big");
}
return new byte[] { (byte) ((v >>> 16) & 0xFF), (byte) ((v >>> 8) & 0xFF), (byte) ((v >>> 0) & 0xFF) };
}
public static int tripleByteArrayToSmallInt(byte[] arr, int offset) {
if (arr == null || arr.length - offset < 2) {
throw new IllegalArgumentException("Invalid arguments");
}
return ((arr[offset] & 0xFF) << 16) + ((arr[1 + offset] & 0xFF) << 8) + (arr[2 + offset] & 0xFF);
}
public static byte[] getByteArrayChecksum(byte[] arr) {
if (arr.length > 65535) {
throw new IllegalArgumentException("Byte array is too long");
}
int result = 0;
int step = arr.length > 100 ? 16 : 1;
for (int i = 0; i < arr.length; i += step) {
result += (arr[i] & 0xFF);
}
return smallIntToTripleByteArray(result);
}
public static byte[] appendByteArrays(byte[] a, byte[] b) {
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
public static byte[] appendByte(byte[] bytes, byte b) {
byte[] result = Arrays.copyOf(bytes, bytes.length + 1);
result[result.length - 1] = b;
return result;
}
public static byte[] uuidToByteArray(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buffer = new byte[16];
for (int i = 0; i < 8; i++) {
buffer[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
buffer[i] = (byte) (lsb >>> 8 * (7 - i));
}
return buffer;
}
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
if (b == null)
return null;
byte[] bytes = new byte[numBytes];
byte[] biBytes = b.toByteArray();
int start = (biBytes.length == numBytes + 1) ? 1 : 0;
int length = Math.min(biBytes.length, numBytes);
System.arraycopy(biBytes, start, bytes, numBytes - length, length);
return bytes;
}
public static byte[] bigIntegerToBytes(BigInteger value) {
if (value == null)
return null;
byte[] data = value.toByteArray();
if (data.length != 1 && data[0] == 0) {
byte[] tmp = new byte[data.length - 1];
System.arraycopy(data, 1, tmp, 0, tmp.length);
data = tmp;
}
return data;
}
public static int matchingNibbleLength(byte[] a, byte[] b) {
int i = 0;
int length = a.length < b.length ? a.length : b.length;
while (i < length) {
if (a[i] != b[i])
break;
i++;
}
return i;
}
public static byte[] longToBytes(long val) {
return ByteBuffer.allocate(8).putLong(val).array();
}
public static byte[] calcPacketLength(byte[] msg) {
int msgLen = msg.length;
byte[] len = { (byte) ((msgLen >> 24) & 0xFF), (byte) ((msgLen >> 16) & 0xFF), (byte) ((msgLen >> 8) & 0xFF),
(byte) ((msgLen) & 0xFF) };
return len;
}
public static int byteArrayToInt(byte[] b) {
if (b == null || b.length == 0) {
return 0;
}
return new BigInteger(1, b).intValue();
}
public static String nibblesToPrettyString(byte[] nibbles) {
StringBuffer buffer = new StringBuffer();
for (byte nibble : nibbles) {
String nibleString = oneByteToHexString(nibble);
buffer.append("\\x" + nibleString);
}
return buffer.toString();
}
public static String oneByteToHexString(byte value) {
String retVal = Integer.toString(value & 0xFF, 16);
if (retVal.length() == 1)
retVal = "0" + retVal;
return retVal;
}
public static int numBytes(String val) {
BigInteger bInt = new BigInteger(val);
int bytes = 0;
while (!bInt.equals(BigInteger.ZERO)) {
bInt = bInt.shiftRight(8);
++bytes;
}
if (bytes == 0)
++bytes;
return bytes;
}
public static byte[] encodeValFor32Bits(Object arg) {
byte[] data;
if (arg.toString().trim().matches("-?\\d+(\\.\\d+)?")) {
data = new BigInteger(arg.toString().trim()).toByteArray();
} else if (arg.toString().trim().matches("0[xX][0-9a-fA-F]+")) {
data = new BigInteger(arg.toString().trim().substring(2), 16).toByteArray();
} else {
data = arg.toString().trim().getBytes();
}
if (data.length > 32) {
throw new RuntimeException("values can't be more than 32 byte");
}
byte[] val = new byte[32];
int j = 0;
for (int i = data.length; i > 0; --i) {
val[31 - j] = data[i - 1];
++j;
}
return val;
}
public static byte[] encodeDataList(Object... args) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (Object arg : args) {
byte[] val = encodeValFor32Bits(arg);
try {
baos.write(val);
} catch (IOException e) {
throw new Error("Happen something that should never happen ", e);
}
}
return baos.toByteArray();
}
public static int firstNonZeroByte(byte[] data) {
int firstNonZero = -1;
int i = 0;
for (; i < data.length; ++i) {
if (data[i] != 0) {
firstNonZero = i;
break;
}
}
return firstNonZero;
}
public static byte[] stripLeadingZeroes(byte[] data) {
if (data == null) {
return null;
}
int firstNonZero = firstNonZeroByte(data);
int i = 0;
for (; i < data.length; ++i) {
if (data[i] != 0) {
firstNonZero = i;
break;
}
}
if (i == data.length) {
return new byte[1];
}
if (firstNonZero == 0) {
return data;
}
byte[] result = new byte[data.length - firstNonZero];
System.arraycopy(data, firstNonZero, result, 0, data.length - firstNonZero);
return result;
}
public static byte[] setBit(byte[] data, int pos, int val) {
if ((data.length * 8) - 1 < pos) {
throw new Error("outside byte array limit, pos: " + pos);
}
int posByte = data.length - 1 - (pos) / 8;
int posBit = (pos) % 8;
byte setter = (byte) (1 << (posBit));
byte toBeSet = data[posByte];
byte result;
if (val == 1) {
result = (byte) (toBeSet | setter);
} else {
result = (byte) (toBeSet & ~setter);
}
data[posByte] = result;
return data;
}
public static int getBit(byte[] data, int pos) {
if ((data.length * 8) - 1 < pos) {
throw new Error("outside byte array limit, pos: " + pos);
}
int posByte = data.length - 1 - pos / 8;
int posBit = pos % 8;
byte dataByte = data[posByte];
return Math.min(1, (dataByte & (1 << (posBit))));
}
public static boolean increment(byte[] bytes) {
final int startIndex = 0;
int i;
for (i = bytes.length - 1; i >= startIndex; i--) {
bytes[i]++;
if (bytes[i] != 0) {
break;
}
}
return (i >= startIndex || bytes[startIndex] != 0);
}
public static byte[] copyToArray(BigInteger value) {
byte[] src = ByteUtils.bigIntegerToBytes(value);
byte[] dest = ByteBuffer.allocate(32).array();
System.arraycopy(src, 0, dest, dest.length - src.length, src.length);
return dest;
}
public static String toHexString(byte[] byteArray) {
if (byteArray == null) {
return null;
}
final StringBuilder sb = new StringBuilder(2 + 2 * byteArray.length);
for (final byte b : byteArray) {
sb.append(hexChars.charAt((b & 0xF0) >> 4)).append(hexChars.charAt((b & 0x0F)));
}
return sb.toString();
}
public static String toHexString0x(byte[] byteArray) {
if (byteArray == null) {
return null;
}
return "0x" + toHexString(byteArray);
}
public static String toBinString0b(byte[] byteArray) {
if (byteArray == null) {
return null;
}
return "0b" + toBinString(byteArray);
}
public static String toBinString(byte[] byteArray) {
StringBuilder sb = new StringBuilder();
for (int byteNum = byteArray.length - 1; byteNum >= 0; byteNum--) {
for (int bitNum = SIZE_IN_BITS - 1; bitNum >= 0; bitNum--) {
if (bitAt(bitNum, byteArray[byteNum])) {
sb.append("1");
} else {
sb.append("0");
}
}
}
return sb.toString();
}
public static byte[] concatenate(byte[] a, byte[] b) {
return appendByteArrays(a, b);
}
public static boolean bitAt(int offset, byte aByte) {
return (aByte & (1 << offset)) != 0;
}
public static byte setBitAt(int offset, boolean bitValue, byte aByte) {
return (byte) ((bitValue) ? (aByte | (1 << offset)) : (aByte & ~(1 << offset)));
}
public static byte[] readFully(Path filePath) throws FileNotFoundException, IOException {
return readFully(new FileInputStream(filePath.toFile()));
}
public static byte[] readFully(InputStream inputStream) throws IOException {
byte[] buffer = new byte[131072];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
}
public static void writeFully(Path filePath, byte[] bytes) throws IOException {
writeFully(new FileOutputStream(filePath.toFile()), bytes);
}
public static void writeFully(OutputStream outputStream, byte[] bytes) throws IOException {
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();
}
}
public static byte[] copy(byte[] aByte) {
return Arrays.copyOf(aByte, aByte.length);
}
}
| 29.956757
| 111
| 0.582732
|
970f9d41d1f71535baf3ae1bd9ef3b29b233d109
| 266
|
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
System.out.println("修改了HelloWorld类");
System.out.println("第二次修改");
System.out.println("在master分支下输出一条信息");
System.out.println("在develop分支下输出一条信息");
}
}
| 26.6
| 42
| 0.725564
|
79e88a46c3a108e692bd52d5b77dab16bbed8112
| 2,551
|
package science.atlarge.opencraft.opencraft.messaging.policies;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import science.atlarge.opencraft.messaging.Policy;
/**
* Defines a mapping from players to chunks of interest and from objects to the chunk in which they reside.
*/
public final class ChunkPolicy implements Policy<Chunk, Object, Player> {
private final World world;
private final int viewDistance;
/**
* Create a chunk policy for the given world and view distance.
*
* @param world the world from which chunks may be interesting.
* @param viewDistance the maximum view distance of any player.
*/
public ChunkPolicy(World world, int viewDistance) {
this.world = world;
this.viewDistance = viewDistance;
}
@Override
public Set<Chunk> computeInterestSet(Player player) {
Location location = player.getLocation();
if (location.getWorld() != world) {
return new HashSet<>();
}
int centerX = location.getBlockX() >> 4;
int centerZ = location.getBlockZ() >> 4;
int radius = Math.min(viewDistance, player.getViewDistance());
Set<Chunk> chunks = new HashSet<>();
for (int x = centerX - radius; x <= centerX + radius; x++) {
for (int z = centerZ - radius; z <= centerZ + radius; z++) {
Chunk chunk = world.getChunkAt(x, z);
chunks.add(chunk);
}
}
return chunks;
}
@Override
public Iterable<Chunk> selectTargets(Object publisher) {
if (publisher instanceof Chunk) {
Chunk chunk = (Chunk) publisher;
return Collections.singletonList(chunk);
}
if (publisher instanceof Block) {
Chunk chunk = ((Block) publisher).getChunk();
return Collections.singletonList(chunk);
}
if (publisher instanceof Entity) {
Chunk chunk = ((Entity) publisher).getChunk();
return Collections.singletonList(chunk);
}
if (publisher instanceof Location) {
Chunk chunk = ((Location) publisher).getChunk();
return Collections.singletonList(chunk);
}
throw new UnsupportedOperationException("Cannot select target topic for type: " + publisher.getClass());
}
}
| 31.493827
| 112
| 0.634261
|
fb21d4914536bccd2334f6affeaf120eabcf99e5
| 2,121
|
class Solution {
public List<Integer> countSmaller(int[] nums) {
if (nums == null || nums.length <= 0) {
return new ArrayList();
}
int[][] count = new int[nums.length][2];
for (int i = 0; i < nums.length; i++) {
count[i][1] = 0;
count[i][0] = i;
}
getSmallerCount(0, nums.length - 1, nums, count);
List<Integer> res = new ArrayList(nums.length);
int[] sol = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sol[count[i][0]] = count[i][1];
}
for (int i = 0; i < nums.length; i++) {
res.add(sol[i]);
}
return res;
}
private void getSmallerCount(int start, int end, int[] nums, int count[][]) {
if (start == end) {
count[start][1] = 0;
return;
}
int mid = (start + end) / 2;
getSmallerCount(start, mid, nums, count);
getSmallerCount(mid + 1, end, nums, count);
int right = mid + 1;
for (int i = start; i <= mid; i++) {
while (right <= end && nums[count[i][0]] <= nums[count[right][0]]) {
right++;
}
if (right <= end) {
count[i][1] = (end - right + 1) + count[i][1];
}
}
int left = start;
right = mid + 1;
int[][] merged = new int[end - start + 1][2];
int merge = 0;
while (left <= mid && right <= end) {
if (nums[count[left][0]] <= nums[count[right][0]]) {
merged[merge] = count[right];
right++;
} else {
merged[merge] = count[left];
left++;
}
merge++;
}
while (left <= mid) {
merged[merge] = count[left];
left++;
merge++;
}
while (right <= end) {
merged[merge] = count[right];
right++;
merge++;
}
for (int i = start; i <= end; i++) {
count[i] = merged[i - start];
}
}
}
| 31.191176
| 81
| 0.410655
|
3d62018c5a2d2452b8496eec0e6ee94540be393f
| 4,042
|
package com.dadsunion.tron.controller;
import java.util.List;
import java.util.Arrays;
import com.dadsunion.tron.constants.WithdrawState;
import com.dadsunion.tron.delegate.TronDelegate;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dadsunion.common.annotation.Log;
import com.dadsunion.common.core.controller.BaseController;
import com.dadsunion.common.core.domain.AjaxResult;
import com.dadsunion.common.enums.BusinessType;
import com.dadsunion.tron.domain.TronWithdrawRecord;
import com.dadsunion.tron.service.ITronWithdrawRecordService;
import com.dadsunion.common.utils.poi.ExcelUtil;
import com.dadsunion.common.core.page.TableDataInfo;
/**
* 提现记录Controller
*
* @author l8oo8l
* @date 2021-03-06
*/
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/tron/withdraw")
public class TronWithdrawRecordController extends BaseController {
private final ITronWithdrawRecordService iTronWithdrawRecordService;
private final TronDelegate tronDelegate;
/**
* 查询提现记录列表
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:list')")
@GetMapping("/list")
public TableDataInfo list(TronWithdrawRecord tronWithdrawRecord) {
startPage();
List<TronWithdrawRecord> list = iTronWithdrawRecordService.queryList(tronWithdrawRecord);
return getDataTable(list);
}
/**
* 导出提现记录列表
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:export')")
@Log(title = "提现记录", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(TronWithdrawRecord tronWithdrawRecord) {
List<TronWithdrawRecord> list = iTronWithdrawRecordService.queryList(tronWithdrawRecord);
ExcelUtil<TronWithdrawRecord> util = new ExcelUtil<TronWithdrawRecord>(TronWithdrawRecord.class);
return util.exportExcel(list, "withdraw");
}
/**
* 获取提现记录详细信息
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(iTronWithdrawRecordService.getById(id));
}
/**
* 新增提现记录
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:add')")
@Log(title = "提现记录", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody TronWithdrawRecord tronWithdrawRecord) {
return toAjax(iTronWithdrawRecordService.save(tronWithdrawRecord) ? 1 : 0);
}
/**
* 修改提现记录
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:edit')")
@Log(title = "提现记录", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody TronWithdrawRecord tronWithdrawRecord) {
return toAjax(iTronWithdrawRecordService.updateById(tronWithdrawRecord) ? 1 : 0);
}
/**
* 删除提现记录
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:remove')")
@Log(title = "提现记录", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(iTronWithdrawRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
}
/**
* 重新发起提现
*/
@PreAuthorize("@ss.hasPermi('tron:withdraw:edit')")
@Log(title = "重新发起提现", businessType = BusinessType.UPDATE)
@PutMapping("again")
public AjaxResult again(@RequestBody TronWithdrawRecord tronWithdrawRecord) {
TronWithdrawRecord twr = iTronWithdrawRecordService.getById(tronWithdrawRecord.getId());
// 查询提现状态
if (WithdrawState.HANDLING != twr.getState()) {
return AjaxResult.error("当前状态不可操作");
}
return toAjax(tronDelegate.reWithdraw(twr) ? 1 : 0);
}
}
| 33.683333
| 99
| 0.779317
|
77c1929f3bb4c340c84c13f1c28bf992226ad596
| 5,789
|
package local.rdps.svja.action.interceptor;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.TimeZone;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.json.JSONException;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.ExceptionHolder;
import com.opensymphony.xwork2.interceptor.Interceptor;
import local.rdps.svja.action.BaseAction;
import local.rdps.svja.action.RestAction;
import local.rdps.svja.constant.ErrorConstants;
import local.rdps.svja.constant.ResultConstants;
import local.rdps.svja.exception.ApplicationException;
import local.rdps.svja.exception.IllegalParameterException;
import local.rdps.svja.util.ValidationUtils;
import local.rdps.svja.vo.JsonErrorVo;
/**
* <p>
* This interceptor monitors and handles errors, turning them into a JSON response.
* </p>
*
* @author DaRon
* @since 1.0
*/
public class JsonErrorInterceptor implements Interceptor {
private static final Logger logger = LogManager.getLogger();
private static final long serialVersionUID = 9156313660873257945L;
/**
* Create a json error object from an exception
*
* @param e
* @return
*/
private static JsonErrorVo createJsonErrorObject(final Exception e) {
return e instanceof ApplicationException
? new JsonErrorVo(((ApplicationException) e).getExceptionStatusCode(),
((ApplicationException) e).getUiMessage())
: e instanceof ApplicationException
? new JsonErrorVo(((ApplicationException) e).getExceptionStatusCode(), "")
// could throw an ApplicationException here to wrap any non-ApplicationException
: new JsonErrorVo(500, "");
}
/**
* Get the full stack trace as a string from the provided exception
* <p>
* This output is capped at 10000 characters for preventing DoS by flooding stack traces
*
* @param e
* @return
*/
private static String getFullStackTrace(final Throwable e) {
if (ValidationUtils.isEmpty(e))
return "";
final StringWriter stringWriter = new StringWriter();
try (final PrintWriter printWriter = new PrintWriter(stringWriter)) {
e.printStackTrace(printWriter);
}
final String fullStack = stringWriter.toString();
return fullStack.length() > 10000 ? fullStack.substring(0, 10000) : fullStack;
}
/**
* Log exception data
*
* @param e
*/
private static void logExceptionData(final ApplicationException e) {
final String COLON = ": ";
if (JsonErrorInterceptor.logger.isEnabled(e.getLogLevel())) {
final String message = e.getExceptionStatusCode() + " (telling Struts: '" + e.getExceptionReturnString()
+ "') - " + e.getExceptionTitle() + COLON + System.lineSeparator() + System.lineSeparator();
// Check how much we log and for any other particulars
switch (e.getStackTraceLogDirective()) {
case ErrorConstants.DO_NOT_LOG_STACK_TRACE:
// Log the exception, but not the stack trace
JsonErrorInterceptor.logger.log(e.getLogLevel(), message + e);
break;
case ErrorConstants.LOG_LIMITED_STACK_TRACE:
// Log the exception and a limited stack trace
JsonErrorInterceptor.logger.log(e.getLogLevel(),
message + '\n' + JsonErrorInterceptor.getFullStackTrace(e));
break;
case ErrorConstants.LOG_STACK_TRACE_AS_INFO:
// Log the exception separately from the stack trace
JsonErrorInterceptor.logger.log(e.getLogLevel(),
message + '\n' + JsonErrorInterceptor.getFullStackTrace(e));
if (JsonErrorInterceptor.logger.isInfoEnabled()) {
JsonErrorInterceptor.logger.info(message, e);
}
break;
default:
// Make anything else an error and log the stack trace
JsonErrorInterceptor.logger.error("{}\n{}", message, JsonErrorInterceptor.getFullStackTrace(e));
}
}
}
/**
* Process the exception: - log the exception - send an email about the exception if appropriate (code >= 500)
*
* @param action
* @param e
*/
private static void processException(final BaseAction action, final ApplicationException e) {
// log the exception
JsonErrorInterceptor.logExceptionData(e);
// setup error that displays on the front-end
if (action instanceof RestAction) {
final JsonErrorVo jsonError = JsonErrorInterceptor.createJsonErrorObject(e);
((RestAction) action).setError(jsonError);
}
}
@Override
public void destroy() {
}
@Override
public void init() {
// Ensure that everything is in UTC
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
@Override
public String intercept(final ActionInvocation invocation) throws Exception {
try {
return invocation.invoke();
} catch (final Exception e) {
final ActionContext context = invocation.getInvocationContext();
final HttpServletResponse response = (HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE);
final ApplicationException error = e instanceof ApplicationException ? (ApplicationException) e
// wrap json parsing exceptions as illegal parameter exceptions
: (e instanceof JSONException) || (e instanceof NumberFormatException)
? new IllegalParameterException(e.getMessage(), e)
// wrap all other exceptions as an application exception
: new ApplicationException(e.getMessage(), e);
// add exception reference to the front-end
invocation.getStack().push(new ExceptionHolder(error));
JsonErrorInterceptor.processException((BaseAction) invocation.getAction(), error);
// Set the HTTP response status code and return the exception return string
response.setStatus(error.getExceptionStatusCode());
return ResultConstants.RESULT_EXCEPTION;
}
}
}
| 35.084848
| 111
| 0.744688
|
0fc9a7f9fde5d5f9c51e44da93c4d9a48da22d92
| 921
|
/*
* 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 br.com.compdevbooks.alphacosmetics.business;
import br.com.compdevbooks.alphacosmetics.dao.IDAO;
import br.com.compdevbooks.alphacosmetics.dao.IVendedorDAO;
import br.com.compdevbooks.alphacosmetics.entity.pessoa.VendedorEntity;
import java.util.List;
/**
*
* @author Daniel
*/
public class Vendedor extends ABusiness<VendedorEntity, Exception, IVendedorDAO>{
public Vendedor(IDAO<VendedorEntity> dao) {
super(dao);
}
public List<VendedorEntity> getByNome(String nome){
return ((IVendedorDAO) dao).getByNome(nome);
}
public List<VendedorEntity> buscarTodosVendedores(){
return ((IVendedorDAO) dao).buscarTodosVendedores();
}
}
| 28.78125
| 82
| 0.704669
|
f6643de199468127ba71dd6ddf58eb4549c20931
| 84
|
package br.com.bdev.api.infra.database.repository;
public class UserRepository {
}
| 16.8
| 50
| 0.797619
|
1d8cf45d8d7f6adedd153a216709fb411a01df13
| 1,312
|
package com.loserico.methodref;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MethodRefCompare {
public static class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Name:[" + name + "]" + ", age:[" + age + "]";
}
}
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("vivi", 32));
persons.add(new Person("zaizai", 3));
persons.add(new Person("rico", 33));
Person[] personsArr = persons.toArray(new Person[persons.size()]);
// Comparator<Person> byName = Comparator.comparing(p -> p.getName());
Comparator<Person> byName = Comparator.comparing(Person::getName);
Arrays.sort(personsArr, byName);
for (int i = 0; i < personsArr.length; i++) {
Person person = personsArr[i];
System.out.println(person);
}
}
}
| 21.508197
| 72
| 0.623476
|
05769259a4ccc9803d8cc9c5c8c6ec8ae3ae919a
| 1,004
|
package org.evomaster.dbconstraint;
import java.util.Objects;
public class SimilarToConstraint extends TableConstraint {
private final /* non-null*/ String columnName;
private final /*non-null*/ String pattern;
private final /*non-null*/ ConstraintDatabaseType databaseType;
public SimilarToConstraint(String tableName, String columnName, String pattern, ConstraintDatabaseType databaseType) {
super(tableName);
this.columnName = Objects.requireNonNull(columnName);
this.pattern = Objects.requireNonNull(pattern);
this.databaseType = Objects.requireNonNull(databaseType);
}
public String getColumnName() {
return columnName;
}
public String getPattern() {
return pattern;
}
public ConstraintDatabaseType getDatabaseType() {
return databaseType;
}
@Override
public <K, V> K accept(TableConstraintVisitor<K, V> visitor, V argument) {
return visitor.visit(this, argument);
}
}
| 27.135135
| 122
| 0.701195
|
5cd90a11dc3d2ec6903ac1aca84cf17db0672e1c
| 658
|
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test task #255.
*
*@author Idergunov(mailto:idergunov058@yadnex.ru).
*@version $Id$
*@since 0.1
*/
public class ArrayDuplicateTest {
/**
* Test add.
* Удалить дубли в массиве.
*/
@Test
public void whenRemoveDuplicatesThenArrayWithoutDuplicate() {
ArrayDuplicate duplicate = new ArrayDuplicate();
String[] resultArray = duplicate.remove(new String[] {"Hello", "World", "Hello", "Super", "World"});
String[] expectArray = new String[] {"Hello", "World", "Super"};
assertThat(resultArray, is(expectArray));
}
}
| 23.5
| 102
| 0.711246
|
decae19b40fee582dd055e024e9a3de8b2e0d0a4
| 3,524
|
package com.stackscaling.agentmaster.resources.utils;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.lightj.util.JsonUtil;
import org.lightj.util.StringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
/**
* data util
* @author biyu
*
*/
public class DataUtil {
/**
* remove from map any empty or zero values
* @param source
* @return
*/
public static Map<String, String> removeNullAndZero(Map<String, String> source) {
// remove all zero value from options before saving
HashMap<String, String> result = new HashMap<String, String>(source);
for (Iterator<Entry<String, String>> iter = result.entrySet().iterator(); iter.hasNext();) {
Entry<String, String> entry = iter.next();
if (StringUtil.isNullOrEmptyAfterTrim(entry.getValue()) || StringUtil.equalIgnoreCase("0", entry.getValue())) {
iter.remove();
}
}
return result;
}
/**
* retrieve from map with key, with default value if key not exist
* @param options
* @param key
* @param defVal
* @return
*/
public static String getOptionValue(Map<String, String> options, String key, String defVal) {
return (options != null &&
options.containsKey(key) &&
!StringUtil.isNullOrEmpty(options.get(key))) ? options.get(key) : defVal;
}
/**
* decode recursively a json string into map of object (nested arrays or maps)
* @param jsonMap
* @return
* @throws IOException
*/
public static void decode(String key, String jsonVal, Map<String, Object> result) throws IOException
{
result.put(key, decodeRecursive(jsonVal));
}
/**
* decode recursively a json string to corresponding object (nested arrays or maps)
* @param jsonVal
* @return
* @throws IOException
*/
public static Object decodeRecursive(String jsonVal) throws IOException
{
Object value = null;
if (jsonVal.startsWith("[") && jsonVal.endsWith("]")) {
// string array
String[] sValues = JsonUtil.decode(jsonVal, String[].class);
Object tmpValue = decodeRecursive(sValues[0]);
Class klass = tmpValue.getClass();
value = Array.newInstance(klass, sValues.length);
for (int i = 0; i < sValues.length; i++) {
tmpValue = decodeRecursive(sValues[i]);
Array.set(value, i, tmpValue);
}
}
else if (jsonVal.startsWith("{") && jsonVal.endsWith("}")) {
// string map
HashMap<String, String> sValues = JsonUtil.decode(jsonVal, new TypeReference<HashMap<String, String>>(){});
HashMap<String, Object> tmpValues = new HashMap<String, Object>();
value = tmpValues;
for (Entry<String, String> entry : sValues.entrySet()) {
tmpValues.put(entry.getKey(), decodeRecursive(entry.getValue()));
}
}
else {
value = jsonVal;
}
return value;
}
/**
* turn nvp map into array of id, value maps
* @param key
* @param value
* @return
*/
public static Map<String, String> createResultItem(String key, String value) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("id", key);
item.put("value", value);
return item;
}
/**
* turn a result string into json result
* @param result
* @return
*/
public static JsonResult jsonResult(String result) {
return new JsonResult(result);
}
static class JsonResult {
public String result;
public String time;
public JsonResult(String result) {
super();
this.result = result;
this.time = DateUtils.getNowDateTimeDotStr();
}
}
}
| 26.298507
| 114
| 0.685868
|
fadfb5a68c7de5fb9429c76c9e62b53d65d15587
| 1,618
|
/**Faca um programa que receba o codigo correspondente ao cargo de um funcionario e seu salario atual e mostre
* o cargo, o valor do aumento e seu novo salario. Os cargos estao na tabela a seguir.
* 1: Escriturario, 50%
* 2: Secretario, 35%
* 3: Caixa, 20%
* 4: Gerente, 10%
* 5: Diretor, sem aumento
*
*/
import java.util.Scanner;
import java.util.Locale;
public class Exercicio22{
public static void main(String[] args){
Locale.setDefault(Locale.ENGLISH);
Scanner in = new Scanner(System.in);
int codigo = in.nextInt();
double salAtual = in.nextDouble();
double aumento;
double novoSal;
switch(codigo){
case 1: {
String cargo = "Escriturario";
aumento = salAtual*0.5;
novoSal = salAtual + aumento;
System.out.printf("%s %.4f %.4f", cargo, aumento, novoSal);
break;
}
case 2: {
String cargo = "Secretario";
aumento = salAtual*0.35;
novoSal = salAtual + aumento;
System.out.printf("%s %.4f %.4f", cargo, aumento, novoSal);
break;
}
case 3: {
String cargo = "Caixa";
aumento = salAtual*0.2;
novoSal = salAtual + aumento;
System.out.printf("%s %.4f %.4f", cargo, aumento, novoSal);
break;
}
case 4: {
String cargo = "Gerente";
aumento = salAtual*0.1;
novoSal = salAtual + aumento;
System.out.printf("%s %.4f %.4f", cargo, aumento, novoSal);
break;
}
case 5: {
String cargo = "Diretor";
aumento = 0;
novoSal = salAtual + aumento;
System.out.printf("%s %.4f %.4f", cargo, aumento, novoSal);
break;
}
}
}
}
| 26.966667
| 110
| 0.603214
|
b666f689953b241a3dc20b5b034bf77c89e747a8
| 1,294
|
package org.javersion.object;
import static org.assertj.core.api.Assertions.assertThat;
import static org.javersion.object.ObjectVersionGraph.init;
import java.util.Arrays;
import org.javersion.core.Revision;
import org.junit.Test;
public class ObjectVersionGraphTest {
private ObjectVersion<String> v1 = ObjectVersion.<String>builder().build();
private ObjectVersion<String> v2 = ObjectVersion.<String>builder(new Revision())
.parents(v1.revision)
.build();
private ObjectVersion<String> v3 = ObjectVersion.<String>builder()
.parents(v2.revision)
.build();
@Test
public void initializers() {
ObjectVersionGraph<String> graph = init(v1);
assertThat(graph.getTip().getVersion()).isEqualTo(v1);
graph = init(Arrays.asList(v1, v2));
assertThat(graph.getTip().getVersion()).isEqualTo(v2);
graph = init(v1, v2, v3);
assertThat(graph.getTip().getVersion()).isEqualTo(v3);
}
@Test
public void optimize() {
ObjectVersionGraph<String> graph = init(v1, v2);
graph = graph.optimize(v2.revision).getGraph();
assertThat(graph.size()).isEqualTo(1);
assertThat(graph.getTip().getRevision()).isEqualTo(v2.revision);
}
}
| 30.809524
| 84
| 0.657651
|
c80b861569b537893ddc5ac208b7cf23bbd998d4
| 2,729
|
package org.apache.spark.util.collection.unsafe.sort;
import org.apache.commons.io.IOUtils;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import io.indexr.util.IOUtil;
import io.indexr.util.MemoryUtil;
public final class UnsafeSorterSpillReader extends UnsafeSorterIterator implements Closeable {
private FileChannel file;
private ByteBuffer buffer;
private long bufferAddr;
// Variables that change with every record read:
private long baseOffset;
private int recordLength;
private long keyPrefix;
private int numRecords;
private int numRecordsRemaining;
public UnsafeSorterSpillReader(
Path path) throws IOException {
file = FileChannel.open(path, StandardOpenOption.READ);
assert file.size() >= 4;
allocateBuffer(1024 * 1024);
buffer.order(ByteOrder.nativeOrder());
fillBuffer(4);
numRecords = numRecordsRemaining = buffer.getInt();
}
private void allocateBuffer(int cap) {
buffer = ByteBuffer.allocateDirect(cap);
bufferAddr = MemoryUtil.getAddress(buffer);
}
private void fillBuffer(int atLeastBytes) throws IOException {
buffer.clear();
buffer.limit(atLeastBytes);
IOUtil.readFully(file, buffer);
buffer.flip();
}
@Override
public int getNumRecords() {
return numRecords;
}
@Override
public boolean hasNext() {
return (numRecordsRemaining > 0);
}
@Override
public void loadNext() throws IOException {
if (buffer.remaining() < 4 + 8) {
fillBuffer(4 + 8);
}
recordLength = buffer.getInt();
keyPrefix = buffer.getLong();
if (recordLength > 0) {
if (buffer.remaining() < recordLength) {
if (buffer.capacity() > 4 + 8 + recordLength) {
allocateBuffer(4 + 8 + recordLength);
}
fillBuffer(recordLength);
}
}
baseOffset = bufferAddr;
numRecordsRemaining--;
if (numRecordsRemaining == 0) {
close();
}
}
@Override
public Object getBaseObject() {
return null;
}
@Override
public long getBaseOffset() {
return baseOffset;
}
@Override
public int getRecordLength() {
return recordLength;
}
@Override
public long getKeyPrefix() {
return keyPrefix;
}
@Override
public void close() throws IOException {
IOUtils.closeQuietly(file);
}
}
| 24.585586
| 94
| 0.624771
|
fea35f3c1a7ce0c6afee867541449d7589ca101a
| 2,950
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 tools4j, Marco Terzer, Anton Anufriev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.eventsourcing.mmap;
import org.tools4j.eventsourcing.api.IndexedPollerFactory;
import org.tools4j.eventsourcing.api.Poller;
import org.tools4j.mmap.region.api.RegionRingFactory;
import java.io.IOException;
import java.util.Objects;
public class MmapIndexedPollerFactory implements IndexedPollerFactory {
private final String directory;
private final String filePrefix;
private final RegionRingFactory regionRingFactory;
private final int regionSize;
private final int regionRingSize;
private final int regionsToMapAhead;
public MmapIndexedPollerFactory(final String directory,
final String filePrefix,
final RegionRingFactory regionRingFactory,
final int regionSize,
final int regionRingSize,
final int regionsToMapAhead) throws IOException {
this.directory = Objects.requireNonNull(directory);
this.filePrefix = Objects.requireNonNull(filePrefix);
this.regionRingFactory = Objects.requireNonNull(regionRingFactory);
this.regionSize = regionSize;
this.regionRingSize = regionRingSize;
this.regionsToMapAhead = regionsToMapAhead;
}
@Override
public Poller createPoller(final Poller.Options options) throws IOException {
return new MmapIndexedPoller(
RegionAccessorSupplier.forReadOnly(
directory,
filePrefix,
regionRingFactory,
regionSize,
regionRingSize,
regionsToMapAhead),
options
);
}
}
| 42.753623
| 85
| 0.678983
|
9d8fb1eb6033af7e0d90d84caa9795c21c52f26d
| 19,077
|
package com.technologies.highstreet.netconf2soapmediator.server;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class CWMPMessage {
private static StringBuilder envelope, envelopeEnd, header, informResponse, factoryReset;
private static ArrayList<String> getParamValList = new ArrayList<String>();
private static ArrayList<String> getFAPParamValList = new ArrayList<String>();
private static ArrayList<String> getParamAttList = new ArrayList<String>();
private static StringBuilder xmlString = new StringBuilder(10);
private static ArrayList<ArrayList<String>> setParamList = new ArrayList<ArrayList<String>>();
// constructor
public CWMPMessage() {
//initialize objects
initEnvelope();
initHeader();
initInformResponse();
initFactoryReset();
initGetParamValList();
initGetFAPParamValList();
initGetParamAttList();
initEnvelopeEnd();
getParametersFromFile();
}
void getParametersFromFile() {
try {
BufferedReader file = new BufferedReader(new FileReader("./xmlTR069Examples/GetParameterValuesResponse_example.xml"));
String stringBuffer;
while ((stringBuffer=file.readLine()) != null) {
xmlString.append(stringBuffer);
}
//System.out.println(xmlString.toString());
file.close();
}
catch (Exception fx) {
System.out.println("Exception " + fx.toString());
}
}
void initGetFAPParamValList() {
getFAPParamValList.add("Device.Services.FAPService.1.REM.");
// FAPSevice.REM
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.REMBandList");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.EUTRACarrierARFCNDLList"); //this is a list, more than one value.
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.ScanTimeout");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.ScanStatus");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.LastScanTime");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.ScanOnBoot");
// FAPSevice.REM.Cell
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.EUTRACarrierARFCN");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.PhyCellID");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSRP");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSRQ");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSSI");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.DLBandwidth");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.ULBandwidth");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.RSTxPower");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.TAC");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CellID");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CellBarred");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CSGIndication");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CSGIdentity");
// getFAPParamValList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.PLMNList.PLMNID");
}
void initGetParamValList() {
// DeviceInfo
getParamValList.add("Device.DeviceInfo.Manufacturer");
getParamValList.add("Device.DeviceInfo.ManufacturerOUI");
getParamValList.add("Device.DeviceInfo.Description");
getParamValList.add("Device.DeviceInfo.ProductClass");
getParamValList.add("Device.DeviceInfo.SerialNumber");
getParamValList.add("Device.DeviceInfo.HardwareVersion");
getParamValList.add("Device.DeviceInfo.SoftwareVersion");
getParamValList.add("Device.DeviceInfo.UpTime");
getParamValList.add("Device.DeviceInfo.FirstUseDate");
getParamValList.add("Device.IPsec.Enable");
// ManagementServer
getParamValList.add("Device.ManagementServer.PeriodicInformEnable");
getParamValList.add("Device.ManagementServer.PeriodicInformInterval");
// FAPService
// getParamValList.add("Device.Services.FAPService.1.REM.LTE.REMPLMNList");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.ULBandwidth");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.DLBandwidth");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.PhyCellID");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNUL");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNDL");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.PHY.PRACH.RootSequenceIndex");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.Common.CellIdentity");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable");
getParamValList.add("Device.Services.FAPService.1.FAPControl.LTE.Gateway.S1SigLinkServerList"); //this is a list, more than one value.
getParamValList.add("Device.Time.LocalTimeZone");
getParamValList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.TAC");
getParamValList.add("Device.Services.FAPService.1.FAPControl.LTE.OpState");
getParamValList.add("Device.Services.FAPService.1.FAPControl.LTE.AdminState");
}
void initGetParamAttList() {
// DeviceInfo
// getParamAttList.add("Device.DeviceInfo.Manufacturer");
// getParamAttList.add("Device.DeviceInfo.ManufacturerOUI");
// getParamAttList.add("Device.DeviceInfo.Description");
// getParamAttList.add("Device.DeviceInfo.ProductClass");
// getParamAttList.add("Device.DeviceInfo.SerialNumber");
// getParamAttList.add("Device.DeviceInfo.HardwareVersion");
// getParamAttList.add("Device.DeviceInfo.SoftwareVersion");
// getParamAttList.add("Device.DeviceInfo.UpTime");
// getParamAttList.add("Device.DeviceInfo.FirstUseDate");
// ManagementServer
getParamAttList.add("Device.ManagementServer.PeriodicInformEnable");
getParamAttList.add("Device.ManagementServer.PeriodicInformInterval");
// FAPService
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.REMPLMNList");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.ULBandwidth");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.DLBandwidth");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.PhyCellID");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNUL");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNDL");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.PHY.PRACH.RootSequenceIndex");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.Common.CellIdentity");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary");
// getParamAttList.add("Device.Services.FAPService.1.FAPControl.LTE.Gateway.S1SigLinkServerList"); //this is a list, more than one value.
// getParamAttList.add("Device.Time.LocalTimeZone");
// getParamAttList.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.TAC");
// getParamAttList.add("Device.Services.FAPService.1.FAPControl.LTE.OpState");
// getParamAttList.add("Device.Services.FAPService.1.FAPControl.LTE.AdminState");
// FAPSevice.REM
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.REMBandList");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.EUTRACarrierARFCNDLList"); //this is a list, more than one value.
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.ScanTimeout");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.ScanStatus");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.LastScanTime");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.ScanOnBoot");
// FAPSevice.REM.Cell
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.EUTRACarrierARFCN");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.PhyCellID");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSRP");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSRQ");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.RF.RSSI");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.DLBandwidth");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.ULBandwidth");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.RSTxPower");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.TAC");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CellID");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CellBarred");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CSGIndication");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.CSGIdentity");
// getParamAttList.add("Device.Services.FAPService.1.REM.LTE.Cell.1.BCCH.PLMNList.PLMNID");
}
void initEnvelope() {
envelope = new StringBuilder();
envelope.append("<soapenv:Envelope ");
envelope.append("xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
envelope.append("xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" ");
envelope.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
envelope.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
envelope.append("xmlns:cwmp=\"urn:dslforum-org:cwmp-1-0\">\n");
}
void initHeader() {
header = new StringBuilder();
header.append("\t<soapenv:Header>\n");
header.append("\t\t<cwmp:ID soapenv:mustUnderstand=\"1\">1</cwmp:ID>\n");
header.append("\t</soapenv:Header>\n");
}
void initEnvelopeEnd() {
envelopeEnd = new StringBuilder();
envelopeEnd.append("</soapenv:Envelope>\n");
}
void initInformResponse() {
informResponse = new StringBuilder();
informResponse.append("\t<soapenv:Body>\n");
informResponse.append("\t\t<cwmp:InformResponse>\n");
informResponse.append("\t\t\t<MaxEnvelopes>1</MaxEnvelopes>\n");
informResponse.append("\t\t</cwmp:InformResponse>\n");
informResponse.append("\t</soapenv:Body>\n");
}
void initFactoryReset() {
factoryReset = new StringBuilder();
factoryReset.append("\t<soapenv:Body>\n");
factoryReset.append("\t\t<cwmp:FactoryReset>\n");
factoryReset.append("\t\t\t<MaxEnvelopes>1</MaxEnvelopes>\n");
factoryReset.append("\t\t</cwmp:FactoryReset>\n");
factoryReset.append("\t</soapenv:Body>\n");
}
StringBuilder getInformResponse() {
System.out.println("InformResponse msg");
StringBuilder msg = new StringBuilder();
msg.append(envelope);
msg.append(header);
msg.append(informResponse);
msg.append(envelopeEnd);
return msg;
}
StringBuilder getFactoryReset() {
System.out.println("FactoryReset msg");
StringBuilder msg = new StringBuilder();
msg.append(envelope);
msg.append(header);
msg.append(factoryReset);
msg.append(envelopeEnd);
return msg;
}
StringBuilder getParameterValues(boolean FAP) {
System.out.println("GetParameterValues msg");
ArrayList<String> map = new ArrayList<String>();
if (FAP == true) {
map = getFAPParamValList;
} else {
map = getParamValList;
}
StringBuilder msg = new StringBuilder();
msg.append(envelope);
msg.append(header);
// body
msg.append("\t<soapenv:Body>\n");
msg.append("\t\t<cwmp:GetParameterValues>\n");
msg.append("\t\t\t<ParameterNames soap:arrayType=\"xsd:string[" + map.size() + "]\">\n");
for (int i = 0; i < map.size(); i++) {
msg.append("\t\t\t\t<string>" + map.get(i) + "</string>\n");
}
msg.append("\t\t\t</ParameterNames>\n");
msg.append("\t\t</cwmp:GetParameterValues>\n");
msg.append("\t</soapenv:Body>\n");
// end body
msg.append(envelopeEnd);
return msg;
}
StringBuilder getParameterAttributes() {
System.out.println("GetParameterAttributes msg");
StringBuilder msg = new StringBuilder();
msg.append(envelope);
msg.append(header);
// body
msg.append("\t<soapenv:Body>\n");
msg.append("\t\t<cwmp:GetParameterAttributes>\n");
msg.append("\t\t\t<ParameterNames soap:arrayType=\"xsd:string[" + getParamAttList.size() + "]\">\n");
for (int i = 0; i < getParamAttList.size(); i++) {
msg.append("\t\t\t\t<string>" + getParamAttList.get(i) + "</string>\n");
}
msg.append("\t\t\t</ParameterNames>\n");
msg.append("\t\t</cwmp:GetParameterAttributes>\n");
msg.append("\t</soapenv:Body>\n");
// end body
msg.append(envelopeEnd);
return msg;
}
StringBuilder setParameterValues(ArrayList<ArrayList<String>> list) {
System.out.println("SetParameterValues msg");
StringBuilder msg = new StringBuilder();
msg.append(envelope);
msg.append(header);
// body
msg.append("\t<soapenv:Body>\n");
msg.append("\t\t<cwmp:SetParameterValues>\n");
msg.append("\t\t\t<ParameterList soap:arrayType=\"cwmp:ParameterValueStruct[" + list.size() + "]\">\n");
for (int i = 0; i < list.size(); i++) {
msg.append("\t\t\t<ParameterValueStruct>\n");
msg.append("\t\t\t\t<Name>" + list.get(i).get(0) + "</Name>\n");
msg.append("\t\t\t\t<Value xsi:type=\"xsd:" + list.get(i).get(1) + "</Value>\n");
msg.append("\t\t\t</ParameterValueStruct>\n");
}
msg.append("\t\t\t</ParameterList>\n");
msg.append("\t\t\t<ParameterKey>12345</ParameterKey>\n");
msg.append("\t\t</cwmp:SetParameterValues>\n");
msg.append("\t</soapenv:Body>\n");
// end body
msg.append(envelopeEnd);
return msg;
}
public static void clearSetParamList() {
getSetParamList().clear();
String function = Thread.currentThread().getStackTrace()[1].getMethodName();
String function2 = Thread.currentThread().getStackTrace()[2].getMethodName();
System.out.println(function + " " + function2);
}
public static void initSetParamList() {
String function = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(function + " Creating SET message to initialize the device");
ArrayList<String> list = new ArrayList<String>();
// list = new ArrayList<String>();
// list.add("Device.Services.FAPService.1.FAPControl.LTE.AdminState");
// list.add("boolean" + "\">" + "false");
// setParamList.add(list);
list = new ArrayList<String>();
list.add("Device.ManagementServer.PeriodicInformEnable");
list.add("boolean" + "\">" + "true");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.ManagementServer.PeriodicInformInterval");
list.add("unsignedInt" + "\">" + "30");
getSetParamList().add(list);
}
public static void initSetIPsecParamList() {
String function = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(function + " Creating SET message to initialize the device");
ArrayList<String> list = new ArrayList<String>();
list = new ArrayList<String>();
list.add("Device.IPsec.Enable");
list.add("boolean" + "\">" + "false");
getSetParamList().add(list);
}
public static void initSetFAPParamList() {
String function = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(function + " Creating SET message to initialize the device");
ArrayList<String> list = new ArrayList<String>();
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.PhyCellID");
list.add("string" + "\">" + "210,211,212");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.DLBandwidth");
list.add("string" + "\">" + "100");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.ULBandwidth");
list.add("string" + "\">" + "100");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.PHY.PRACH.RootSequenceIndex");
list.add("string" + "\">" + "738,0,837,12");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNUL");
list.add("string" + "\">" + "18700");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.RF.EARFCNDL");
list.add("string" + "\">" + "700");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.TAC");
list.add("unsignedInt" + "\">" + "1");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID");
list.add("string" + "\">" + "311181");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary");
list.add("boolean" + "\">" + "true");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable");
list.add("boolean" + "\">" + "true");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.FAPControl.LTE.Gateway.S1SigLinkServerList");
list.add("string" + "\">" + "10.9.50.66");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.FAPControl.LTE.Gateway.S1SigLinkPort");
list.add("unsignedInt" + "\">" + "36412");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Time.LocalTimeZone");
list.add("string" + "\">" + "EST-5EDT,M3.2.0/2,M11.1.0/2");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.CellConfig.LTE.RAN.Common.CellIdentity");
list.add("unsignedInt" + "\">" + "53760");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.REM.LTE.EUTRACarrierARFCNDLList");
list.add("string" + "\">" + "700");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.REM.LTE.ScanTimeout");
list.add("unsignedInt" + "\">" + "3600");
getSetParamList().add(list);
list = new ArrayList<String>();
list.add("Device.Services.FAPService.1.REM.LTE.ScanOnBoot");
list.add("boolean" + "\">" + "1");
getSetParamList().add(list);
}
final public static String getXmlString() {
return xmlString.toString();
}
public static ArrayList<ArrayList<String>> getSetParamList() {
return setParamList;
}
public static void setSetParamList(ArrayList<ArrayList<String>> List) {
setParamList = List;
}
}
| 41.471739
| 138
| 0.723646
|
69da2d584015393f8e101472ad65699811124e6c
| 686
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.betula;
import java.beans.PropertyChangeListener;
import java.util.Set;
/**
*
* @author boris.heithecker
*/
public interface Unit {
public static final String PROP_DISPLAYNAME = "displayName";
public static final String PROP_STUDENTS = "students";
public UnitId getUnitId();
public Set<Student> getStudents();
public Student findStudent(StudentId id);
public String getDisplayName();
public void addPropertyChangeListener(PropertyChangeListener l);
public void removePropertyChangeListener(PropertyChangeListener l);
}
| 22.129032
| 71
| 0.744898
|
21b6d201a29c9f9c713152806df97d84ccecfe19
| 1,068
|
public class Lista {
public Elemento prim, ult;
public Lista(){
prim = new Elemento(null);
ult = prim;
}
public void enfileirar(ContaBancaria nova){
Elemento novo = new Elemento(nova);
ult.prox = novo;
ult = novo;
}
public ContaBancaria desenfileirar(){
Elemento aux = prim.prox;
prim.prox = aux.prox;
aux.prox = null;
if(aux == ult)
ult = prim;
return aux.conta;
}
public ContaBancaria buscar(int num){
Elemento aux = prim.prox;
while(aux != null){
if(num == aux.conta.num)
return aux.conta;
aux = aux.prox;
}
return null;
}
public String imprimir(){
StringBuilder sb = new StringBuilder();
Elemento aux = prim.prox;
while(aux != null){
sb.append(aux.conta.dadosConta() + "\n");
aux = aux.prox;
}
return sb.toString();
}
public boolean vazia(){
return prim == ult;
}
}
| 22.25
| 53
| 0.505618
|
f6bdb090364830f273d3cb16d9a222f9d702b435
| 25,118
|
package org.infinispan.distribution.ch.impl;
import static java.lang.Math.min;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import org.infinispan.commons.hash.MurmurHash3;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.distribution.ch.ConsistentHashFactory;
import org.infinispan.globalstate.ScopedPersistentState;
import org.infinispan.marshall.core.Ids;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.topology.PersistentUUID;
import org.jgroups.util.UUID;
/**
* {@link org.infinispan.distribution.ch.ConsistentHashFactory} implementation
* that guarantees that multiple caches with the same members will
* have the same consistent hash (unlike {@link DefaultConsistentHashFactory}).
*
* <p>It has a drawback compared to {@link DefaultConsistentHashFactory} though:
* it can potentially move a lot more segments during a rebalance than
* strictly necessary.
* E.g. {0:AB, 1:BA, 2:CD, 3:DA} could turn into {0:BC, 1:CA, 2:CB, 3:AB} when D leaves,
* even though {0:AB, 1:BA, 2:CB, 3:AC} would require fewer segment ownership changes.
*
* <p>It may also reorder the owners of a segments, e.g. AB -> BA
* (same as {@linkplain DefaultConsistentHashFactory}).
*
* @author Dan Berindei
* @since 5.2
*/
public class SyncConsistentHashFactory implements ConsistentHashFactory<DefaultConsistentHash> {
@Override
public DefaultConsistentHash create(int numOwners, int numSegments, List<Address> members,
Map<Address, Float> capacityFactors) {
checkCapacityFactors(members, capacityFactors);
Builder builder = createBuilder(numOwners, numSegments, members, capacityFactors);
builder.populateOwners();
return new DefaultConsistentHash(numOwners, numSegments, members, capacityFactors, builder.segmentOwners);
}
@Override
public DefaultConsistentHash fromPersistentState(ScopedPersistentState state) {
String consistentHashClass = state.getProperty("consistentHash");
if (!DefaultConsistentHash.class.getName().equals(consistentHashClass))
throw CONTAINER.persistentConsistentHashMismatch(this.getClass().getName(), consistentHashClass);
return new DefaultConsistentHash(state);
}
Builder createBuilder(int numOwners, int numSegments, List<Address> members, Map<Address, Float> capacityFactors) {
return new Builder(numOwners, numSegments, members, capacityFactors);
}
void checkCapacityFactors(List<Address> members, Map<Address, Float> capacityFactors) {
if (capacityFactors != null) {
float totalCapacity = 0;
for (Address node : members) {
Float capacityFactor = capacityFactors.get(node);
if (capacityFactor == null || capacityFactor < 0)
throw new IllegalArgumentException("Invalid capacity factor for node " + node + ": " + capacityFactor);
totalCapacity += capacityFactor;
}
if (totalCapacity == 0)
throw new IllegalArgumentException("There must be at least one node with a non-zero capacity factor");
}
}
@Override
public DefaultConsistentHash updateMembers(DefaultConsistentHash baseCH, List<Address> newMembers,
Map<Address, Float> actualCapacityFactors) {
checkCapacityFactors(newMembers, actualCapacityFactors);
// The ConsistentHashFactory contract says we should return the same instance if we're not making changes
boolean sameCapacityFactors = actualCapacityFactors == null ? baseCH.getCapacityFactors() == null :
actualCapacityFactors.equals(baseCH.getCapacityFactors());
if (newMembers.equals(baseCH.getMembers()) && sameCapacityFactors)
return baseCH;
int numSegments = baseCH.getNumSegments();
int numOwners = baseCH.getNumOwners();
// We assume leavers are far fewer than members, so it makes sense to check for leavers
HashSet<Address> leavers = new HashSet<>(baseCH.getMembers());
leavers.removeAll(newMembers);
// Create a new "balanced" CH in case we need to allocate new owners for segments with 0 owners
DefaultConsistentHash rebalancedCH = null;
// Remove leavers
List<Address>[] newSegmentOwners = new List[numSegments];
for (int s = 0; s < numSegments; s++) {
List<Address> owners = new ArrayList<>(baseCH.locateOwnersForSegment(s));
owners.removeAll(leavers);
if (!owners.isEmpty()) {
newSegmentOwners[s] = owners;
} else {
// this segment has 0 owners, fix it
if (rebalancedCH == null) {
rebalancedCH = create(numOwners, numSegments, newMembers, actualCapacityFactors);
}
newSegmentOwners[s] = rebalancedCH.locateOwnersForSegment(s);
}
}
return new DefaultConsistentHash(numOwners, numSegments, newMembers,
actualCapacityFactors, newSegmentOwners);
}
@Override
public DefaultConsistentHash rebalance(DefaultConsistentHash baseCH) {
DefaultConsistentHash rebalancedCH = create(baseCH.getNumOwners(), baseCH.getNumSegments(), baseCH.getMembers(),
baseCH.getCapacityFactors());
// the ConsistentHashFactory contract says we should return the same instance if we're not making changes
if (rebalancedCH.equals(baseCH))
return baseCH;
return rebalancedCH;
}
@Override
public DefaultConsistentHash union(DefaultConsistentHash ch1, DefaultConsistentHash ch2) {
return ch1.union(ch2);
}
@Override
public boolean equals(Object other) {
return other != null && other.getClass() == getClass();
}
@Override
public int hashCode() {
return -10007;
}
static class Builder {
static final int NO_NODE = -1;
// Input
final int numOwners;
final int numSegments;
// Output
final List<Address>[] segmentOwners;
final int[][] ownerIndices;
// Constant data
final List<Address> sortedMembers;
final int numNodes;
final float[] sortedCapacityFactors;
final float[] distanceFactors;
final float totalCapacity;
final int actualNumOwners;
final int numNodeHashes;
// Hashes use only 63 bits, or the interval 0..2^63-1
final long segmentSize;
final long[] segmentHashes;
final long[][] nodeHashes;
int nodeDistanceUpdates;
final OwnershipStatistics stats;
Builder(int numOwners, int numSegments, List<Address> members, Map<Address, Float> capacityFactors) {
this.numSegments = numSegments;
this.numOwners = numOwners;
this.sortedMembers = sortMembersByCapacity(members, capacityFactors);
this.sortedCapacityFactors = capacityFactorsToArray(sortedMembers, capacityFactors);
this.totalCapacity = computeTotalCapacity();
numNodes = sortedMembers.size();
actualNumOwners = min(numOwners, numNodes);
distanceFactors = capacityFactorsToDistanceFactors();
segmentOwners = new List[numSegments];
ownerIndices = new int[numSegments][];
for (int s = 0; s < numSegments; s++) {
segmentOwners[s] = new ArrayList<>(actualNumOwners);
ownerIndices[s] = new int[actualNumOwners];
}
segmentSize = Long.MAX_VALUE / numSegments;
segmentHashes = computeSegmentHashes(numSegments);
// If we ever make the number of segments dynamic, the number of hashes should be fixed.
// Otherwise the extra hashes would cause extra segment to move on segment number changes.
numNodeHashes = 32 - Integer.numberOfLeadingZeros(numSegments);
nodeHashes = computeNodeHashes();
stats = new OwnershipStatistics(sortedMembers);
}
private float[] capacityFactorsToDistanceFactors() {
// Nodes with capacity factor 0 have been removed
float minCapacity = sortedCapacityFactors[numNodes - 1];
float[] distanceFactors = new float[numNodes];
for (int n = 0; n < numNodes; n++) {
distanceFactors[n] = minCapacity / sortedCapacityFactors[n];
}
return distanceFactors;
}
private float[] capacityFactorsToArray(List<Address> sortedMembers, Map<Address, Float> capacityFactors) {
float[] capacityFactorsArray = new float[sortedMembers.size()];
for (int n = 0; n < sortedMembers.size(); n++) {
capacityFactorsArray[n] = capacityFactors != null ? capacityFactors.get(sortedMembers.get(n)) : 1f;
}
return capacityFactorsArray;
}
private List<Address> sortMembersByCapacity(List<Address> members, Map<Address, Float> capacityFactors) {
if (capacityFactors == null)
return members;
// Only add members with non-zero capacity
List<Address> sortedMembers = new ArrayList<>();
for (Address member : members) {
if (!capacityFactors.get(member).equals(0f)) {
sortedMembers.add(member);
}
}
// Sort in descending order
sortedMembers.sort((a1, a2) -> Float.compare(capacityFactors.get(a2), capacityFactors.get(a1)));
return sortedMembers;
}
int[] computeExpectedSegments(int expectedOwners, float totalCapacity, int iteration) {
int[] expected = new int[numNodes];
float remainingCapacity = totalCapacity;
int remainingCopies = expectedOwners * numSegments;
float averageSegments = (float) remainingCopies / numNodes;
for (int n = 0; n < numNodes; n++) {
float capacityFactor = sortedCapacityFactors[n];
if (capacityFactor == 0f) {
expected[n] = 0;
}
float idealOwnedSegments = remainingCopies * capacityFactor / remainingCapacity;
if (idealOwnedSegments > numSegments) {
remainingCapacity -= capacityFactor;
remainingCopies -= numSegments;
expected[n] = numSegments;
} else {
// All the nodes from now on will have less than numSegments segments,
// so we can stop updating remainingCapacity/remainingCopies
expected[n] = fudgeExpectedSegments(idealOwnedSegments, averageSegments, iteration);
}
}
return expected;
}
static int fudgeExpectedSegments(float idealOwnedSegments, float averageSegments, int iteration) {
// In the first rounds reduce the number of expected segments so every node has a chance
// In the later rounds increase the number of expected segments so every segment eventually finds an owner
// It's harder to allocate the last segments to the nodes with large capacity,
// so the step by which we reduce/increase is not linear with the number of ideal expected segments
// But assign at least one extra segment per node every 5 iterations, in case there are too few segments
float step = Math.max(Math.min(averageSegments * 0.05f, idealOwnedSegments * 0.15f), 1f);
return Math.max((int) (idealOwnedSegments + (iteration - 2.5f ) * step), 0);
}
private long[] computeSegmentHashes(int numSegments) {
assert segmentSize != 0;
long[] segmentHashes = new long[numSegments];
long currentSegmentHash = segmentSize >> 1;
for (int s = 0; s < numSegments; s++) {
segmentHashes[s] = currentSegmentHash;
currentSegmentHash += segmentSize;
}
return segmentHashes;
}
private long[][] computeNodeHashes() {
long[][] nodeHashes = new long[numNodes][];
for (int n = 0; n < numNodes; n++) {
nodeHashes[n] = new long[this.numNodeHashes];
for (int h = 0; h < this.numNodeHashes; h++) {
nodeHashes[n][h] = nodeHash(sortedMembers.get(n), h);
}
Arrays.sort(nodeHashes[n]);
}
return nodeHashes;
}
float computeTotalCapacity() {
if (sortedCapacityFactors == null)
return sortedMembers.size();
float totalCapacity = 0;
for (float sortedCapacityFactor : sortedCapacityFactors) {
totalCapacity += sortedCapacityFactor;
}
return totalCapacity;
}
long nodeHash(Address address, int virtualNode) {
// 64-bit hashes from 32-bit hashes have a non-negligible chance of collision,
// so we try to get all 128 bits from UUID addresses
long[] key = new long[2];
if (address instanceof JGroupsAddress) {
org.jgroups.Address jGroupsAddress = ((JGroupsAddress) address).getJGroupsAddress();
if (jGroupsAddress instanceof UUID) {
key[0] = ((UUID) jGroupsAddress).getLeastSignificantBits();
key[1] = ((UUID) jGroupsAddress).getMostSignificantBits();
} else {
key[0] = address.hashCode();
}
} else if (address instanceof PersistentUUID) {
key[0] = ((PersistentUUID) address).getLeastSignificantBits();
key[1] = ((PersistentUUID) address).getMostSignificantBits();
} else {
key[0] = address.hashCode();
}
return MurmurHash3.MurmurHash3_x64_64(key, virtualNode) & Long.MAX_VALUE;
}
/**
* @return distance between 2 points in the 0..2^63-1 range, max 2^62-1
*/
long distance(long a, long b) {
long distance = a < b ? b - a : a - b;
if ((distance & (1L << 62)) != 0) {
distance = -distance - Long.MIN_VALUE;
}
// For the -2^63..2^63-1 range, the code would be
// if (distance < 0) {
// distance = -distance;
// }
return distance;
}
void populateOwners() {
// List k contains each segment's kth closest available node
PriorityQueue<SegmentInfo>[] segmentQueues = new PriorityQueue[Math.max(1, actualNumOwners)];
for (int i = 0; i < segmentQueues.length; i++) {
segmentQueues[i] = new PriorityQueue<>(numSegments);
}
// Temporary priority queue for one segment's potential owners
PriorityQueue<SegmentInfo> temporaryQueue = new PriorityQueue<>(numNodes);
assignSegments(1, totalCapacity, 1, segmentQueues, temporaryQueue);
assert stats.sumPrimaryOwned() == numSegments;
// The minimum queue count we can use is actualNumOwners - 1
// A bigger queue count improves stability, i.e. a rebalance after a join/leave moves less segments around
// However, the queueCount==1 case is optimized, so actualNumOwners-1 has better performance for numOwners=2
assignSegments(actualNumOwners, totalCapacity, actualNumOwners - 1, segmentQueues, temporaryQueue);
assert stats.sumOwned() == actualNumOwners * numSegments;
}
private void assignSegments(int currentNumOwners, float totalCapacity, int queuesCount,
PriorityQueue<SegmentInfo>[] segmentQueues,
PriorityQueue<SegmentInfo> temporaryQueue) {
int totalCopies = currentNumOwners * numSegments;
// We try to assign the closest node as the first owner, then the 2nd closest node etc.
// But we also try to keep the number of owned segments per node close to the "ideal" number,
// so we start by allocating a smaller number of segments to each node and slowly allow more segments.
for (int loadIteration = 0; stats.sumOwned() < totalCopies; loadIteration++) {
int[] nodeSegmentsToAdd = computeExpectedSegments(currentNumOwners, totalCapacity, loadIteration);
int iterationCopies = 0;
for (int n = 0; n < numNodes; n++) {
iterationCopies += nodeSegmentsToAdd[n];
nodeSegmentsToAdd[n] -= stats.getOwned(n);
}
iterationCopies = Math.max(iterationCopies, totalCopies);
for (int distanceIteration = 0; distanceIteration < numNodes; distanceIteration++) {
if (stats.sumOwned() >= iterationCopies)
break;
populateQueues(currentNumOwners, nodeSegmentsToAdd, queuesCount, segmentQueues, temporaryQueue);
if (!assignQueuedOwners(currentNumOwners, nodeSegmentsToAdd, queuesCount, iterationCopies, segmentQueues))
break;
}
}
}
// Useful for debugging
private BitSet[] computeAvailableSegmentsPerNode(int currentNumOwners) {
BitSet[] nodeSegmentsAvailable = new BitSet[numNodes];
for (int s = 0; s < numSegments; s++) {
if (!segmentIsAvailable(s, currentNumOwners))
continue;
for (int n = 0; n < numNodes; n++) {
if (nodeCanOwnSegment(s, segmentOwners[s].size(), n)) {
if (nodeSegmentsAvailable[n] == null) {
nodeSegmentsAvailable[n] = new BitSet();
}
nodeSegmentsAvailable[n].set(s);
}
}
}
return nodeSegmentsAvailable;
}
private boolean assignQueuedOwners(int currentNumOwners, int[] nodeSegmentsToAdd, int queuesCount,
int iterationCopies, PriorityQueue<SegmentInfo>[] segmentQueues) {
boolean assigned = false;
for (int i = 0; i < queuesCount; i++) {
SegmentInfo si;
while ((si = segmentQueues[i].poll()) != null) {
int ownerPosition = segmentOwners[si.segment].size();
if (nodeSegmentsToAdd[si.nodeIndex] <= 0)
continue;
if (i == 0 ||
segmentIsAvailable(si.segment, currentNumOwners) &&
nodeCanOwnSegment(si.segment, ownerPosition, si.nodeIndex)) {
assignOwner(si.segment, ownerPosition, si.nodeIndex, nodeSegmentsToAdd);
assigned = true;
}
if (stats.sumOwned() >= iterationCopies) {
return assigned;
}
}
segmentQueues[i].clear();
}
return assigned;
}
private void populateQueues(int currentNumOwners, int[] nodeSegmentsToAdd, int queueCount,
PriorityQueue<SegmentInfo>[] segmentQueues,
PriorityQueue<SegmentInfo> temporaryQueue) {
// Bypass the temporary queue if the queue count is 1
SegmentInfo best = null;
for (int s = 0; s < numSegments; s++) {
if (!segmentIsAvailable(s, currentNumOwners))
continue;
for (int n = 0; n < numNodes; n++) {
if (nodeSegmentsToAdd[n] > 0 && nodeCanOwnSegment(s, segmentOwners[s].size(), n)) {
long scaledDistance = nodeSegmentDistance(n, segmentHashes[s]);
if (queueCount > 1) {
SegmentInfo si = new SegmentInfo(s, n, scaledDistance);
temporaryQueue.add(si);
} else {
if (best == null) {
best = new SegmentInfo(s, n, scaledDistance);
} else if (scaledDistance < best.distance) {
best.update(n, scaledDistance);
}
}
}
}
if (queueCount > 1) {
for (int i = 0; i < queueCount && !temporaryQueue.isEmpty(); i++) {
segmentQueues[i].add(temporaryQueue.remove());
}
temporaryQueue.clear();
} else {
if (best != null) {
segmentQueues[0].add(best);
}
best = null;
}
}
}
private boolean segmentIsAvailable(int segment, int currentNumOwners) {
return segmentOwners[segment].size() < currentNumOwners;
}
private long nodeSegmentDistance(int nodeIndex, long segmentHash) {
nodeDistanceUpdates++;
long[] currentNodeHashes = nodeHashes[nodeIndex];
int hashIndex = Arrays.binarySearch(currentNodeHashes, segmentHash);
long scaledDistance;
if (hashIndex > 0) {
// Found an exact match
scaledDistance = 0L;
} else {
// Flip to get the insertion point
hashIndex = -(hashIndex + 1);
long hashBefore = hashIndex > 0 ? currentNodeHashes[hashIndex - 1] : currentNodeHashes[numNodeHashes - 1];
long hashAfter = hashIndex < numNodeHashes ? currentNodeHashes[hashIndex] : currentNodeHashes[0];
long distance = min(distance(hashBefore, segmentHash), distance(hashAfter, segmentHash));
scaledDistance = (long) (distance * distanceFactors[nodeIndex]);
}
return scaledDistance;
}
protected void assignOwner(int segment, int ownerPosition, int nodeIndex, int[] nodeSegmentsWanted) {
assert nodeSegmentsWanted[nodeIndex] > 0;
// One less segment needed for the assigned node
--nodeSegmentsWanted[nodeIndex];
assert segmentOwners[segment].size() == ownerPosition;
segmentOwners[segment].add(sortedMembers.get(nodeIndex));
ownerIndices[segment][ownerPosition] = nodeIndex;
stats.incOwned(nodeIndex, ownerPosition == 0);
// System.out.printf("owners[%d][%d] = %s (%d)\n", segment, ownerPosition, sortedMembers.get(nodeIndex), nodeIndex);
}
boolean nodeCanOwnSegment(int segment, int ownerPosition, int nodeIndex) {
// Return false the node exists in the owners list
return !intArrayContains(ownerIndices[segment], ownerPosition, nodeIndex);
}
boolean intArrayContains(int[] array, int end, int value) {
for (int i = 0; i < end; i++) {
if (array[i] == value)
return true;
}
return false;
}
static class SegmentInfo implements Comparable<SegmentInfo> {
static final int NO_AVAILABLE_OWNERS = -2;
final int segment;
int nodeIndex;
long distance;
SegmentInfo(int segment) {
this.segment = segment;
reset();
}
public SegmentInfo(int segment, int nodeIndex, long distance) {
this.segment = segment;
this.nodeIndex = nodeIndex;
this.distance = distance;
}
void update(int closestNode, long minDistance) {
this.nodeIndex = closestNode;
this.distance = minDistance;
}
boolean isValid() {
return nodeIndex >= 0;
}
void reset() {
update(NO_NODE, Long.MAX_VALUE);
}
boolean hasNoAvailableOwners() {
return nodeIndex == NO_AVAILABLE_OWNERS;
}
void markNoPotentialOwners() {
update(NO_AVAILABLE_OWNERS, Long.MAX_VALUE);
}
@Override
public int compareTo(SegmentInfo o) {
// Sort ascending by distance
return Long.compare(distance, o.distance);
}
@Override
public String toString() {
if (nodeIndex >= 0) {
return String.format("SegmentInfo#%d{n=%d, distance=%016x}", segment, nodeIndex, distance);
}
return String.format("SegmentInfo#%d{%s}", segment, segmentDescription());
}
private String segmentDescription() {
switch (nodeIndex) {
case NO_NODE:
return "NO_NODE";
case NO_AVAILABLE_OWNERS:
return "NO_AVAILABLE_OWNERS";
default:
return String.valueOf(segment);
}
}
}
}
public static class Externalizer extends AbstractExternalizer<SyncConsistentHashFactory> {
@Override
public void writeObject(ObjectOutput output, SyncConsistentHashFactory chf) {
}
@Override
public SyncConsistentHashFactory readObject(ObjectInput unmarshaller) {
return new SyncConsistentHashFactory();
}
@Override
public Integer getId() {
return Ids.SYNC_CONSISTENT_HASH_FACTORY;
}
@Override
public Set<Class<? extends SyncConsistentHashFactory>> getTypeClasses() {
return Collections.singleton(SyncConsistentHashFactory.class);
}
}
}
| 40.97553
| 124
| 0.620233
|
8f51b7bf621f1739b403491f8c7233e693d636e7
| 1,435
|
/*
package leetcode.solutions;
import java.util.*;
/*
Problem : 21
Number leecode problem: 36
https://leetcode.com/problems/sudoku-solver/
Time Complexity: O(2^n)
Space Complexity: O(1)
*/
*/
public class SudokuSolver{
public void solveSudoku(char[][] board){
boolean[][] rows = new boolean[10][10], cols = new boolean[10][10], sectors[10][10];
int auxSec = 1;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
int r = i + 2*i, c = j + 2*j;
for(int i2 = r; i2 < r +3; i2++){
for(int j2 = c; j2 < c + 3; j2++){
if(board[i2][j2] != '.'){
int a = board[i2][j2] - '0';
rows[i2 + 1][a] = cols[j2 + 1][a] = sectors[auxSec][a] = true;
}
}
}
auxSec++;
}
}
}
int[][] coor = {{1,2,3},{4,5,6},{7,8,9}};
private boolean back(char[][] board, boolean[][] rows, boolean[][] cols, boolean[][] sectors, int i, int j){
if(i <= 7 && j == 9){ i++; j = 0; }
if(i == 8 && j == 9){ return true; }
if(board[i][j] != '.')return back(board, rows, cols, sectors,i, j + 1);
for(int t = 1; t <= 9; t++){
if(rows[i+1][t] || cols[j+1][t] || sectors[coor[i/3][i/3]][t])continue;
rows[i+1][t] = cols[j+1][t] = sectors[coor[i/3][i/3]][t] = true;
board[i][j] = (char)(t + '0');
if(back(board, rows, cols, sectors, i, j+1))return true;
rows[i+1][t] = cols[j+1][t] = sectors[coor[i/3][i/3]][t] = false;
board[i][j] = '.';
}
return false;
}
}
| 27.075472
| 109
| 0.507317
|
385d4034c8b42d67f2ab78b7f9275074bef33007
| 391
|
package it.unibz.deltabpmn.dataschema.elements.providers;
import it.unibz.deltabpmn.dataschema.elements.Sort;
/**
* An interface for a factory used to generate {@code Sort} objects.
*/
public interface SortProvider {
/**
* A method for creating {@code Sort} objects.
* @param name A sort name.
* @return A {@code Sort} object.
*/
Sort newSort(String name);
}
| 24.4375
| 68
| 0.677749
|
68a993f2a53830afac2c5581991449c9a0a82c31
| 2,027
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.data.gemfire.function.execution;
import org.apache.geode.cache.RegionService;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.Function;
/**
* Creates an {@literal OnServer} {@link Function} {@link Execution} initialized with
* either a {@link RegionService} or a {@link Pool}.
*
* @author David Turanski
* @author John Blum
* @see org.apache.geode.cache.RegionService
* @see org.apache.geode.cache.client.Pool
* @see org.apache.geode.cache.execute.Execution
* @see org.apache.geode.cache.execute.Function
* @see org.springframework.data.gemfire.function.execution.AbstractClientFunctionTemplate
*/
@SuppressWarnings("unused")
public class GemfireOnServerFunctionTemplate extends AbstractClientFunctionTemplate {
public GemfireOnServerFunctionTemplate(RegionService cache) {
super(cache);
}
public GemfireOnServerFunctionTemplate(Pool pool) {
super(pool);
}
public GemfireOnServerFunctionTemplate(String poolName) {
super(poolName);
}
@Override
protected AbstractFunctionExecution newFunctionExecutionUsingPool(Pool pool) {
return new OnServerUsingPoolFunctionExecution(pool);
}
@Override
protected AbstractFunctionExecution newFunctionExecutionUsingRegionService(RegionService regionService) {
return new OnServerUsingRegionServiceFunctionExecution(regionService);
}
}
| 35.561404
| 118
| 0.789837
|
253c951cd578681a11e17a91c18b7a4abe35e121
| 214
|
package com.mentor4you.repository;
import com.mentor4you.model.Mentees;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MenteeRepository extends JpaRepository<Mentees ,Integer> {
}
| 26.75
| 75
| 0.841121
|
f8be82ddebb2b4a627d81ffe4c6d309c640dd27a
| 1,305
|
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* From: https://github.com/square/retrofit/blob/master/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/StringConverterFactory.java
*/
public class StringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.get("text/plain");
@Nullable @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type,
Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return (Converter<ResponseBody, String>) ResponseBody::string;
}
return null;
}
@Nullable @Override public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return (Converter<String, RequestBody>) StringConverterFactory::create;
}
return null;
}
@SuppressWarnings("deprecation")
private static RequestBody create(String value) {
return RequestBody.create(MEDIA_TYPE, value);
}
}
| 33.461538
| 145
| 0.765517
|
7dfc21579eae83a04de8a88510fd249e64c1a90d
| 5,024
|
package rfx.core.stream.functor.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import rfx.core.model.CallbackResult;
import rfx.core.stream.message.Fields;
import rfx.core.stream.message.Tuple;
import rfx.core.stream.message.Values;
import rfx.core.stream.model.DataFlowInfo;
import rfx.core.stream.topology.BaseTopology;
import rfx.core.util.StringUtil;
import rfx.core.util.Utils;
import akka.event.Logging;
import akka.event.LoggingAdapter;
/**
* @author trieunt
*
*/
public class DataFileSourceFunctor extends DataSourceFunctor {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
public DataFileSourceFunctor(DataFlowInfo dataFlowInfo, BaseTopology topology) {
super(dataFlowInfo, topology);
}
//what data fields that this actor would send to next actor
static Fields outFields = new Fields(DataSourceFunctor.EVENT);
final static String SCHEME_FILE = "file";
final static String SCHEME_HTTP = "http";
final static String SCHEME_FILE_PREFIX = SCHEME_FILE + "://";
final static int BUFFER_SIZE = 5000;
static AtomicLong genId = new AtomicLong();
public static final long getCurrentCount(){
return genId.get();
}
static int mb = 1024*1024;
static final AtomicBoolean notified = new AtomicBoolean(false);
@Override
public void onReceive(Object message) throws Exception {
//System.out.println(message + " at " + System.currentTimeMillis());
if (EMIT_LOG_EVENT.equals(message)) {
if(isEmitting() || isStopEmitting() || isOverMaxConcurrentEmitter() ){
//System.out.println("--------DataFileSourceFunctor.skip-------"+message);
unhandled(message);
return;
}
setEmitting(true);
CallbackResult<String> result = super.doPreProcessing();
System.out.println("doPreProcessing "+result);
if(result != null){
String uriStr = result.getResult();
if(uriStr.startsWith("/")){
uriStr = StringUtil.toString(SCHEME_FILE_PREFIX , uriStr);
} else {
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println(s);
uriStr = StringUtil.toString(SCHEME_FILE_PREFIX, s , "/" , uriStr);
System.out.println(uriStr);
}
URI uri = new URI(uriStr);
notified.set(false);
if(SCHEME_FILE.equals(uri.getScheme())){
int c = 0;
File file = new File(uri);
if( file.isFile() ){
BufferedReader br = null;
try {
System.out.println(genId.incrementAndGet() + " #BEGIN DataFileSourceFunctor uri: " + uri);
br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
this.emit(outFields,line);
if(++c % maxSizeToSleep == 0){
Utils.sleep(400);
}
}
System.out.println(" #END Total: "+c+" rows at file: " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br != null){
br.close();
//System.out.println("Wait "+timeToSleep);
Utils.sleep(timeToSleep);
// get Runtime instance
Runtime instance = Runtime.getRuntime();
// used memory
double usedMemory = (instance.totalMemory() - instance.freeMemory()) / mb;
System.out.println("Used Memory: " + usedMemory);
// free memory
System.out.println("Free Memory: " + instance.freeMemory() / mb);
// Maximum available memory
double maxMemory = instance.maxMemory() / mb;
System.out.println("Max Memory: " + maxMemory);
double ratio = usedMemory / maxMemory;
if(ratio > 0.6){
Utils.sleep(5000);
}
//System.out.println("Done continue ");
}
}
}
} else if(SCHEME_HTTP.equals(uri.getScheme())){
URL url = new URL(result.getResult());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 2048);
String row = null;
int c = 0;
while (true) {
row = in.readLine();
if(row != null){
Tuple newTuple = new Tuple(outFields, new Values(row));
this.emit(newTuple, self());
if(++c % maxSizeToSleep == 0){
Utils.sleep(5);
}
super.doPostProcessing();
} else {
break;
}
}
in.close();
}
} else {
if(!notified.get()){
this.topology.getEmittedDataListener().processingDone();
notified.set(true);
}
}
setEmitting(false);
} else if(STOP_EMIT_LOG_EVENT.equals(message)){
stopEmitting();
}
else {
unhandled(message);
}
}
}
| 31.012346
| 97
| 0.62699
|
640f507c596f1f1b2d1c9c2bf1e38635a5c66c21
| 2,729
|
package com.regnosys.rosetta.blueprints.runner.actions;
import com.google.common.collect.ImmutableList;
import com.regnosys.rosetta.blueprints.runner.data.DataIdentifier;
import com.regnosys.rosetta.blueprints.runner.data.GroupableData;
import com.regnosys.rosetta.blueprints.runner.data.Issue;
import com.regnosys.rosetta.blueprints.runner.nodes.ProcessorNode;
import com.regnosys.rosetta.blueprints.runner.nodes.StatefullNode;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Merger<I, B, O,K> extends StatefullNode implements ProcessorNode<I, O, K> {
private final Function<DataIdentifier, BiConsumer<B, ? extends I>> inserters;
private final Function<K, ? extends B> supplier;
private final Function<B, O> finalizer;
private Map<K, IssuesAndResult<B>> results = new HashMap<>();
private static class IssuesAndResult<O> {
O result;
Collection<Issue> issues = new ArrayList<>();
Map<DataIdentifier, GroupableData<?,?>> precedents = new HashMap<>();
public IssuesAndResult(O result) {
this.result = result;
}
}
public Merger(String uri, String label, Function<DataIdentifier, BiConsumer<B, ? extends I>> insertors,
Function<K, ? extends B> supplier, Function<B, O> finalizer,
DataIdentifier resultType, boolean publishIntermediate) {
super(uri, label, publishIntermediate, resultType);
this.inserters = insertors;
this.supplier = supplier;
this.finalizer = finalizer;
}
@Override
public <T extends I, K2 extends K> Optional<GroupableData<O, K2>> process(GroupableData<T, K2> input) {
IssuesAndResult<B> result = results.getOrDefault(input.getKey(),
new IssuesAndResult<>(supplier.apply(input.getKey())));
@SuppressWarnings("unchecked")
BiConsumer<B, T> inserter = (BiConsumer<B, T>) inserters.apply(input.getIdentifier());
if (inserter!=null) {
inserter.accept(result.result, (T)input.getData());
result.precedents.put(input.getIdentifier(), input);
}
result.issues.addAll(input.getIssues());
results.putIfAbsent(input.getKey(), result);
if (publishIntermediate) {
return Optional.of(input.withNewData(finalizer.apply(result.result), getIdentifier(),
Collections.emptyList(), this));
}
else return Optional.empty();
}
@Override
public Collection<GroupableData<? extends O, ? extends K>> terminate() {
return results.entrySet().stream()
.map(e->GroupableData.withMultiplePrecedents(e.getKey(),
finalizer.apply(e.getValue().result), null, getIdentifier(),
e.getValue().issues, this, e.getValue().precedents.values())
)
.collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
}
}
| 37.383562
| 105
| 0.743496
|
49b35f0aed4ddca1889865acea4e59ecb3cbd848
| 46,575
|
package se.chalmers.datx02.FBA;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pbft.sdk.protobuf.*;
import sawtooth.sdk.protobuf.ConsensusBlock;
import sawtooth.sdk.protobuf.ConsensusPeerInfo;
import sawtooth.sdk.protobuf.ConsensusPeerMessageHeader;
import sawtooth.sdk.protobuf.Transaction;
import sawtooth.sdk.signing.Context;
import sawtooth.sdk.signing.CryptoFactory;
import sawtooth.sdk.signing.Secp256k1PublicKey;
import se.chalmers.datx02.FBA.lib.exceptions.InternalError;
import se.chalmers.datx02.FBA.lib.exceptions.*;
import se.chalmers.datx02.FBA.lib.timing.RetryUntilOk;
import se.chalmers.datx02.FBA.lib.timing.Timeout;
import se.chalmers.datx02.FBA.message.MessageExtension;
import se.chalmers.datx02.FBA.message.MessageType;
import se.chalmers.datx02.FBA.message.ParsedMessage;
import se.chalmers.datx02.lib.Service;
import se.chalmers.datx02.lib.exceptions.BlockNotReadyException;
import se.chalmers.datx02.lib.exceptions.InvalidStateException;
import se.chalmers.datx02.lib.exceptions.ReceiveErrorException;
import se.chalmers.datx02.lib.exceptions.UnknownBlockException;
import java.util.*;
import java.util.stream.Collectors;
import static se.chalmers.datx02.FBA.lib.Hash.verifySha512;
import static se.chalmers.datx02.FBA.message.MessageExtension.logMessage;
import static se.chalmers.datx02.FBA.message.MessageType.*;
/*
todo:
IMPORTANT:
If anything fails, double check for rust syntax:
try_fold
?;
[..]
&mut
Also check for: References to lists (Create new when necessary to not manipulate data)
*/
public class Node {
/*
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private Service service;
private State state;
private MessageLog msg_log;
private List<Transaction> candidateSet;
private List<Transaction> failedTransactions;
public Node(Config config, ConsensusBlock chainHead, List<ConsensusPeerInfo> connected_peers, Service service, State state){
this.service = service;
this.msg_log = new MessageLog(config);
this.state = state;
msg_log.addValidatedBlock(chainHead);
this.state.setChainHead(chainHead.getBlockId().toByteArray());
if(chainHead.getBlockNum() > 1){
try {
// If starting up with a block that has a consensus seal, update the view to match
PbftSeal seal = PbftSeal.parseFrom(chainHead.getPayload());
this.state.setView(seal.getInfo().getView());
logger.info(String.format("Updated view to %d on startup", this.state.getView()));
} catch (InvalidProtocolBufferException e) {
// ignore
}
// If connected to any peers already, send bootstrap commit messages to them
for(ConsensusPeerInfo peer : connected_peers){
try {
broadcastBootstrapCommit(peer.getPeerId().toByteArray());
} catch (InternalError | SerializationError e) {
logger.error("Failed to broadcast bootstrap commit due to error: " + e);
}
}
}
if(state.isPrimary()){
try {
this.service.initializeBlock(null);
} catch (InvalidStateException | UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldnt initialize block on startup due to error: %s", e));
}
}
}
public void onPeerMessage(ParsedMessage msg) throws InvalidMessage {
logger.trace(state + ": Got peer message: " + logMessage(msg.info()));
if(state.getMembers().contains(msg.info().getSignerId().toByteArray())){
throw new InvalidMessage("Received message from node (" + HexBin.encode(msg.info().getSignerId().toByteArray())
+ ") that is not a member of the PBFT network");
}
MessageType msg_type = MessageType.from(msg.info().getMsgType());
if(state.getMode() == State.Mode.ViewChanging
&& msg_type != NewView
&& msg_type != MessageType.ViewChange){
logger.debug(state + ": Node is view changing: ignoring " + msg_type + " message");
return;
}
try {
switch (msg_type) {
case PrePrepare:
handlePrePrepare(msg);
break;
case Prepare:
handlePrepare(msg);
break;
case Commit:
handleCommit(msg);
break;
case ViewChange:
handleViewChange(msg);
break;
case NewView:
handleNewView(msg);
break;
case SealRequest:
handleSealRequest(msg);
break;
case Seal:
handleSealResponse(msg);
break;
default:
logger.warn("Received message with unknown type: " + msg_type);
break;
}
}
catch(Exception e){
logger.error(String.format("Node failed to handle a message due to error: %s", e));
}
}
public void handlePrePrepare(ParsedMessage msg) throws InvalidMessage, FaultyPrimary {
if(msg.info().getSignerId().toByteArray() != state.getPrimaryId()){
logger.warn(String.format("Got PrePrepare from a secondary node {%s}; ignoring message",
Arrays.toString(msg.info().getSignerId().toByteArray())));
return;
}
if(msg.info().getView() != state.getView()){
throw new InvalidMessage(String.format("Node is on view {%d}, but a PrePrepare for view {%d} was received",
state.getView(),
msg.info().getView()));
}
// Check that no `PrePrepare`s already exist with this view and sequence number but a
// different block; if this is violated, the primary is faulty so initiate a view change
List<ParsedMessage> messages = msg_log.getMessageOfTypeSeqView(PrePrepare, msg.info().getSeqNum(), msg.info().getView());
List<ParsedMessage> messagesFiltered = messages.stream().filter(msgF -> msgF.getBlockId().toByteArray() == msg.getBlockId().toByteArray()).collect(Collectors.toList());
if(!messagesFiltered.isEmpty()){
startViewChange(state.getView() + 1);
throw new FaultyPrimary(String.format("When checking PrePrepare with block {%s}, found PrePrepare(s) with same view and seq num but mismatched block(s): {%s}",
HexBin.encode(msg.getBlockId().toByteArray()),
messagesFiltered));
}
msg_log.addMessage(msg);
tryPreparing(msg.getBlockId().toByteArray());
}
public void handlePrepare(ParsedMessage msg) throws InvalidMessage, FaultyPrimary, InternalError {
PbftMessageInfo info = msg.info();
byte[] block_id = msg.getBlockId().toByteArray();
if(msg.info().getView() != state.getView()){
throw new InvalidMessage(String.format("Node is on view {%d}, but a Prepare for view {%d} was received",
state.getView(),
msg.info().getView()));
}
if(info.getSignerId().toByteArray() == state.getPrimaryId()){
startViewChange(state.getView() + 1);
throw new FaultyPrimary(String.format("Received Prepare from primary at view {%d}, seq_num {%d}",
state.getView(),
state.getSeqNum()));
}
msg_log.addMessage(msg);
if(info.getSeqNum() == state.getSeqNum()
&& state.getPhase() == State.Phase.Preparing){
boolean has_matching_pre_prepare = msg_log.hashPrePrepare(info.getSeqNum(), info.getView(), block_id);
boolean has_required_prepares = (
msg_log.getMessageOfTypeSeqViewBlock(MessageType.Prepare, info.getSeqNum(), info.getView(), block_id)
.size() > 2 * state.getFaultyNodes()
);
if(has_matching_pre_prepare && has_required_prepares){
state.switchPhase(State.Phase.Commiting, false);
broadcastPBFTMessage(state.getView(), state.getSeqNum(), MessageType.Commit, block_id);
}
}
}
public void handleCommit(ParsedMessage msg) throws InvalidMessage, ServiceError {
PbftMessageInfo info = msg.info();
byte[] block_id = msg.getBlockId().toByteArray();
if(msg.info().getView() != state.getView()){
throw new InvalidMessage(String.format("Node is on view {%d}, but a Commit for view {%d} was received",
state.getView(),
msg.info().getView()));
}
msg_log.addMessage(msg);
if(info.getSeqNum() == state.getSeqNum()
&& state.getPhase() == State.Phase.Commiting){
boolean has_matching_pre_prepare = msg_log.hashPrePrepare(info.getSeqNum(), info.getView(), block_id);
boolean has_required_commits = (
msg_log.getMessageOfTypeSeqViewBlock(MessageType.Commit, info.getSeqNum(), info.getView(), block_id)
.size() > 2 * state.getFaultyNodes()
);
if(has_matching_pre_prepare && has_required_commits){
try {
service.commitBlock(block_id);
} catch (UnknownBlockException | ReceiveErrorException e) {
throw new ServiceError(String.format("Failed to commit block {%s}", HexBin.encode(block_id)));
}
try {
state.switchPhase(State.Phase.Finishing, false);
} catch (InternalError e) {
logger.error("Failed to switch phase due: " + e);
}
state.commit_timeout.stop();
}
}
}
public void handleViewChange(ParsedMessage msg){
long msg_view = msg.info().getView();
if(msg_view <= state.getView()
|| state.getMode() == State.Mode.ViewChanging
&& msg_view < state.getMode().getViewChanging()){
logger.debug(String.format("Ignoring stale view change message for view {%d}", msg_view));
return;
}
msg_log.addMessage(msg);
boolean is_later_view = (state.getMode() == State.Mode.Normal
|| state.getMode() == State.Mode.ViewChanging
&& msg_view > state.getMode().getViewChanging());
boolean start_view_change = (msg_log.getMessageOfTypeView(MessageType.ViewChange, msg_view).size() > state.getFaultyNodes());
if(is_later_view && start_view_change){
logger.info(String.format("%s Received f + 1 ViewChange messages; starting early view change", state));
startViewChange(msg_view);
return;
}
List<ParsedMessage> messages = msg_log.getMessageOfTypeView(MessageType.ViewChange, msg_view);
// If there are 2f + 1 ViewChange messages and the view change timeout is not already
// started, update the timeout and start it
if(!state.view_change_timeout.isActive() && messages.size() > state.getFaultyNodes()*2){
state.view_change_timeout = new Timeout(state.view_change_duration.multipliedBy(msg_view - state.getView()));
state.view_change_timeout.start();
}
List<ParsedMessage> messages_from_other_nodes = messages.stream().filter(x -> !x.fromSelf()).collect(Collectors.toList());
if(state.isPrimaryAtView(msg_view)
&& messages_from_other_nodes.size() >= 2 * state.getFaultyNodes()){
PbftNewView.Builder new_viewBuilder = PbftNewView.newBuilder()
.setInfo(
MessageExtension.newMessageInfo(NewView, msg_view, state.getSeqNum()-1, state.getPeerId())
);
// Add votes
int i = 0;
for(PbftSignedVote vote : signedVotesFromMessages(messages_from_other_nodes)){
new_viewBuilder.setViewChanges(i++, vote);
}
PbftNewView new_view = new_viewBuilder.build();
logger.trace(String.format("Created NewView message {%s}", new_view));
broadcastMessage(new ParsedMessage(new_view));
}
}
public void handleNewView(ParsedMessage msg) throws InternalError, ServiceError, InvalidMessage {
PbftNewView new_view = msg.getNewViewMessage();
try {
verifyNewView(new_view);
} catch (InvalidMessage e) {
throw new InvalidMessage("NewView failed verification - Error was: " + e);
}
if(state.isPrimary()){
try {
service.cancelBlock();
} catch (InvalidStateException | ReceiveErrorException e) {
logger.info(String.format("Failed to cancel block when becoming secondary: %s", e));
}
}
state.setView(new_view.getInfo().getView());
state.view_change_timeout.stop();
logger.info(String.format("%s: Updated to view %d", state, state.getView()));
state.setModeNormal();
if(state.getPhase() != State.Phase.Finishing){
state.switchPhase(State.Phase.PrePreparing, false);
}
state.idle_timeout.start();
if(state.isPrimary()){
try {
service.initializeBlock(null);
} catch (InvalidStateException | UnknownBlockException | ReceiveErrorException e) {
throw new ServiceError(String.format("Couldn't initialize block after view change, error: %s", e));
}
}
}
public void handleSealRequest(ParsedMessage msg){
if(state.getSeqNum() == msg.info().getSeqNum() + 1){
try {
sendSealResponse(msg.info().getSignerId().toByteArray());
} catch (InternalError e) {
logger.error(String.format("Failed to sendSealResponse from handleSealRequest, due to: %s", e));
}
}
else if(state.getSeqNum() == msg.info().getSeqNum()){
msg_log.addMessage(msg);
}
}
public void handleSealResponse(ParsedMessage msg) throws InvalidMessage {
PbftSeal seal = msg.getSeal();
try {
state.switchPhase(State.Phase.Finishing, false);
return;
} catch (InternalError internalError) {
logger.error("Failed to switch phase on handleSealResponse");
}
ConsensusBlock previous_idBlock = msg_log.getBlockWithId(seal.getBlockId().toByteArray());
byte[] previous_id;
if(previous_idBlock == null)
throw new InvalidMessage(String.format("Received a seal for a block (%s) that the node does not have",
HexBin.encode(seal.getBlockId().toByteArray())));
else{
if(previous_idBlock.getBlockNum() != state.getSeqNum()){
throw new InvalidMessage(String.format("Received a seal for block {%s}, but block_num does not match node's " +
"seq_num: {%d} != {%d}",
HexBin.encode(seal.getBlockId().toByteArray()),
previous_idBlock.getBlockNum(),
state.getSeqNum()
));
}
else
previous_id = previous_idBlock.getBlockId().toByteArray();
}
try {
verifyConsensusSeal(seal, previous_id);
} catch (InvalidMessage e) {
throw new InvalidMessage("Consensus seal failed verification - Error was:" + e);
}
try {
catchup(false, seal);
} catch (ServiceError e) {
logger.error(String.format("Failed to catchup due: %s", e));
}
}
public void onBlockNew(ConsensusBlock block) throws InternalError, ServiceError {
logger.info(String.format("%s: Got BlockNew: %d / %s",
state,
block.getBlockNum(),
HexBin.encode(block.getBlockId().toByteArray())));
logger.trace(String.format("Block details: %s", block));
// Only future blocks should be considered since committed blocks are final
if(block.getBlockNum() < state.getSeqNum()){
try {
service.failBlock(block.getBlockId().toByteArray());
} catch (UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldn't fail block due to error: %s", e));
}
throw new InternalError(String.format("Received block {%d} / {%s} that is older than the current sequence number: {%d}",
block.getBlockNum(),
HexBin.encode(block.getBlockId().toByteArray()),
state.getSeqNum()));
}
// Make sure the node already has the previous block, since the consensus seal can't be
// verified without it
ConsensusBlock previous_block = msg_log.getBlockWithId(block.getPreviousId().toByteArray());
if(previous_block == null)
previous_block = msg_log.getUnvalidatedBlockWithId(block.getPreviousId().toByteArray());
if(previous_block == null){
try {
service.failBlock(block.getBlockId().toByteArray());
} catch (UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldn't fail block due to error: %s", e));
}
throw new InternalError(String.format("Received block {%d} / {%s} but node does not have previous block: {%s}",
block.getBlockNum(),
HexBin.encode(block.getBlockId().toByteArray()),
HexBin.encode(block.getPreviousId().toByteArray())));
}
// Make sure that the previous block has the previous block number (enforces that blocks
// are strictly monotically increasing by 1)
if(previous_block.getBlockNum() != block.getBlockNum() - 1){
try {
service.failBlock(block.getBlockId().toByteArray());
} catch (UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldn't fail block due to error: %s", e));
}
throw new InternalError(String.format("Received block {%d} / {%s} but its previous block {%d} / {%s} " +
"does not have the previous block_num",
block.getBlockNum(),
HexBin.encode(block.getBlockId().toByteArray()),
block.getBlockNum() - 1,
HexBin.encode(block.getPreviousId().toByteArray())));
}
msg_log.addUnvalidatedBlock(block);
// Have the validator check the block
List<byte[]> block_check = new ArrayList<>();
block_check.add(block.getBlockId().toByteArray());
try {
service.checkBlocks(block_check);
} catch (UnknownBlockException | ReceiveErrorException e) {
throw new ServiceError(String.format("Failed to check block {%d} / {%s} ",
block.getBlockNum(),
HexBin.encode(block.getBlockId().toByteArray())));
}
}
public void onBlockValid(byte[] blockId) throws InvalidMessage {
logger.info(String.format("Got blockvalid: %s",
HexBin.encode(blockId)));
ConsensusBlock block = msg_log.blockValidated(blockId);
if(block == null){
throw new InvalidMessage(String.format("Received BlockValid message for an unknown block: {%s}",
HexBin.encode(blockId)));
}
tryHandlingBlock(block);
}
public void onBlockInvalid(byte[] blockId) throws InvalidMessage {
logger.info(String.format("Got BlockInvalid: %s", HexBin.encode(blockId)));
if(!msg_log.blockInvalidated(blockId)){
throw new InvalidMessage(String.format("Received BlockInvalid message for an unknown block: %s",
HexBin.encode(blockId)));
}
try {
service.failBlock(blockId);
} catch (UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldn't fail block due to error: %s", e));
}
}
public boolean tryHandlingBlock(ConsensusBlock block) throws InvalidMessage {
if(block.getBlockNum() > state.getSeqNum() + 1)
return true;
PbftSeal seal;
try {
seal = verifyConsensusSealFromBlock(block);
} catch (InvalidMessage | SerializationError | InternalError e) {
throw new InvalidMessage("Consensus seal failed verification - Error was:" + e);
}
boolean is_waiting = (state.getPhase() == State.Phase.Finishing);
if(block.getBlockNum() > state.getSeqNum() && !is_waiting){
try {
catchup(true, seal);
} catch (ServiceError e) {
logger.error(String.format("Failed to catchup due: %s", e));
return false;
}
}
else if(block.getBlockNum() == state.getSeqNum()){
if(block.getSignerId().toByteArray() == state.getPeerId() && state.isPrimary()){
logger.info("Broadcasting PrePrepares");
broadcastPBFTMessage(state.getView(),
state.getSeqNum(),
PrePrepare,
block.getBlockId().toByteArray());
}
else{
tryPreparing(block.getBlockId().toByteArray());
}
}
return true;
}
public void catchup(boolean catchup_again, PbftSeal seal) throws ServiceError {
logger.info(String.format("%s: Attempting to commit block %d using catch-up",
state,
state.getSeqNum()));
List<ParsedMessage> messages = new ArrayList<>();
for(PbftSignedVote vote : seal.getCommitVotesList()){
try {
messages.add(new ParsedMessage(vote));
} catch (SerializationError serializationError) {
messages = null; // Failed
break;
}
}
long view = messages.get(0).info().getView();
if(view != state.getView()){
logger.info(String.format("Updating view from {%d} to {%d}",
state.getView(),
view));
state.setView(view);
}
for(ParsedMessage message : messages){
msg_log.addMessage(message);
}
try {
service.commitBlock(seal.getBlockId().toByteArray());
} catch (UnknownBlockException | ReceiveErrorException e) {
throw new ServiceError(String.format("Failed to commit block with catch-up {%d} / {%s}",
state.getSeqNum(),
HexBin.encode(seal.getBlockId().toByteArray())));
}
state.idle_timeout.stop();
try {
state.switchPhase(State.Phase.Finishing, catchup_again);
} catch (InternalError e) {
logger.error("Failed to switch phase due: " + e);
}
}
public void onBlockCommit(byte[] blockId) throws ServiceError {
logger.info(String.format("%s: Got BlockCommit for {%s}", state, HexBin.encode(blockId)));
boolean is_catching_up = (state.getPhase().getFinishing()
&& state.getPhase() == State.Phase.Finishing);
List<byte[]> invalid_block_ids = msg_log.getBlocksWithNum(state.getSeqNum())
.stream().map(x -> {
if(x.getBlockId().toByteArray() != blockId)
return x.getBlockId().toByteArray();
else
return null;
}).filter(Objects::nonNull).collect(Collectors.toList());
for(byte[] id : invalid_block_ids){
try {
service.failBlock(id);
} catch (UnknownBlockException | ReceiveErrorException e) {
logger.error(String.format("Couldn't fail block %s due to error %s", HexBin.encode(id),e));
}
}
state.setSeqNum(state.getSeqNum() + 1);
state.setModeNormal();
try {
state.switchPhase(State.Phase.PrePreparing, false);
} catch (InternalError internalError) {
logger.error(String.format("Failed to switch phase on onBlockCommit"));
}
state.setChainHead(blockId);
List<byte[]> requesters = msg_log.getMessageOfTypeSeq(SealRequest, state.getSeqNum() - 1)
.stream().map(req -> req.info().getSignerId().toByteArray()).collect(Collectors.toList());
for(byte[] req : requesters){
try {
sendSealResponse(req);
} catch (InternalError e) {
logger.error(String.format("Failed to send seal response due to: {%s}", e));
}
}
updateMembership(blockId);
if(state.atForcedViewChange())
state.setView(state.getView() + 1);
msg_log.garbageCollect(state.getSeqNum());
List<ConsensusBlock> grandchildren = msg_log.getBlocksWithNum(state.getSeqNum() + 1);
try{
for(ConsensusBlock block : grandchildren){
if(tryHandlingBlock(block))
return;
}
return; // return if succeded
}
catch (InvalidMessage invalidMessage) { } // ignore
if(is_catching_up){
logger.info(String.format("%s: Requesting seal to finish catch-up to block %s",
state,
state.getSeqNum()));
broadcastPBFTMessage(state.getView(),
state.getSeqNum(),
SealRequest,
new byte[]{});
return;
}
state.idle_timeout.start();
List<byte[]> block_ids = msg_log.getBlocksWithNum(state.getSeqNum())
.stream().map(block -> block.getBlockId().toByteArray())
.collect(Collectors.toList());
for(byte[] id : block_ids){
tryPreparing(id);
}
if(state.isPrimary()){
logger.info(String.format("%s: Initializing block on top of %s",
state,
HexBin.encode(blockId)));
try {
service.initializeBlock(blockId);
} catch (InvalidStateException | ReceiveErrorException | UnknownBlockException e) {
throw new ServiceError(String.format("Couldn't initialize block after commit, error: %s", e));
}
}
}
public void updateMembership(byte[] blockId){
RetryUntilOk retryUntilOk = new RetryUntilOk(state.exponential_retry_base, state.exponential_retry_max);
Map<String, String> settings = retryUntilOk.run(() -> service.getSettings(blockId, Collections.singletonList("sawtooth.consensus.pbft.members")));
List<byte[]> on_chain_members = Config.getMembersFromSettings(settings);
if(on_chain_members != state.getMembers()){
logger.info(String.format("Updating membership: %s", on_chain_members));
state.setMembers(on_chain_members);
long faulty_nodes = (state.getMembers().size() - 1)/3;
if(faulty_nodes == 0){
logger.warn("This network no longer contains enough nodes to be fault tolerant");
}
state.setFaultyNodes(faulty_nodes);
}
}
public void tryPreparing(byte[] blockId){
ConsensusBlock block = msg_log.getBlockWithId(blockId);
if(block != null){
if(state.getPhase() == State.Phase.PrePreparing
&& msg_log.hashPrePrepare(state.getSeqNum(), state.getView(), blockId)
&& block.getBlockNum() == state.getSeqNum()){
try {
state.switchPhase(State.Phase.Preparing, false);
state.idle_timeout.stop();
state.commit_timeout.start();
if(!state.isPrimary())
broadcastPBFTMessage(state.getView(),
state.getSeqNum(),
Prepare,
blockId);
} catch (InternalError internalError) {
logger.error("Failed to switch phase on tryPreparing");
}
}
}
}
public void onPeerConnected(byte[] peerId){
if(!state.getMembers().contains(peerId)
|| state.getSeqNum() == 1)
return;
try {
broadcastBootstrapCommit(peerId);
} catch (InternalError | SerializationError e) {
logger.error(String.format("Failed to broadcast Bootstrap Commit due to error %s", e));
}
}
public void broadcastBootstrapCommit(byte[] peerId) throws InternalError, SerializationError {
long view = 0;
if(state.getSeqNum() != 2){
ConsensusBlock block = msg_log.getBlockWithId(state.getChainHead());
if(block == null)
throw new InternalError(String.format("Node does not have chain head {%s} in its log", Arrays.toString(state.getChainHead())));
else{
try {
view = PbftSeal.parseFrom(block.getPayload())
.getInfo().getView();
} catch (InvalidProtocolBufferException e) {
throw new SerializationError(String.format("Error parsing seal from chain head %s", e));
}
}
}
PbftMessageInfo commit = MessageExtension.newMessageInfo(Commit, view, state.getSeqNum()-1, state.getPeerId());
service.sendTo(peerId, "Commit", commit.toByteArray());
}
public List<PbftSignedVote> signedVotesFromMessages(List<ParsedMessage> msgs){
return msgs.stream()
.map(m -> PbftSignedVote.newBuilder()
.setHeaderBytes(ByteString.copyFrom(m.getHeaderBytes()))
.setHeaderSignature(ByteString.copyFrom(m.getHeaderSignature()))
.setMessageBytes(ByteString.copyFrom(m.getMessageBytes()))
.build())
.collect(Collectors.toList());
}
protected static class DoubleKey<T,F>{
private T key1;
private F key2;
public DoubleKey(T key1, F key2){
this.key1 = key1;
this.key2 = key2;
}
}
protected static class DoubleKeyComparator implements Comparator<DoubleKey>{
@Override
public int compare(DoubleKey o1, DoubleKey o2) {
if(o1.key1 == o2.key1 && o1.key2 == o2.key2)
return 0;
else
return -1;
}
}
public PbftSeal buildSeal() throws InternalError {
logger.trace(String.format("%s: Building seal for block %d", state, state.getSeqNum() - 1));
List<ParsedMessage> msgs = msg_log.getMessageOfTypeSeq(Commit, state.getSeqNum() - 1);
Map<DoubleKey<byte[], Long>, List<ParsedMessage>> msgsMap = new TreeMap<>(new DoubleKeyComparator());
List<ParsedMessage> messages = null;
long view = 0;
byte[] block_id = null;
// filter out
msgs = msgs.stream()
.filter(msg -> !msg.fromSelf())
.collect(Collectors.toList());
// add to map
for(ParsedMessage msg : msgs){
DoubleKey key = new DoubleKey<>(msg.getBlockId().toByteArray(), msg.info().getView());
msgsMap.computeIfAbsent(key, k -> new ArrayList<>());
msgsMap.get(key).add(msg);
}
for(Map.Entry<DoubleKey<byte[], Long>, List<ParsedMessage>> entry : msgsMap.entrySet()){
if(entry.getValue().size() >= 2 * state.getFaultyNodes()) {
messages = entry.getValue();
break;
}
}
if(messages == null)
throw new InternalError("Couldn't find 2f commit messages in the message log for building a seal");
PbftSeal.Builder sealBuilder = PbftSeal.newBuilder()
.setInfo(
MessageExtension.newMessageInfo(Seal, view, state.getSeqNum()-1, state.getPeerId())
)
.setBlockId(ByteString.copyFrom(block_id));
int i = 0;
for(PbftSignedVote voteSeal : signedVotesFromMessages(messages)){
sealBuilder.setCommitVotes(i++, voteSeal);
}
PbftSeal seal = sealBuilder.build();
logger.trace("Seal created: " + logMessage(seal));
return seal;
}
@FunctionalInterface
public interface InvalidMessageFunction<T, R> {
R apply(T t) throws InvalidMessage;
}
public <R> byte[] verifyVote(PbftSignedVote vote, MessageType expected_type, InvalidMessageFunction<PbftMessage,R> validation_criteria) throws SerializationError, InvalidMessage, SigningError {
PbftMessage pbft_message;
ConsensusPeerMessageHeader header;
try {
pbft_message = PbftMessage.parseFrom(vote.getMessageBytes());
} catch (InvalidProtocolBufferException e) {
throw new SerializationError(String.format("Error parsing PbftMessage from vote, %s", e));
}
try {
header = ConsensusPeerMessageHeader.parseFrom(vote.getHeaderBytes());
} catch (InvalidProtocolBufferException e) {
throw new SerializationError(String.format("Error parsing header from vote, %s", e));
}
logger.trace(String.format("Verifying vote with PbftMessage: {%s} and header: {%s}", pbft_message, header));
if(header.getSignerId() != pbft_message.getInfo().getSignerId()){
throw new InvalidMessage(String.format("Received a vote where PbftMessage's signer ID {%s} " +
"and PeerMessage's signer ID {%s} dont match",
pbft_message.getInfo().getSignerId(),
header.getSignerId()));
}
MessageType msg_type = MessageType.from(pbft_message.getInfo().getMsgType());
if(msg_type != expected_type)
throw new InvalidMessage(String.format("Received a {%s} vote, but expected a {%s}", msg_type, expected_type));
Secp256k1PublicKey key = Secp256k1PublicKey.fromHex(HexBin.encode(header.getSignerId().toByteArray()));
Context context = CryptoFactory.createContext("secp256k1");
if(!context.verify(HexBin.encode(vote.getHeaderSignature().toByteArray()),
vote.getHeaderBytes().toByteArray(),
key)){
throw new SigningError(String.format("Vote (%s) failed signature verification", vote));
}
try {
verifySha512(vote.getMessageBytes().toByteArray(), header.getContentSha512().toByteArray());
}
catch(SigningError e){
return null;
}
try {
validation_criteria.apply(pbft_message);
}
catch(InvalidMessage e){
return null;
}
return pbft_message.getInfo().getSignerId().toByteArray();
}
public void verifyNewView(PbftNewView new_view) throws InvalidMessage {
if(new_view.getInfo().getView() <= state.getView()){
throw new InvalidMessage(String.format("Node is on view {%d}, but received NewView message for view {%d}",
state.getView(),
new_view.getInfo().getView()));
}
if(new_view.getInfo().getSignerId().toByteArray() != state.getPrimaryIdAtView(new_view.getInfo().getView())){
throw new InvalidMessage(String.format("Received NewView message for view {%d} that is not from the primary for that view",
new_view.getInfo().getView()));
}
List<byte[]> voter_ids = null;
for(PbftSignedVote vote : new_view.getViewChangesList()){
byte[] id;
try {
id = verifyVote(vote, ViewChange, msg -> {
if (msg.getInfo().getView() != new_view.getInfo().getView()) {
throw new InvalidMessage(String.format("ViewChange's view number (%d) doesn't match NewView's view number (%d)",
msg.getInfo().getView(),
new_view.getInfo().getView()));
}
return msg;
});
} catch (SerializationError | SigningError | InvalidMessage e) {
voter_ids = null;
break;
}
voter_ids.add(id);
}
List<byte[]> peer_ids = state.getMembers()
.stream()
.filter(pid -> pid != new_view.getInfo().getSignerId().toByteArray())
.collect(Collectors.toList());
logger.trace(String.format("Comparing voter IDs (%s) with member IDs - primary (%s)", voter_ids, peer_ids));
if(Collections.indexOfSubList(peer_ids, voter_ids) == -1){
List<byte[]> newsub = new ArrayList<>(peer_ids); // clone
throw new InvalidMessage(String.format("NewView contains vote(s) from invalid IDs: %s",
newsub.removeAll(voter_ids)
));
}
if(voter_ids.size() < 2 * state.getFaultyNodes()){
throw new InvalidMessage(String.format("NewView needs {%d} votes, but only {%d} found",
2 * state.getFaultyNodes(),
voter_ids.size()));
}
}
public PbftSeal verifyConsensusSealFromBlock(ConsensusBlock block) throws InvalidMessage, SerializationError, InternalError {
if(block.getBlockNum() < 2)
return PbftSeal.newBuilder().build();
if(block.getPayload().isEmpty())
throw new InvalidMessage("Block published without a seal");
PbftSeal seal;
try {
seal = PbftSeal.parseFrom(block.getPayload().toByteArray());
} catch (InvalidProtocolBufferException e) {
throw new SerializationError("Error parsing seal for verification");
}
logger.trace(String.format("Parsed seal: %s", logMessage(seal)));
if(seal.getBlockId() != block.getPreviousId())
throw new InvalidMessage(String.format("Seal's ID (%s) doesn't match block's previous ID (%s)",
HexBin.encode(seal.getBlockId().toByteArray()),
HexBin.encode(block.getPreviousId().toByteArray())));
ConsensusBlock proven_block_previous_id = msg_log.getBlockWithId(seal.getBlockId().toByteArray());
if(proven_block_previous_id == null)
throw new InternalError(String.format("Got seal for block {%s}, but block was not found in the log",
seal.getBlockId()));
try {
verifyConsensusSeal(seal, proven_block_previous_id.getBlockId().toByteArray());
} catch (InvalidMessage invalidMessage) {
return null;
}
return seal;
}
public void verifyConsensusSeal(PbftSeal seal, byte[] previousId) throws InvalidMessage {
List<byte[]> voter_ids = new ArrayList<>();
for(PbftSignedVote vote : seal.getCommitVotesList()){
byte[] id;
try {
id = verifyVote(vote, Commit, msg -> {
if (msg.getBlockId() != seal.getBlockId())
throw new InvalidMessage("Commit vote's block ID (" + msg.getBlockId() + ") doesn't match seal's ID (" + seal.getBlockId() + ")");
if (msg.getInfo().getView() != seal.getInfo().getView())
throw new InvalidMessage("Commit vote's view (" + msg.getInfo().getView() + ") doesn't match seal's view (" + seal.getInfo().getView() + ")");
if (msg.getInfo().getSeqNum() != seal.getInfo().getSeqNum())
throw new InvalidMessage("Commit vote's seqnum (" + msg.getInfo().getSeqNum() + ") doesn't match seal's seqnum (" + seal.getInfo().getSeqNum() + ")");
return msg;
});
} catch (SerializationError | SigningError | InvalidMessage e) {
voter_ids = null;
break;
}
voter_ids.add(id);
}
logger.trace("Getting on-chain list of members to verify seal");
RetryUntilOk retryUntilOk = new RetryUntilOk(state.exponential_retry_base, state.exponential_retry_max);
// All of the votes in a seal must come from PBFT members, and the primary can't explicitly
// vote itself, since building a consensus seal is an implicit vote. Check that the votes
// received are from a subset of "members - seal creator". Use the list of members from the
// block previous to the one this seal verifies, since that represents the state of the
// network at the time this block was voted on.
Map<String, String> settings = retryUntilOk.run(() -> service.getSettings(previousId,
Arrays.asList("sawtooth.consensus.fba.members")
));
List<byte[]> members = Config.getMembersFromSettings(settings);
if(!members.contains(seal.getInfo().getSignerId().toByteArray()))
throw new InvalidMessage(String.format("Consensus seal is signed by an unknown peer: %s", seal.getInfo().getSignerId()));
List<byte[]> peer_ids = members
.stream()
.filter(pid -> pid != seal.getInfo().getSignerId().toByteArray())
.collect(Collectors.toList());
logger.trace(String.format("Comparing voter IDs (%s) with on-chain member IDs - primary (%s)", voter_ids, peer_ids));
if(Collections.indexOfSubList(peer_ids, voter_ids) == -1){
List<byte[]> newsub = new ArrayList<>(peer_ids); // clone
throw new InvalidMessage(String.format("Consensus seal contains vote(s) from invalid ID(s): %s",
newsub.removeAll(voter_ids)
));
}
if(voter_ids.size() < 2 * state.getFaultyNodes())
throw new InvalidMessage(String.format("Consensus seal needs {%d} votes, but only {%d} found", 2 * state.getFaultyNodes(), voter_ids.size()));
}
public void tryPublish() throws ServiceError {
if(!state.isPrimary() || state.getPhase() != State.Phase.PrePreparing)
return;
logger.trace(String.format("%s: Attempting to summarize block", state));
try {
service.summarizeBlock();
} catch (InvalidStateException | BlockNotReadyException | ReceiveErrorException e) {
logger.trace(String.format("Couldn't summarize, so not finalizing: %s", e));
return;
}
// We don't publish a consensus seal at block 1, since we never receive any
// votes on the genesis block. Leave payload blank for the first block.
byte[] data = new byte[]{};
if(state.getSeqNum() > 1) {
try {
data = buildSeal().toByteArray();
} catch (InternalError internalError) {
internalError.printStackTrace();
}
}
try {
byte[] block_id = service.finalizeBlock(data);
logger.info(String.format("{%s}: Publishing block {%s}", state, HexBin.encode(block_id)));
} catch (InvalidStateException | UnknownBlockException | ReceiveErrorException | BlockNotReadyException e) {
throw new ServiceError(String.format("Couldn't finalize block: %s", e));
}
}
public boolean checkIdleTimeoutExpired(){
return state.idle_timeout.checkExpired();
}
public void startIdleTimeout(){
state.idle_timeout.start();
}
public boolean checkCommitTimeoutExpired(){
return state.commit_timeout.checkExpired();
}
public void startCommitTimeout(){
state.commit_timeout.start();
}
public boolean checkViewChangeTimeoutExpired(){
return state.view_change_timeout.checkExpired();
}
public void broadcastPBFTMessage(long view, long seq_num, MessageType msg_type, byte[] blockId){
PbftMessage msg = PbftMessage.newBuilder()
.setBlockId(ByteString.copyFrom(blockId))
.setInfo(
MessageExtension.newMessageInfo(msg_type, view, seq_num, state.getPeerId())
)
.build();
logger.trace(String.format("%s: : Created PBFT message: %s", state, msg));
broadcastMessage(new ParsedMessage(msg));
}
public void broadcastMessage(ParsedMessage msg) {
service.broadcast(msg.info().getMsgType(),
msg.getMessageBytes());
try {
onPeerMessage(msg);
} catch (InvalidMessage invalidMessage) {
logger.error("broadcastMessage failed on onPeerMessage");
}
}
public void sendSealResponse(byte[] recipient) throws InternalError {
PbftSeal seal;
try {
seal = buildSeal();
} catch (InternalError e) {
throw new InternalError(String.format("Failed to build requested seal due to: %s", e));
}
byte[] msg_bytes = seal.toByteArray();
service.sendTo(
recipient,
"Seal",
msg_bytes
);
}
public void startViewChange(long view){
if(state.getMode() == State.Mode.ViewChanging
&& view <= state.getMode().getViewChanging()){
return;
}
state.setModeViewChanging(view);
state.idle_timeout.stop();
state.commit_timeout.stop();
state.view_change_timeout.stop();
broadcastPBFTMessage(
view,
state.getSeqNum() - 1,
ViewChange,
new byte[]{}
);
}
public State getState(){
return state;
}
*/
}
| 39.336993
| 197
| 0.584047
|
e157ea609ac82ce8f597208b38c2dfc4c2300c32
| 2,747
|
package mage.cards.n;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.EpicEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.players.Player;
import mage.target.TargetPlayer;
import mage.target.common.TargetCardInLibrary;
/**
*
* @author jeffwadsworth
*
*/
public final class NeverendingTorment extends CardImpl {
public NeverendingTorment(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{4}{B}{B}");
// Search target player's library for X cards, where X is the number of cards in your hand, and exile them. Then that player shuffles their library.
this.getSpellAbility().addEffect(new NeverendingTormentEffect());
this.getSpellAbility().addTarget(new TargetPlayer());
// Epic
this.getSpellAbility().addEffect(new EpicEffect());
}
public NeverendingTorment(final NeverendingTorment card) {
super(card);
}
@Override
public NeverendingTorment copy() {
return new NeverendingTorment(this);
}
}
class NeverendingTormentEffect extends OneShotEffect {
public NeverendingTormentEffect() {
super(Outcome.Benefit);
staticText = "Search target player's library for X cards, where X is the number of cards in your hand, and exile them. Then that player shuffles their library";
}
public NeverendingTormentEffect(final NeverendingTormentEffect effect) {
super(effect);
}
@Override
public boolean apply(Game game, Ability source) {
boolean applied = false;
Player targetPlayer = game.getPlayer(source.getFirstTarget());
Player you = game.getPlayer(source.getControllerId());
if (targetPlayer != null
&& you != null) {
TargetCardInLibrary target = new TargetCardInLibrary(you.getHand().size(), new FilterCard());
you.searchLibrary(target, source, game, targetPlayer.getId());
for (UUID cardId : target.getTargets()) {
final Card targetCard = game.getCard(cardId);
if (targetCard != null) {
applied |= you.moveCardToExileWithInfo(targetCard, null, null, source, game, Zone.LIBRARY, true);
}
}
targetPlayer.shuffleLibrary(source, game);
}
return applied;
}
@Override
public NeverendingTormentEffect copy() {
return new NeverendingTormentEffect(this);
}
}
| 32.317647
| 168
| 0.680015
|
fd3b3162836c15bc93fc4ab51a9252a3fef605ac
| 1,173
|
package br.odb;
import android.content.Context;
import android.content.res.Configuration;
import android.view.InputDevice;
import java.util.ArrayList;
import java.util.List;
/**
* Created by monty on 27/09/16.
*/
public class ControllerHelper {
private Context mContext;
public ControllerHelper(Context context) {
mContext = context;
}
public boolean hasGamepad() {
return getGameControllerIds().size() > 0;
}
public boolean hasPhysicalKeyboard() {
return mContext.getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
}
private List<Integer> getGameControllerIds() {
List<Integer> gameControllerDeviceIds = new ArrayList<>();
int[] deviceIds = InputDevice.getDeviceIds();
for (int deviceId : deviceIds) {
InputDevice dev = InputDevice.getDevice(deviceId);
int sources = dev.getSources();
if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((sources & InputDevice.SOURCE_JOYSTICK)
== InputDevice.SOURCE_JOYSTICK)) {
if (!gameControllerDeviceIds.contains(deviceId)) {
gameControllerDeviceIds.add(deviceId);
}
}
}
return gameControllerDeviceIds;
}
}
| 23
| 94
| 0.73231
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.