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 |
|---|---|---|---|---|---|
d81ccd92b63d9bbb4b2f7778e1064b25c487ecfa | 129 | package com.frewen.designpattern.chain.resposibility.architecture.abs;
public enum RequestLevel {
ONE,
TWO,
THREE
}
| 16.125 | 70 | 0.736434 |
786883f0a5719bcd0bf4bbb45d8226da58e39a5b | 1,224 | package webapp.tier.service;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import javax.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class HazelcastSubscribeServiceTest {
@Inject
HazelcastSubscribeService svc;
private static HazelcastInstance mockInstance;
private String respbody = "message: Hello k8s-3tier-webapp with quarkus";
@BeforeEach
public void setup() throws IOException {
mockInstance = Hazelcast.newHazelcastInstance();
}
@AfterEach
public void after() {
mockInstance.shutdown();
}
@Test
void testSubscribeHazelcast() {
svc.subscribeHazelcast(mockInstance, svc.createHazelcastDeliverSubscriber());
assertThat(svc.publishMsg(mockInstance).getFullmsg(), containsString(respbody));
}
@Test
void testSubscribeNoData() {
try {
svc.run();
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| 22.254545 | 82 | 0.776961 |
35750edc4b416620df011350d4c9473082cda561 | 2,554 | /*
*
* Copyright 2016 jshook
* 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.nosqlbench.engine.core.script;
import io.nosqlbench.cli.testing.ProcessInvoker;
import io.nosqlbench.cli.testing.ProcessResult;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
public class NBCliIntegrationTests {
private final static String JARNAME = "target/nb.jar";
private Logger logger = LoggerFactory.getLogger(NBCliIntegrationTests.class);
@Test
public void listWorkloadsTest() {
ProcessInvoker invoker = new ProcessInvoker();
invoker.setLogDir("logs/test");
ProcessResult result = invoker.run("workload-test", 15,
"java", "-jar", JARNAME, "--logs-dir", "logs/test", "--list-workloads"
);
System.out.println(result.getStdoutData());
System.out.println(result.getStderrData());
assertThat(result.exitStatus).isEqualTo(0);
}
// disabled till after release
// This is not disabled on testbranch, only on master
// @Test
// public void dockerMetrics() {
// ProcessInvoker invoker = new ProcessInvoker();
// invoker.setLogDir("logs/test");
//
// // check for docker
// ProcessResult result = invoker.run("docker-detection-test", 15,
// "docker", "ps"
// );
//
// System.out.println(result.getStdoutData());
// System.out.println(result.getStderrData());
//
// if(result.exitStatus ==0) {
// result = invoker.run("docker-metrics-test", 15,
// "java", "-jar", JARNAME, "--logs-dir", "logs/test", "--docker-metrics"
// );
// System.out.println(result.getStdoutData());
// System.out.println(result.getStderrData());
// assertThat(result.exitStatus).isEqualTo(0);
// return;
// }
//
// logger.warn("skipped docker-metrics test because docker is not available");
// }
}
| 35.472222 | 87 | 0.648786 |
cd1762eef61be0ffda6d5ca5f49740eef986d339 | 3,835 | /*
* Copyright 2018-2021 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.datastore.request;
import com.b2international.snowowl.core.domain.TransactionContext;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry;
import com.google.common.base.Strings;
/**
* @since 6.5
*/
final class SnomedMRCMDomainMemberUpdateDelegate extends SnomedRefSetMemberUpdateDelegate {
SnomedMRCMDomainMemberUpdateDelegate(final SnomedRefSetMemberUpdateRequest request) {
super(request);
}
@Override
boolean execute(final SnomedRefSetMemberIndexEntry original, final SnomedRefSetMemberIndexEntry.Builder member, final TransactionContext context) {
final String domainConstraint = getProperty(SnomedRf2Headers.FIELD_MRCM_DOMAIN_CONSTRAINT);
final String parentDomain = getProperty(SnomedRf2Headers.FIELD_MRCM_PARENT_DOMAIN);
final String proximalPrimitiveConstraint = getProperty(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_CONSTRAINT);
final String proximalPrimitiveRefinement = getProperty(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_REFINEMENT);
final String domainTemplateForPrecoordination = getProperty(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_PRECOORDINATION);
final String domainTemplateForPostcoordination = getProperty(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_POSTCOORDINATION);
final String guideURL = getProperty(SnomedRf2Headers.FIELD_MRCM_GUIDEURL);
boolean changed = false;
if (!Strings.isNullOrEmpty(domainConstraint) && !domainConstraint.equals(original.getDomainConstraint())) {
member.field(SnomedRf2Headers.FIELD_MRCM_DOMAIN_CONSTRAINT, domainConstraint);
changed |= true;
}
if (parentDomain != null && !parentDomain.equals(original.getParentDomain())) {
member.field(SnomedRf2Headers.FIELD_MRCM_PARENT_DOMAIN, parentDomain);
changed |= true;
}
if (!Strings.isNullOrEmpty(proximalPrimitiveConstraint) && !proximalPrimitiveConstraint.equals(original.getProximalPrimitiveConstraint())) {
member.field(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_CONSTRAINT, proximalPrimitiveConstraint);
changed |= true;
}
if (proximalPrimitiveRefinement != null && !proximalPrimitiveRefinement.equals(original.getProximalPrimitiveRefinement())) {
member.field(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_REFINEMENT, proximalPrimitiveRefinement);
changed |= true;
}
if (!Strings.isNullOrEmpty(domainTemplateForPrecoordination) && !domainTemplateForPrecoordination.equals(original.getDomainTemplateForPrecoordination())) {
member.field(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_PRECOORDINATION, domainTemplateForPrecoordination);
changed |= true;
}
if (!Strings.isNullOrEmpty(domainTemplateForPostcoordination) && !domainTemplateForPostcoordination.equals(original.getDomainTemplateForPostcoordination())) {
member.field(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_POSTCOORDINATION, domainTemplateForPostcoordination);
changed |= true;
}
if (guideURL != null && !guideURL.equals(original.getGuideURL())) {
member.field(SnomedRf2Headers.FIELD_MRCM_GUIDEURL, guideURL);
changed |= true;
}
return changed;
}
}
| 46.204819 | 160 | 0.814342 |
e26d7767fc2e7b7b7c89a0da4545ee42f3bd923e | 159 | package org.processmining.framework.providedobjects;
import org.processmining.framework.ProMID;
public interface ProvidedObjectID extends ProMID {
}
| 19.875 | 53 | 0.805031 |
314dca5b77e56e1a2b516b675cc51aef377cf763 | 76 | package com.baeldung.componentscan.filter.regex;
public class Elephant { }
| 19 | 48 | 0.802632 |
eeac345828ab68faf355188bbb65d0a9fbb3c0ab | 13,132 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.iothub.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.iothub.fluent.models.PrivateEndpointConnectionInner;
import java.util.List;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in PrivateEndpointConnectionsClient. */
public interface PrivateEndpointConnectionsClient {
/**
* List private endpoint connection properties.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of private endpoint connections for an IotHub.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
List<PrivateEndpointConnectionInner> list(String resourceGroupName, String resourceName);
/**
* List private endpoint connection properties.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of private endpoint connections for an IotHub along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<List<PrivateEndpointConnectionInner>> listWithResponse(
String resourceGroupName, String resourceName, Context context);
/**
* Get private endpoint connection properties.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return private endpoint connection properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner get(
String resourceGroupName, String resourceName, String privateEndpointConnectionName);
/**
* Get private endpoint connection properties.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return private endpoint connection properties along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<PrivateEndpointConnectionInner> getWithResponse(
String resourceGroupName, String resourceName, String privateEndpointConnectionName, Context context);
/**
* Update the status of a private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param privateEndpointConnection The private endpoint connection with updated properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginUpdate(
String resourceGroupName,
String resourceName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner privateEndpointConnection);
/**
* Update the status of a private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param privateEndpointConnection The private endpoint connection with updated properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginUpdate(
String resourceGroupName,
String resourceName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner privateEndpointConnection,
Context context);
/**
* Update the status of a private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param privateEndpointConnection The private endpoint connection with updated properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner update(
String resourceGroupName,
String resourceName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner privateEndpointConnection);
/**
* Update the status of a private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param privateEndpointConnection The private endpoint connection with updated properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner update(
String resourceGroupName,
String resourceName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner privateEndpointConnection,
Context context);
/**
* Delete private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginDelete(
String resourceGroupName, String resourceName, String privateEndpointConnectionName);
/**
* Delete private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginDelete(
String resourceGroupName, String resourceName, String privateEndpointConnectionName, Context context);
/**
* Delete private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner delete(
String resourceGroupName, String resourceName, String privateEndpointConnectionName);
/**
* Delete private endpoint connection with the specified name.
*
* @param resourceGroupName The name of the resource group that contains the IoT hub.
* @param resourceName The name of the IoT hub.
* @param privateEndpointConnectionName The name of the private endpoint connection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the private endpoint connection of an IotHub.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner delete(
String resourceGroupName, String resourceName, String privateEndpointConnectionName, Context context);
}
| 55.644068 | 115 | 0.750305 |
48cdde33bd99a935cb006f191ed7a69adc884e56 | 431 | package mapper;
import org.apache.ibatis.annotations.Param;
import po.Purchase;
import java.util.Date;
import java.util.List;
public interface PurchaseMapper {
int reduceInventory(@Param("purchaseID")int purchaseID, @Param("purchaseTime")Date purchaseTime);
Purchase queryByProductID(@Param("productID")int productID);
Purchase queryByPurchaseID(@Param("purchaseID")int purchaseID);
List<Purchase> queryAll();
}
| 28.733333 | 101 | 0.772622 |
fb5938e0f4af9c2a34d7ba478a22a4b2325290a3 | 302 | package nl.th7mo.youtube;
import nl.th7mo.spotify.playlist.SpotifyPlaylist;
public class YoutubeController {
public void postPlaylist(SpotifyPlaylist spotifyPlaylist) {
YoutubePlaylistDAO playlistDAO = new YoutubePlaylistDAO(spotifyPlaylist);
playlistDAO.postPlaylist();
}
}
| 25.166667 | 81 | 0.768212 |
4d3dcd46075418bef7078b46240a3a2bc5f328db | 7,566 | package org.hisp.dhis.analytics.table;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.analytics.AnalyticsTableGenerator;
import org.hisp.dhis.analytics.AnalyticsTableService;
import org.hisp.dhis.analytics.AnalyticsTableType;
import org.hisp.dhis.analytics.AnalyticsTableUpdateParams;
import org.hisp.dhis.commons.collection.CollectionUtils;
import org.hisp.dhis.message.MessageService;
import org.hisp.dhis.resourcetable.ResourceTableService;
import org.hisp.dhis.scheduling.JobConfiguration;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.system.notification.Notifier;
import org.hisp.dhis.system.util.Clock;
import org.hisp.dhis.system.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hisp.dhis.system.notification.NotificationLevel.ERROR;
import static org.hisp.dhis.system.notification.NotificationLevel.INFO;
/**
* @author Lars Helge Overland
*/
public class DefaultAnalyticsTableGenerator
implements AnalyticsTableGenerator
{
private static final Log log = LogFactory.getLog( DefaultAnalyticsTableGenerator.class );
@Autowired
private List<AnalyticsTableService> analyticsTableServices;
@Autowired
private ResourceTableService resourceTableService;
@Autowired
private MessageService messageService;
@Autowired
private SystemSettingManager systemSettingManager;
@Autowired
private Notifier notifier;
// -------------------------------------------------------------------------
// Implementation
// -------------------------------------------------------------------------
@Override
public void generateTables( AnalyticsTableUpdateParams params )
{
final Date startTime = new Date();
final Clock clock = new Clock( log ).startClock();
final JobConfiguration jobId = params.getJobId();
final Set<AnalyticsTableType> skipTypes = CollectionUtils.emptyIfNull( params.getSkipTableTypes() );
final Set<AnalyticsTableType> availableTypes = analyticsTableServices.stream()
.map( AnalyticsTableService::getAnalyticsTableType )
.collect( Collectors.toSet() );
log.info( String.format( "Found %d analytics table types: %s", availableTypes.size(), availableTypes ) );
log.info( String.format( "Analytics table update: %s", params ) );
try
{
notifier.clear( jobId ).notify( jobId, "Analytics table update process started" );
if ( !params.isSkipResourceTables() )
{
notifier.notify( jobId, "Updating resource tables" );
generateResourceTables();
}
for ( AnalyticsTableService service : analyticsTableServices )
{
AnalyticsTableType tableType = service.getAnalyticsTableType();
if ( !skipTypes.contains( tableType ) )
{
notifier.notify( jobId, "Updating tables: " + tableType );
service.update( params );
}
}
clock.logTime( "Analytics tables updated" );
notifier.notify( jobId, INFO, "Analytics tables updated: " + clock.time(), true );
}
catch ( RuntimeException ex )
{
notifier.notify( jobId, ERROR, "Process failed: " + ex.getMessage(), true );
messageService.sendSystemErrorNotification( "Analytics table process failed", ex );
throw ex;
}
systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_ANALYTICS_TABLES_UPDATE, startTime );
systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_ANALYTICS_TABLES_RUNTIME, DateUtils.getPrettyInterval( clock.getSplitTime() ) );
}
@Override
public void dropTables()
{
for ( AnalyticsTableService service : analyticsTableServices )
{
service.dropTables();
}
}
@Override
public void generateResourceTables( JobConfiguration jobId )
{
final Clock clock = new Clock().startClock();
notifier.notify( jobId, "Generating resource tables" );
try
{
generateResourceTables();
notifier.notify( jobId, INFO, "Resource tables generated: " + clock.time(), true );
}
catch ( RuntimeException ex )
{
notifier.notify( jobId, ERROR, "Process failed: " + ex.getMessage(), true );
messageService.sendSystemErrorNotification( "Resource table process failed", ex );
throw ex;
}
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private void generateResourceTables()
{
final Date startTime = new Date();
resourceTableService.dropAllSqlViews();
resourceTableService.generateOrganisationUnitStructures();
resourceTableService.generateDataSetOrganisationUnitCategoryTable();
resourceTableService.generateCategoryOptionComboNames();
resourceTableService.generateDataElementGroupSetTable();
resourceTableService.generateIndicatorGroupSetTable();
resourceTableService.generateOrganisationUnitGroupSetTable();
resourceTableService.generateCategoryTable();
resourceTableService.generateDataElementTable();
resourceTableService.generatePeriodTable();
resourceTableService.generateDatePeriodTable();
resourceTableService.generateCategoryOptionComboTable();
resourceTableService.createAllSqlViews();
systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_RESOURCE_TABLES_UPDATE, startTime );
}
}
| 39.202073 | 155 | 0.683056 |
4e213500834ed8a751216120a59e82c772d3d391 | 7,087 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.be.components.lifecycle;
import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.common.api.UserRoleEnum;
import org.openecomp.sdc.exception.ResponseFormat;
import static org.junit.Assert.assertTrue;
public class CertificationChangeTransitionValidationTest extends LifecycleTestBase {
private CertificationChangeTransition certifyTransitionObj = null;
@Mock
private ServiceBusinessLogic serviceBusinessLogic;
private User owner = null;
Resource resource;
Service service;
@SuppressWarnings("unchecked")
@Before
public void setup() {
super.setup();
// checkout transition object
certifyTransitionObj = new CertificationChangeTransition(serviceBusinessLogic, LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, janusGraphDao);
certifyTransitionObj.setConfigurationManager(configurationManager);
certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation);
owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null);
user.setRole(UserRoleEnum.DESIGNER.getName());
resource = createResourceObject();
service = createServiceObject();
}
@Test
public void testVFCMTStateValidation(){
Resource resource = createResourceVFCMTObject();
Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(validateBeforeTransition.isLeft());
}
@Test
public void testStateCheckInValidationSuccess() {
Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(changeStateResult.isLeft());
changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(changeStateResult.isLeft());
}
@Test
public void testStateCheckOutValidationSuccess() {
Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
assertTrue(changeStateResult.isLeft());
changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
assertTrue(changeStateResult.isLeft());
}
@Test
public void testStateCertifyValidationFail() {
Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.CERTIFIED);
assertValidationStateErrorResponse(validateBeforeTransition);
certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
assertValidationStateErrorResponse(validateBeforeTransition);
}
@Test
public void testRolesSuccess() {
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertSuccessWithResourceAndService();
user.setRole(UserRoleEnum.ADMIN.getName());
assertSuccessWithResourceAndService();
}
@Test
public void testRolesFail() {
user.setRole(UserRoleEnum.TESTER.getName());
assertBeforeTransitionRoleFalis();
assertBeforeTransitionRoleFalis();
assertBeforeTransitionRoleFalis();
user.setRole(UserRoleEnum.PRODUCT_MANAGER.getName());
assertBeforeTransitionRoleFalis();
user.setRole(UserRoleEnum.PRODUCT_STRATEGIST.getName());
assertBeforeTransitionRoleFalis();
}
private void assertSuccessWithResourceAndService() {
Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(validateBeforeTransition.isLeft());
certifyTransitionObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(validateBeforeTransition.isLeft());
}
private void assertBeforeTransitionRoleFalis() {
Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertResponse(Either.right(validateBeforeTransition.right().value()), ActionStatus.RESTRICTED_OPERATION);
certifyTransitionObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertResponse(Either.right(validateBeforeTransition.right().value()), ActionStatus.RESTRICTED_OPERATION);
}
private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) {
assertTrue(validateBeforeTransition.isRight());
ResponseFormat error = validateBeforeTransition.right().value();
Either<Resource, ResponseFormat> changeStateResult = Either.right(error);
assertTrue(changeStateResult.isRight());
assertResponse(changeStateResult, ActionStatus.ILLEGAL_COMPONENT_STATE);
}
}
| 47.563758 | 206 | 0.741075 |
0758718d46653dc99258c78fb602cfab772d07ec | 10,331 | /**
*/
package model;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Team</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link model.Team#getName <em>Name</em>}</li>
* <li>{@link model.Team#getCaptain <em>Captain</em>}</li>
* <li>{@link model.Team#getStartingLine <em>Starting Line</em>}</li>
* <li>{@link model.Team#getSubstitutes <em>Substitutes</em>}</li>
* <li>{@link model.Team#getStaff <em>Staff</em>}</li>
* <li>{@link model.Team#getGoals <em>Goals</em>}</li>
* <li>{@link model.Team#getPenalties <em>Penalties</em>}</li>
* <li>{@link model.Team#getCards <em>Cards</em>}</li>
* <li>{@link model.Team#getRedBans <em>Red Bans</em>}</li>
* <li>{@link model.Team#getGoalCount <em>Goal Count</em>}</li>
* <li>{@link model.Team#getMembers <em>Members</em>}</li>
* <li>{@link model.Team#getMatch <em>Match</em>}</li>
* <li>{@link model.Team#getGoalCountHT <em>Goal Count HT</em>}</li>
* </ul>
* </p>
*
* @see model.ModelPackage#getTeam()
* @model
* @generated
*/
public interface Team extends EObject {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see model.ModelPackage#getTeam_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link model.Team#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Captain</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Captain</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Captain</em>' reference.
* @see #setCaptain(Player)
* @see model.ModelPackage#getTeam_Captain()
* @model required="true"
* @generated
*/
Player getCaptain();
/**
* Sets the value of the '{@link model.Team#getCaptain <em>Captain</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Captain</em>' reference.
* @see #getCaptain()
* @generated
*/
void setCaptain(Player value);
/**
* Returns the value of the '<em><b>Starting Line</b></em>' reference list.
* The list contents are of type {@link model.Player}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Starting Line</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Starting Line</em>' reference list.
* @see model.ModelPackage#getTeam_StartingLine()
* @model lower="5" upper="5"
* @generated
*/
EList<Player> getStartingLine();
/**
* Returns the value of the '<em><b>Substitutes</b></em>' reference list.
* The list contents are of type {@link model.Player}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Substitutes</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Substitutes</em>' reference list.
* @see model.ModelPackage#getTeam_Substitutes()
* @model lower="3" upper="7" transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.substitutes'"
* @generated
*/
EList<Player> getSubstitutes();
/**
* Returns the value of the '<em><b>Staff</b></em>' reference list.
* The list contents are of type {@link model.StaffMember}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Staff</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Staff</em>' reference list.
* @see model.ModelPackage#getTeam_Staff()
* @model upper="8" transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.staff'"
* @generated
*/
EList<StaffMember> getStaff();
/**
* Returns the value of the '<em><b>Goals</b></em>' reference list.
* The list contents are of type {@link model.Event}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Goals</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Goals</em>' reference list.
* @see model.ModelPackage#getTeam_Goals()
* @model transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.viatra2.emf.incquery.derived.feature patternFQN='derived.goals'"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.goals'"
* @generated
*/
EList<Event> getGoals();
/**
* Returns the value of the '<em><b>Penalties</b></em>' containment reference list.
* The list contents are of type {@link model.Penalty}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Penalties</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Penalties</em>' containment reference list.
* @see model.ModelPackage#getTeam_Penalties()
* @model containment="true"
* @generated
*/
EList<Penalty> getPenalties();
/**
* Returns the value of the '<em><b>Cards</b></em>' reference list.
* The list contents are of type {@link model.Event}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Cards</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Cards</em>' reference list.
* @see model.ModelPackage#getTeam_Cards()
* @model transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.viatra2.emf.incquery.derived.feature patternFQN='derived.cards'"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.cards'"
* @generated
*/
EList<Event> getCards();
/**
* Returns the value of the '<em><b>Red Bans</b></em>' reference list.
* The list contents are of type {@link model.Event}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Red Bans</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Red Bans</em>' reference list.
* @see model.ModelPackage#getTeam_RedBans()
* @model transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.viatra2.emf.incquery.derived.feature patternFQN='derived.redBans'"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.redBans'"
* @generated
*/
EList<Event> getRedBans();
/**
* Returns the value of the '<em><b>Goal Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Goal Count</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Goal Count</em>' attribute.
* @see model.ModelPackage#getTeam_GoalCount()
* @model transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.viatra2.emf.incquery.derived.feature patternFQN='derived.goalCount'"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.goalCount'"
* @generated
*/
int getGoalCount();
/**
* Returns the value of the '<em><b>Members</b></em>' containment reference list.
* The list contents are of type {@link model.TeamMember}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Members</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Members</em>' containment reference list.
* @see model.ModelPackage#getTeam_Members()
* @model containment="true" lower="8" upper="22"
* @generated
*/
EList<TeamMember> getMembers();
/**
* Returns the value of the '<em><b>Match</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Match</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Match</em>' reference.
* @see model.ModelPackage#getTeam_Match()
* @model required="true" transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.viatra2.emf.incquery.derived.feature patternFQN='derived.match'"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.match'"
* @generated
*/
Match getMatch();
/**
* Returns the value of the '<em><b>Goal Count HT</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Goal Count HT</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Goal Count HT</em>' attribute.
* @see model.ModelPackage#getTeam_GoalCountHT()
* @model transient="true" changeable="false" volatile="true" derived="true"
* annotation="org.eclipse.incquery.querybasedfeature patternFQN='derived.goalCountHT'"
* @generated
*/
int getGoalCountHT();
} // Team
| 37.296029 | 104 | 0.625206 |
f72ec505b45ef974ee470a6110ae5c7c03f9adae | 1,648 | package tech.pcloud.proxy.client.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tech.pcloud.proxy.client.listeners.ServiceRegisterListener;
import tech.pcloud.proxy.client.mapper.ServicesMapper;
import tech.pcloud.proxy.core.model.Node;
import tech.pcloud.proxy.core.service.IdGenerateService;
import java.util.List;
@Slf4j
@Service
public class ServicesService {
@Autowired
@Qualifier("client")
private Node client;
@Autowired
private ServicesMapper servicesMapper;
@Autowired
private IdGenerateService idGenerateService;
@Autowired
private MessageService messageService;
@Autowired
private ConnectionFactory connectionFactory;
public List<tech.pcloud.proxy.core.model.Service> selectAll() {
return servicesMapper.selectAll();
}
public tech.pcloud.proxy.core.model.Service register(tech.pcloud.proxy.core.model.Service service, Node server) {
tech.pcloud.proxy.core.model.Service loadService = servicesMapper.loadByName(service.getName());
if (loadService == null) {
service.setId(idGenerateService.generate(IdGenerateService.IdType.SERVICE));
servicesMapper.insert(service);
} else {
servicesMapper.update(service);
}
connectionFactory.connect(ConnectionFactory.ConnectType.PROXY, server.getIp(), server.getPort(),
new ServiceRegisterListener(client, server, messageService));
return service;
}
}
| 35.826087 | 117 | 0.745146 |
89278127e379de3ca60f74d46b6f9872501051a4 | 825 | package com.example.model;
public abstract class TemplateDto {
public transient int Id;
public transient String Name;
public TemplateDto() {
}
public TemplateDto(String name) {
this.Name = name;
}
public abstract boolean isDefault();
@Override
public String toString() {
return Name;
}
public enum TemplateType {
EditCard(1),
WorkTime(2),
TaskResolutionNotFound(3),
ReadonlyCard(4),
EditHouse(5),
EditHouseEntrance(6),
EditOtherPoint(7),
EditOtherLine(8),
EditOtherPolygon(9);
private final int id;
TemplateType(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
} | 19.642857 | 41 | 0.527273 |
65d3c90d433bd9b35d8f5da8b258d3f1ffc066df | 1,745 | package com.mauriciotogneri.joini.app.model;
import com.mauriciotogneri.joini.app.app.Options;
import java.util.ArrayList;
import java.util.List;
public class Group
{
private final String name;
private final List<Item> items = new ArrayList<>();
public Group(String name)
{
this.name = name;
}
public String name()
{
return name;
}
public Boolean name(String name)
{
return this.name.equals(name);
}
public void add(Item item)
{
items.add(item);
}
public void join(Group group, Options options)
{
for (Item item : group.items)
{
Item localItem = item(item.name());
if (localItem != null)
{
localItem.join(this, item, options);
}
else if (options.createItems)
{
Item newItem = new Item(item.name());
newItem.join(this, item, options);
add(item);
}
else
{
throw new RuntimeException(String.format("Item not found in target: %s.%s", name, item));
}
}
}
private Item item(String name)
{
for (Item item : items)
{
if (item.name(name))
{
return item;
}
}
return null;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(String.format("[[%s]]%n%n", name));
for (Item item : items)
{
builder.append(item.toString());
}
builder.append(String.format("%n"));
return builder.toString();
}
} | 20.529412 | 105 | 0.503152 |
396134b358544b4c15b73d00ce9c9a656b945a52 | 568 | package org.svenson.matcher;
/**
* Matches the parse path if it's equals to a special string.
*
* @author fforw at gmx dot de
*
*/
public class EqualsPathMatcher
implements PathMatcher
{
private String parsePath;
public EqualsPathMatcher(String parsePath)
{
this.parsePath = parsePath;
}
public boolean matches(String parsePath, Class typeHint)
{
return this.parsePath.equals(parsePath);
}
@Override
public String toString()
{
return "path equals '" + parsePath + "'";
}
}
| 18.933333 | 62 | 0.628521 |
0150dd69fbb3e1fbc27b6482e2980ce4265c4b1b | 4,520 | package au.gov.digitalhealth.medserve.transform.rxnorm.model;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Coding;
import au.gov.digitalhealth.medserve.extension.MedicationType;
import au.gov.digitalhealth.medserve.transform.rxnorm.enumeration.RxNormReltaionshipType;
import au.gov.digitalhealth.medserve.transform.rxnorm.enumeration.RxNormType;
import au.gov.digitalhealth.medserve.transform.util.FhirCodeSystemUri;
public class Concept {
private static final Logger logger = Logger.getLogger(Concept.class.getCanonicalName());
private long rxcui;
private String name;
private RxNormType type;
private Map<RxNormReltaionshipType, Set<Concept>> relationships = new HashMap<>();
private Set<Coding> alternativeIds = new HashSet<>();
CodeableConcept codeableConcept = new CodeableConcept();
private Set<String> supportedSab = new HashSet<>(Arrays.asList("RXNORM", "ATC", "NDFRT", "NDC", "MTHSPL"));
public Concept(long rxcui) {
this.rxcui = rxcui;
}
public void addCode(String sab, RxNormType type, String code, String value) {
if (sab.equals("RXNORM") && type.isBaseType()) {
setBaseIdentity(type, value);
} else if (sab.equals("RXNORM") && type.equals(RxNormType.PrescribableName)) {
setBaseIdentity(type, value);
} else if (supportedSab.contains(sab)) {
codeableConcept.addCoding(new Coding(getSystem(sab, type), code, value));
} else {
// logger.info("Skipping " + sab + " " + type + " " + code + " " + value);
}
}
private String getSystem(String sab, RxNormType rxType) {
switch (sab) {
case "RXNORM":
return FhirCodeSystemUri.RXNORM_URI.getUri();
case "ATC":
return FhirCodeSystemUri.ATC_URI.getUri();
case "NDFRT":
return FhirCodeSystemUri.NDFRT_URI.getUri();
case "NDC":
return FhirCodeSystemUri.NDC_URI.getUri();
case "MTHSPL":
return FhirCodeSystemUri.UNII_URI.getUri();
default:
throw new RuntimeException("Cannot get URI for SAB " + sab + " type " + rxType);
}
}
private void setBaseIdentity(RxNormType rxType, String value) {
if (name != null || type != null) {
throw new RuntimeException(
"Trying to set type " + rxType + " and value " + value + " to concept " + this.toString());
}
this.type = rxType;
this.name = value;
codeableConcept.setText(name);
codeableConcept.addCoding(new Coding(FhirCodeSystemUri.RXNORM_URI.getUri(), Long.toString(rxcui), name));
}
public void addRelationship(RxNormReltaionshipType rela, Concept concept) {
Set<Concept> targets = relationships.get(rela);
if (targets == null) {
targets = new HashSet<>();
relationships.put(rela, targets);
}
targets.add(concept);
}
public long getRxcui() {
return rxcui;
}
public String getName() {
return name;
}
public RxNormType getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (rxcui ^ (rxcui >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Concept other = (Concept) obj;
if (rxcui != other.rxcui)
return false;
return true;
}
public CodeableConcept toCodeableConcept() {
return codeableConcept;
}
public boolean isBaseType() {
return type.isBaseType();
}
public MedicationType getMedicationType() {
return type.getMedicationType();
}
public boolean isActive() {
// TODO deal with history
return true;
}
public Set<Concept> getTargets(RxNormReltaionshipType relType, RxNormType type) {
return relationships.get(relType).stream().filter(c -> c.getType().equals(type)).collect(Collectors.toSet());
}
}
| 31.172414 | 117 | 0.620575 |
7f8876d017cd3658c99d17ecad2954b3b9c7e56a | 853 | package mage.cards.b;
import mage.abilities.effects.common.BalanceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import java.util.UUID;
/**
* @author emerald000
*/
public final class Balance extends CardImpl {
public Balance(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{W}");
// Each player chooses a number of lands they control equal to the number of lands controlled by the player who controls the fewest, then sacrifices the rest. Players discard cards and sacrifice creatures the same way.
this.getSpellAbility().addEffect(new BalanceEffect());
}
private Balance(final Balance card) {
super(card);
}
@Override
public Balance copy() {
return new Balance(this);
}
}
| 27.516129 | 226 | 0.708089 |
5a1668febdf734555357c893f863b59906647cf6 | 3,573 | package com.psychic_engine.cmput301w17t10.feelsappman;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.psychic_engine.cmput301w17t10.feelsappman.Controllers.CreateMoodController;
import com.psychic_engine.cmput301w17t10.feelsappman.Enums.MoodState;
import com.psychic_engine.cmput301w17t10.feelsappman.Enums.SocialSetting;
import com.psychic_engine.cmput301w17t10.feelsappman.Exceptions.EmptyMoodException;
import com.psychic_engine.cmput301w17t10.feelsappman.Exceptions.TriggerTooLongException;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.Mood;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.MoodEvent;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.Participant;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.ParticipantSingleton;
import junit.framework.TestCase;
import org.junit.Before;
/**
* Created by adong on 3/13/17.
* Commented by adong
*/
/**
* Tests whether or not the CreateMoodController is able to editMoodEvent the participant's mood list
* upon creation of the mood they wish to createMoodEvent in the CreateMoodActivity.
* @see CreateMoodController
*/
public class CreateMoodControllerTest extends TestCase {
private ParticipantSingleton instance = ParticipantSingleton.getInstance();
private MoodEvent moodEvent;
private Context ctx;
@Before
public void setUp() throws EmptyMoodException, TriggerTooLongException {
//http://stackoverflow.com/questions/8605611/get-context-of-test-project-in-android-junit-test-case
//obtained April 1, 2017
//by fada21
ctx = InstrumentationRegistry.getContext();
Participant testParticipant = new Participant("TestCreateMood");
instance.addParticipant(testParticipant);
instance.setSelfParticipant(testParticipant);
Mood mood = new Mood(MoodState.HAPPY);
moodEvent = new MoodEvent(mood, SocialSetting.ALONE, "301", null, null);
}
/**
* Initialize parameters and classes for the test case. selfParticipant is required to
* set the self participant of the instance, and the add a dummy mood event to test the
* method.
*/
public void test1_createMoodEvent () {
String moodString = "Happy";
String socialSettingString = "Alone";
String trigger = "301";
try {
if (instance.getSelfParticipant().getMoodList() != null) {
instance.getSelfParticipant().getMoodList().clear();
}
}
catch (NullPointerException n) {
try {
CreateMoodController.createMoodEvent(moodString, socialSettingString, trigger, null, null, ctx);
assertEquals("empty, editMoodEvent fail", instance.getSelfParticipant().getMoodList()
.get(0).getMood().getMood(),
moodEvent.getMood().getMood());
} catch (Exception f) {
assertTrue("Failed create", false);
}
}
// test if the editMoodEvent was unsuccessful
try {
CreateMoodController.createMoodEvent(moodString, socialSettingString, trigger, null, null, ctx);
assertEquals("empty, editMoodEvent fail", instance.getSelfParticipant().getMoodList()
.get(0).getMood().getMood(),
moodEvent.getMood().getMood());
} catch (Exception e) {
assertTrue("Failed create", false);
}
}
}
| 42.035294 | 116 | 0.689337 |
7635575ffb2f339a74012cedc61f6730c020c304 | 3,788 | package dev.morphia.mapping;
import dev.morphia.annotations.Reference;
import dev.morphia.mapping.lazy.LazyFeatureDependencies;
import dev.morphia.mapping.lazy.ProxyTestBase;
import dev.morphia.testutil.TestEntity;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static dev.morphia.query.experimental.filters.Filters.eq;
import static java.util.Arrays.asList;
@Category(Reference.class)
public class MapWithNonStringKeyAndReferenceValueTest extends ProxyTestBase {
@Test
public void testMapKeyShouldBeInteger() {
getMapper().map(ChildEntity.class, ParentEntity.class);
final ChildEntity ce1 = new ChildEntity();
ce1.value = "first";
final ChildEntity ce2 = new ChildEntity();
ce2.value = "second";
final ParentEntity pe = new ParentEntity();
pe.childMap.put(1, ce1);
pe.childMap.put(2, ce2);
getDs().save(asList(ce1, ce2, pe));
final ParentEntity fetched = getDs().find(ParentEntity.class).filter(eq("_id", pe.getId())).first();
Assert.assertNotNull(fetched);
Assert.assertNotNull(fetched.childMap);
Assert.assertEquals(2, fetched.childMap.size());
//it is really String without fixing the reference mapper
//so ignore IDE's complains if any
Set<Integer> set = fetched.childMap.keySet();
Assert.assertTrue(set.iterator().next() != null);
}
@Test
public void testWithProxy() {
Assume.assumeTrue(LazyFeatureDependencies.assertProxyClassesPresent());
getMapper().map(ChildEntity.class, ParentEntity.class);
final ChildEntity ce1 = new ChildEntity();
ce1.value = "first";
final ChildEntity ce2 = new ChildEntity();
ce2.value = "second";
final ParentEntity pe = new ParentEntity();
pe.lazyChildMap.put(1, ce1);
pe.lazyChildMap.put(2, ce2);
getDs().save(asList(ce1, ce2, pe));
final ParentEntity fetched = getDs().find(ParentEntity.class)
.filter(eq("_id", pe.getId()))
.first();
Assert.assertNotNull(fetched);
assertIsProxy(fetched.lazyChildMap);
assertNotFetched(fetched.lazyChildMap);
Assert.assertEquals(2, fetched.lazyChildMap.size());
assertNotFetched(fetched.lazyChildMap);
Assert.assertTrue(fetched.lazyChildMap.keySet().iterator().next() != null);
}
private static class ParentEntity extends TestEntity {
@Reference
private Map<Integer, ChildEntity> childMap = new HashMap<>();
@Reference(lazy = true)
private Map<Integer, ChildEntity> lazyChildMap = new HashMap<>();
}
private static class ChildEntity extends TestEntity {
private String value;
@Override
public int hashCode() {
int result = getId() != null ? getId().hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ChildEntity that = (ChildEntity) o;
if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null) {
return false;
}
if (value != null ? !value.equals(that.value) : that.value != null) {
return false;
}
return true;
}
}
}
| 32.93913 | 108 | 0.610348 |
c8ea93bd001a68242608a09144c8efbdc566cc45 | 2,045 | package com.netsparker.teamcity;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.StringUtil;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
public class ScanPropertiesProcessor implements PropertiesProcessor{
@Override
public Collection<InvalidProperty> process(Map<String, String> properties) {
Collection<InvalidProperty> result = new HashSet<>();
ScanType scanType = null;
//Scan Type
try {
scanType = ScanType.valueOf(properties.get(ScanRequest.SCAN_TYPE_Literal));
} catch (Exception ex) {
result.add(new InvalidProperty(
ScanRequest.SCAN_TYPE_Literal,
"The parameter 'Scan Type' must be specified."));
}
//WebsiteId
boolean isWebsiteIdEmpty = StringUtil.isEmptyOrSpaces(properties.get(ScanRequest.WEBSITE_ID_Literal));
if (isWebsiteIdEmpty) {
result.add(new InvalidProperty(
ScanRequest.WEBSITE_ID_Literal,
"The parameter 'Website URL' must be specified."));
}
boolean isWebsiteIdValid = AppCommon.IsGUIDValid(properties.get(ScanRequest.WEBSITE_ID_Literal));
if (!isWebsiteIdEmpty && !isWebsiteIdValid) {
result.add(new InvalidProperty(
ScanRequest.WEBSITE_ID_Literal,
"The parameter 'Website URL' is invalid"));
}
//ProfileId
boolean isProfileIdEmpty = StringUtil.isEmptyOrSpaces(properties.get(ScanRequest.PROFILE_ID_Literal));
boolean isProfileIdRequired = scanType != ScanType.FullWithPrimaryProfile;
if (isProfileIdEmpty && isProfileIdRequired) {
result.add(new InvalidProperty(
ScanRequest.PROFILE_ID_Literal,
"The parameter 'Profile Name' must be specified."));
}
boolean isProfileIdValid = AppCommon.IsGUIDValid(properties.get(ScanRequest.PROFILE_ID_Literal));
if (!isProfileIdEmpty && isProfileIdRequired && !isProfileIdValid) {
result.add(new InvalidProperty(
ScanRequest.PROFILE_ID_Literal,
"The parameter 'Profile Name' is invalid"));
}
return result;
}
} | 34.083333 | 104 | 0.762836 |
292b9b6a85445ea3b77810a6780c3ec2aeb1e88e | 1,351 | /*
* 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.nifi.hbase.io;
import org.apache.nifi.hbase.scan.ResultCell;
import java.io.IOException;
import java.io.OutputStream;
public interface RowSerializer {
/**
* Serializes the given row and cells to the provided OutputStream
*
* @param rowKey the row's key
* @param cells the cells to serialize
* @param out the OutputStream to serialize to
* @throws IOException if unable to serialize the row
*/
void serialize(byte[] rowKey, ResultCell[] cells, OutputStream out) throws IOException;
}
| 37.527778 | 91 | 0.739452 |
f8ba099abffe5ae339d85f3aa875227fc0ac3117 | 1,573 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.test.runner;
import com.intellij.build.BuildViewSettingsProvider;
import com.intellij.execution.testframework.TestConsoleProperties;
import com.intellij.execution.testframework.sm.runner.SMTestLocator;
import com.intellij.execution.testframework.sm.runner.SMTestProxy;
import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView;
import com.intellij.openapi.util.registry.Registry;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* @author Vladislav.Soroka
*/
public class GradleTestsExecutionConsole extends SMTRunnerConsoleView implements BuildViewSettingsProvider {
private final Map<String, SMTestProxy> testsMap = new HashMap<>();
private final StringBuilder myBuffer = new StringBuilder();
public GradleTestsExecutionConsole(TestConsoleProperties consoleProperties, @Nullable String splitterProperty) {
super(consoleProperties, splitterProperty);
}
public Map<String, SMTestProxy> getTestsMap() {
return testsMap;
}
public StringBuilder getBuffer() {
return myBuffer;
}
@Override
public void dispose() {
testsMap.clear();
super.dispose();
}
public SMTestLocator getUrlProvider() {
return GradleConsoleProperties.GRADLE_TEST_LOCATOR;
}
@Override
public boolean isExecutionViewHidden() {
return Registry.is("build.view.side-by-side", true);
}
}
| 32.102041 | 140 | 0.78576 |
b5fafb7efa6bc665c81b8131f6a71b6a5d2b3198 | 1,693 | /*
* Copyright 2010-2021 Jan de Jongh <jfcmdejongh@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.javajdj.jinstrument.gpib.dmm.hp3478a;
import org.javajdj.jinstrument.AbstractInstrumentCalibrationData;
import org.javajdj.jinstrument.InstrumentCalibrationData;
/** Calibration Data for a {@link HP3478A_GPIB_Instrument} Digital MultiMeter.
*
* <p>
* Source credits: {@literal https://www.eevblog.com/forum/repair/hp-3478a-how-to-readwrite-cal-sram/}.
*
* @author Jan de Jongh {@literal <jfcmdejongh@gmail.com>}
*
*/
public final class HP3478A_GPIB_CalibrationData
extends AbstractInstrumentCalibrationData
implements InstrumentCalibrationData
{
public final static int SIZE = 256;
private static byte[] checkBytes (final byte[] bytes)
{
if (bytes == null || bytes.length != HP3478A_GPIB_CalibrationData.SIZE)
throw new IllegalArgumentException ();
for (final byte b : bytes)
if ((b & 0xf0) != 0x40)
throw new IllegalArgumentException ();
return bytes;
}
public HP3478A_GPIB_CalibrationData (final byte[] bytes)
{
super (HP3478A_GPIB_CalibrationData.checkBytes (bytes));
}
}
| 31.943396 | 103 | 0.732428 |
93e27f4a01e16cae09abb4314c49b4853dc982ff | 3,434 | /**
* 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.cxf.sts.claims;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.rt.security.claims.Claim;
import org.apache.cxf.rt.security.claims.ClaimCollection;
public class StaticEndpointClaimsHandler implements ClaimsHandler {
private static final Logger LOG = LogUtils.getL7dLogger(StaticEndpointClaimsHandler.class);
private Map<String, Map<String, String>> endpointClaimsMap;
private List<String> supportedClaims;
public void setEndpointClaims(Map<String, Map<String, String>> userClaims) {
this.endpointClaimsMap = userClaims;
}
public Map<String, Map<String, String>> getEndpointClaims() {
return endpointClaimsMap;
}
public void setSupportedClaims(List<String> supportedClaims) {
this.supportedClaims = supportedClaims;
}
public List<String> getSupportedClaimTypes() {
return Collections.unmodifiableList(this.supportedClaims);
}
public ProcessedClaimCollection retrieveClaimValues(
ClaimCollection claims, ClaimsParameters parameters) {
ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
String appliesTo = parameters.getAppliesToAddress();
if (appliesTo == null) {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("AppliesTo not provided in RST. " + StaticEndpointClaimsHandler.class.getName() + " ignored");
}
return claimsColl;
}
Map<String, String> endpointClaims = this.getEndpointClaims().get(appliesTo);
if (endpointClaims == null) {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer(StaticEndpointClaimsHandler.class.getName()
+ " doesn't define claims for endpoint '" + appliesTo + "'");
}
return claimsColl;
}
for (Claim claim : claims) {
if (endpointClaims.keySet().contains(claim.getClaimType().toString())) {
ProcessedClaim c = new ProcessedClaim();
c.setClaimType(claim.getClaimType());
c.setPrincipal(parameters.getPrincipal());
c.addValue(endpointClaims.get(claim.getClaimType().toString()));
claimsColl.add(c);
} else {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Unsupported claim: " + claim.getClaimType());
}
}
}
return claimsColl;
}
}
| 36.924731 | 120 | 0.669773 |
5ee854cc353fd40bd69f559d3d13f5b8cb38822b | 661 | package wolf;
import wolf.interfaces.Arg;
import wolf.interfaces.Visitor;
import wolf.node.TFloatNumber;
/**
* A float literal, represents a float.
* @author Kevin Dittmar
* @author William Ezekiel
* @author Joseph Alacqua
* @version Apr 3, 2016
*/
public class FloatLiteral implements Arg {
TFloatNumber float_literal;
public FloatLiteral(TFloatNumber float_literal) {
this.float_literal = float_literal;
}
/**
* Accepts a visitor
* @param v a visitor
* @return the type of this FloatLiteral, FLOAT
*/
@Override
public Object accept(Visitor v) {
return new Type(FlatType.FLOAT);
}
}
| 22.033333 | 53 | 0.676248 |
fca44391f37df924fc5b1c8efd83bd5304c22703 | 21,309 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package pulltorefresharpsample.pulltorefresharpsample;
public final class R {
public static final class attr {
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int contentViewId=0x7f010001;
/** If you are overriding the default fastscroll
drawable, set this to match the width
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int fastScrollThumbWidth=0x7f01000c;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int headerIconDrawable=0x7f01000a;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int headerId=0x7f010000;
/** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int headerTextColor=0x7f010009;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int ptrHeaderBackground=0x7f010008;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int pullDownProgressIndicatorId=0x7f010002;
/** <p>Must be a floating point value, such as "<code>1.2</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int pullDownTension=0x7f010004;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int pullEnabled=0x7f01000b;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int pullToRefreshText=0x7f010005;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int refreshingText=0x7f010007;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int releaseToRefreshText=0x7f010006;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int snapbackDuration=0x7f010003;
}
public static final class color {
public static final int content_background=0x7f040004;
public static final int ptrsharp_sb_gradient_end=0x7f040001;
public static final int ptrsharp_sb_gradient_start=0x7f040000;
public static final int ptrsharp_sb_header_text=0x7f040002;
public static final int ptrsharp_sb_header_text_shadow=0x7f040003;
}
public static final class dimen {
public static final int fastscroll_thumb_width=0x7f050000;
public static final int nav_width=0x7f050001;
}
public static final class drawable {
public static final int android_flavors=0x7f020000;
public static final int icon=0x7f020001;
public static final int progress_medium_holo=0x7f020002;
public static final int ptrsharp_serious_business_gradient=0x7f020003;
public static final int rounded_rect=0x7f020004;
public static final int serious_business_arrow=0x7f020005;
public static final int serious_business_arrow2=0x7f020006;
public static final int spinner_20_inner_holo=0x7f020007;
public static final int spinner_20_outer_holo=0x7f020008;
}
public static final class id {
public static final int expandablelist=0x7f080000;
public static final int fragment_container=0x7f080004;
public static final int gridview=0x7f080001;
public static final int header=0x7f080007;
public static final int header_container=0x7f080006;
public static final int icon=0x7f080009;
public static final int image_view=0x7f080003;
public static final int ptr_wrapper=0x7f080005;
public static final int pullDownProgressIndicator=0x7f080008;
public static final int scrollview=0x7f080002;
public static final int text=0x7f08000a;
}
public static final class layout {
public static final int expandable=0x7f030000;
public static final int expandable_group=0x7f030001;
public static final int expandable_item=0x7f030002;
public static final int grid=0x7f030003;
public static final int grid_item=0x7f030004;
public static final int image=0x7f030005;
public static final int main_layout=0x7f030006;
public static final int nav=0x7f030007;
public static final int nav_item=0x7f030008;
public static final int ptrsharp_header=0x7f030009;
}
public static final class string {
public static final int app_name=0x7f060004;
public static final int library_name=0x7f060000;
public static final int ptrsharp_pull_to_refresh=0x7f060001;
public static final int ptrsharp_refreshing=0x7f060003;
public static final int ptrsharp_release_to_refresh=0x7f060002;
}
public static final class style {
public static final int HoloProgressMedium=0x7f070000;
}
public static final class styleable {
/** Attributes that can be used with a PullToRefresharpWrapper.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_contentViewId PullToRefresharpSample.PullToRefresharpSample:contentViewId}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_fastScrollThumbWidth PullToRefresharpSample.PullToRefresharpSample:fastScrollThumbWidth}</code></td><td> If you are overriding the default fastscroll
drawable, set this to match the width </td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_headerIconDrawable PullToRefresharpSample.PullToRefresharpSample:headerIconDrawable}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_headerId PullToRefresharpSample.PullToRefresharpSample:headerId}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_headerTextColor PullToRefresharpSample.PullToRefresharpSample:headerTextColor}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_ptrHeaderBackground PullToRefresharpSample.PullToRefresharpSample:ptrHeaderBackground}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_pullDownProgressIndicatorId PullToRefresharpSample.PullToRefresharpSample:pullDownProgressIndicatorId}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_pullDownTension PullToRefresharpSample.PullToRefresharpSample:pullDownTension}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_pullEnabled PullToRefresharpSample.PullToRefresharpSample:pullEnabled}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_pullToRefreshText PullToRefresharpSample.PullToRefresharpSample:pullToRefreshText}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_refreshingText PullToRefresharpSample.PullToRefresharpSample:refreshingText}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_releaseToRefreshText PullToRefresharpSample.PullToRefresharpSample:releaseToRefreshText}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresharpWrapper_snapbackDuration PullToRefresharpSample.PullToRefresharpSample:snapbackDuration}</code></td><td></td></tr>
</table>
@see #PullToRefresharpWrapper_contentViewId
@see #PullToRefresharpWrapper_fastScrollThumbWidth
@see #PullToRefresharpWrapper_headerIconDrawable
@see #PullToRefresharpWrapper_headerId
@see #PullToRefresharpWrapper_headerTextColor
@see #PullToRefresharpWrapper_ptrHeaderBackground
@see #PullToRefresharpWrapper_pullDownProgressIndicatorId
@see #PullToRefresharpWrapper_pullDownTension
@see #PullToRefresharpWrapper_pullEnabled
@see #PullToRefresharpWrapper_pullToRefreshText
@see #PullToRefresharpWrapper_refreshingText
@see #PullToRefresharpWrapper_releaseToRefreshText
@see #PullToRefresharpWrapper_snapbackDuration
*/
public static final int[] PullToRefresharpWrapper = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007,
0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b,
0x7f01000c
};
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#contentViewId}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:contentViewId
*/
public static final int PullToRefresharpWrapper_contentViewId = 1;
/**
<p>
@attr description
If you are overriding the default fastscroll
drawable, set this to match the width
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name PullToRefresharpSample.PullToRefresharpSample:fastScrollThumbWidth
*/
public static final int PullToRefresharpWrapper_fastScrollThumbWidth = 12;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#headerIconDrawable}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name PullToRefresharpSample.PullToRefresharpSample:headerIconDrawable
*/
public static final int PullToRefresharpWrapper_headerIconDrawable = 10;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#headerId}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:headerId
*/
public static final int PullToRefresharpWrapper_headerId = 0;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#headerTextColor}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:headerTextColor
*/
public static final int PullToRefresharpWrapper_headerTextColor = 9;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#ptrHeaderBackground}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name PullToRefresharpSample.PullToRefresharpSample:ptrHeaderBackground
*/
public static final int PullToRefresharpWrapper_ptrHeaderBackground = 8;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#pullDownProgressIndicatorId}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:pullDownProgressIndicatorId
*/
public static final int PullToRefresharpWrapper_pullDownProgressIndicatorId = 2;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#pullDownTension}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a floating point value, such as "<code>1.2</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:pullDownTension
*/
public static final int PullToRefresharpWrapper_pullDownTension = 4;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#pullEnabled}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:pullEnabled
*/
public static final int PullToRefresharpWrapper_pullEnabled = 11;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#pullToRefreshText}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name PullToRefresharpSample.PullToRefresharpSample:pullToRefreshText
*/
public static final int PullToRefresharpWrapper_pullToRefreshText = 5;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#refreshingText}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name PullToRefresharpSample.PullToRefresharpSample:refreshingText
*/
public static final int PullToRefresharpWrapper_refreshingText = 7;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#releaseToRefreshText}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name PullToRefresharpSample.PullToRefresharpSample:releaseToRefreshText
*/
public static final int PullToRefresharpWrapper_releaseToRefreshText = 6;
/**
<p>This symbol is the offset where the {@link PullToRefresharpSample.PullToRefresharpSample.R.attr#snapbackDuration}
attribute's value can be found in the {@link #PullToRefresharpWrapper} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name PullToRefresharpSample.PullToRefresharpSample:snapbackDuration
*/
public static final int PullToRefresharpWrapper_snapbackDuration = 3;
};
}
| 56.824 | 206 | 0.673847 |
2e45a12eb5033f808df6558158f47a23e94d6e86 | 6,881 | package cc.mrbird.febs.dca.service.impl;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.dca.dao.DcaBSciencepublishMapper;
import cc.mrbird.febs.dca.entity.DcaBScientificprize;
import cc.mrbird.febs.dca.dao.DcaBScientificprizeMapper;
import cc.mrbird.febs.dca.entity.userXuhao;
import cc.mrbird.febs.dca.service.IDcaBScientificprizeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cc.mrbird.febs.dca.service.IDcaBUserapplyService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.time.LocalDate;
import java.util.stream.Collectors;
/**
* <p>
* 任现职以来科研获奖情况 服务实现类
* </p>
*
* @author viki
* @since 2020-11-06
*/
@Slf4j
@Service("IDcaBScientificprizeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DcaBScientificprizeServiceImpl extends ServiceImpl<DcaBScientificprizeMapper, DcaBScientificprize> implements IDcaBScientificprizeService {
@Autowired
IDcaBUserapplyService iDcaBUserapplyService;
@Autowired
private DcaBSciencepublishMapper dcaBSciencepublishMapper;
@Override
public IPage<DcaBScientificprize> findDcaBScientificprizes(QueryRequest request, DcaBScientificprize dcaBScientificprize) {
try {
LambdaQueryWrapper<DcaBScientificprize> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DcaBScientificprize::getIsDeletemark, 1);//1是未删 0是已删
if (StringUtils.isNotBlank(dcaBScientificprize.getUserAccount())) {
queryWrapper.and(wrap -> wrap.eq(DcaBScientificprize::getUserAccount, dcaBScientificprize.getUserAccount()).or()
.like(DcaBScientificprize::getUserAccountName, dcaBScientificprize.getUserAccount()));
}
if (StringUtils.isNotBlank(dcaBScientificprize.getAuditManName())) {// 年度 和高级、中级、初级
List<String> userAccountsList = this.iDcaBUserapplyService.getApplyAccount(dcaBScientificprize.getAuditMan(), dcaBScientificprize.getAuditManName());
if (userAccountsList.size() == 0) {
userAccountsList.add("qiuc09");
}
queryWrapper.in(DcaBScientificprize::getUserAccount, userAccountsList);
}
if (dcaBScientificprize.getState() != null) {
queryWrapper.eq(DcaBScientificprize::getState, dcaBScientificprize.getState());
}
if (dcaBScientificprize.getAuditState() != null && (dcaBScientificprize.getAuditState() >= 0)) {
queryWrapper.eq(DcaBScientificprize::getAuditState, dcaBScientificprize.getAuditState());
}
if (StringUtils.isNotBlank(dcaBScientificprize.getCreateTimeFrom()) && StringUtils.isNotBlank(dcaBScientificprize.getCreateTimeTo())) {
queryWrapper
.ge(DcaBScientificprize::getCreateTime, dcaBScientificprize.getCreateTimeFrom())
.le(DcaBScientificprize::getCreateTime, dcaBScientificprize.getCreateTimeTo());
}
if (dcaBScientificprize.getAuditXuhaoS() != null && (dcaBScientificprize.getAuditXuhaoS() > 0)) {
if (dcaBScientificprize.getAuditXuhaoE() == null || dcaBScientificprize.getAuditXuhaoE().equals(0)) {
dcaBScientificprize.setAuditXuhaoE(dcaBScientificprize.getAuditXuhaoS());
}
queryWrapper.apply(" dca_b_scientificprize.user_account in " +
"(select user_account from dca_b_user where patent_ranknum" +
" between " + dcaBScientificprize.getAuditXuhaoS() + " and" +
" " + dcaBScientificprize.getAuditXuhaoE() + ")");
}
Page<DcaBScientificprize> page = new Page<>();
SortUtil.handlePageSort(request, page, false);//true 是属性 false是数据库字段可两个
List<userXuhao> xuhaoList = this.dcaBSciencepublishMapper.getXuhao();
IPage<DcaBScientificprize> result = this.page(page, queryWrapper);
for (DcaBScientificprize item : result.getRecords()
) {
List<userXuhao> list2 = xuhaoList.stream().filter(p -> p.getUserAccount().equals(item.getUserAccount())).collect(Collectors.toList());
if (list2.size() > 0) {
item.setAuditXuhao(list2.get(0).getPatentRanknum());
}
}
return result;
} catch (Exception e) {
log.error("获取字典信息失败", e);
return null;
}
}
@Override
public IPage<DcaBScientificprize> findDcaBScientificprizeList(QueryRequest request, DcaBScientificprize dcaBScientificprize) {
try {
Page<DcaBScientificprize> page = new Page<>();
SortUtil.handlePageSort(request, page, false);//true 是属性 false是数据库字段可两个
return this.baseMapper.findDcaBScientificprize(page, dcaBScientificprize);
} catch (Exception e) {
log.error("获取任现职以来科研获奖情况失败", e);
return null;
}
}
@Override
@Transactional
public void createDcaBScientificprize(DcaBScientificprize dcaBScientificprize) {
dcaBScientificprize.setId(UUID.randomUUID().toString());
dcaBScientificprize.setCreateTime(new Date());
dcaBScientificprize.setIsDeletemark(1);
this.save(dcaBScientificprize);
}
@Override
@Transactional
public void updateDcaBScientificprize(DcaBScientificprize dcaBScientificprize) {
dcaBScientificprize.setModifyTime(new Date());
this.baseMapper.updateDcaBScientificprize(dcaBScientificprize);
}
@Override
@Transactional
public void deleteDcaBScientificprizes(String[] Ids) {
List<String> list = Arrays.asList(Ids);
this.baseMapper.deleteBatchIds(list);
}
@Override
@Transactional
public void deleteByuseraccount(String userAccount) {
this.baseMapper.deleteByAccount(userAccount);
}
@Override
@Transactional
public int getMaxDisplayIndexByuseraccount(String userAccount) {
return this.baseMapper.getMaxDisplayIndexByuseraccount(userAccount);
}
} | 45.269737 | 165 | 0.695393 |
8bdc283b16aa8a32e1dd5f4c275be3f7ae71908e | 1,854 | package me.yokeyword.sample.demo_zhihu.ui.fragment.fourth;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import me.yokeyword.sample.R;
import me.yokeyword.sample.demo_zhihu.base.BaseMainFragment;
import me.yokeyword.sample.demo_zhihu.ui.fragment.fourth.child.AvatarFragment;
import me.yokeyword.sample.demo_zhihu.ui.fragment.fourth.child.MeFragment;
/**
* Created by YoKeyword on 16/6/3.
*/
public class ZhihuFourthFragment extends BaseMainFragment {
private Toolbar mToolbar;
private View mView;
public static ZhihuFourthFragment newInstance() {
Bundle args = new Bundle();
ZhihuFourthFragment fragment = new ZhihuFourthFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.zhihu_fragment_fourth, container, false);
return mView;
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
if (findChildFragment(AvatarFragment.class) == null) {
loadFragment();
}
mToolbar = mView.findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.me);
}
private void loadFragment() {
loadRootFragment(R.id.fl_fourth_container_upper, AvatarFragment.newInstance());
loadRootFragment(R.id.fl_fourth_container_lower, MeFragment.newInstance());
}
public void onBackToFirstFragment() {
_mBackToFirstListener.onBackToFirstFragment();
}
}
| 31.423729 | 132 | 0.735167 |
4f1934961494270d3785389949e28508208f12f6 | 337 | package service.inventoryapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InventoryApiApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApiApplication.class, args);
}
}
| 24.071429 | 68 | 0.801187 |
24811f27784ad24a1792ba2b18e7b1526e1295ec | 519 | package io.smallrye.faulttolerance.core.scheduler;
import java.util.ServiceLoader;
public interface SchedulerRunnableWrapper {
Runnable wrap(Runnable runnable);
SchedulerRunnableWrapper INSTANCE = Loader.load();
// ---
class Loader {
private static SchedulerRunnableWrapper load() {
for (SchedulerRunnableWrapper found : ServiceLoader.load(SchedulerRunnableWrapper.class)) {
return found;
}
return runnable -> runnable;
}
}
}
| 24.714286 | 103 | 0.660886 |
673cd7a10c5d863a5fdcc96f5c067d7cb468d03e | 2,165 | /*
* Copyright 2009-2014 PrimeTek.
*
* 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.primefaces.showcase.view.misc;
import javax.faces.view.ViewScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.io.Serializable;
@Named
@ViewScoped
public class ProgressBarView implements Serializable {
private Integer progress1;
private Integer progress2;
public Integer getProgress1() {
progress1 = updateProgress(progress1);
return progress1;
}
public Integer getProgress2() {
progress2 = updateProgress(progress2);
return progress2;
}
public void longRunning() throws InterruptedException {
progress2 = 0;
while (progress2 == null || progress2 < 100) {
progress2 = updateProgress(progress2);
Thread.sleep(500);
}
}
private Integer updateProgress(Integer progress) {
if(progress == null) {
progress = 0;
}
else {
progress = progress + (int)(Math.random() * 35);
if(progress > 100)
progress = 100;
}
return progress;
}
public void setProgress1(Integer progress1) {
this.progress1 = progress1;
}
public void setProgress2(Integer progress2) {
this.progress2 = progress2;
}
public void onComplete() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Progress Completed"));
}
public void cancel() {
progress1 = null;
progress2 = null;
}
}
| 26.728395 | 99 | 0.65127 |
e4e96241dc7c07d87b94ae4f2555078add5d734a | 6,717 | /*
* Copyright (c) 2003, The JUNG Authors
*
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* https://github.com/jrtom/jung/blob/master/LICENSE for a description.
*/
package edu.uci.ics.jung.algorithms.shortestpath;
import java.util.Collection;
import com.google.common.base.Function;
import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality;
import edu.uci.ics.jung.algorithms.scoring.util.VertexScoreTransformer;
import edu.uci.ics.jung.graph.Hypergraph;
/**
* Statistics relating to vertex-vertex distances in a graph.
*
* <p>Formerly known as <code>GraphStatistics</code> in JUNG 1.x.
*
* @author Scott White
* @author Joshua O'Madadhain
*/
public class DistanceStatistics
{
/**
* For each vertex <code>v</code> in <code>graph</code>,
* calculates the average shortest path length from <code>v</code>
* to all other vertices in <code>graph</code> using the metric
* specified by <code>d</code>, and returns the results in a
* <code>Map</code> from vertices to <code>Double</code> values.
* If there exists an ordered pair <code><u,v></code>
* for which <code>d.getDistance(u,v)</code> returns <code>null</code>,
* then the average distance value for <code>u</code> will be stored
* as <code>Double.POSITIVE_INFINITY</code>).
*
* <p>Does not include self-distances (path lengths from <code>v</code>
* to <code>v</code>).
*
* <p>To calculate the average distances, ignoring edge weights if any:
* <pre>
* Map distances = DistanceStatistics.averageDistances(g, new UnweightedShortestPath(g));
* </pre>
* To calculate the average distances respecting edge weights:
* <pre>
* DijkstraShortestPath dsp = new DijkstraShortestPath(g, nev);
* Map distances = DistanceStatistics.averageDistances(g, dsp);
* </pre>
* where <code>nev</code> is an instance of <code>Transformer</code> that
* is used to fetch the weight for each edge.
*
* @see edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath
* @see edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance
*
* @param graph the graph for which distances are to be calculated
* @param d the distance metric to use for the calculation
* @param <V> the vertex type
* @param <E> the edge type
* @return a map from each vertex to the mean distance to each other (reachable) vertex
*/
public static <V,E> Function<V,Double> averageDistances(Hypergraph<V,E> graph, Distance<V> d)
{
final ClosenessCentrality<V,E> cc = new ClosenessCentrality<V,E>(graph, d);
return new VertexScoreTransformer<V, Double>(cc);
}
/**
* For each vertex <code>v</code> in <code>g</code>,
* calculates the average shortest path length from <code>v</code>
* to all other vertices in <code>g</code>, ignoring edge weights.
* @see #diameter(Hypergraph)
* @see edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality
*
* @param g the graph for which distances are to be calculated
* @param <V> the vertex type
* @param <E> the edge type
* @return a map from each vertex to the mean distance to each other (reachable) vertex
*/
public static <V,E> Function<V, Double> averageDistances(Hypergraph<V,E> g)
{
final ClosenessCentrality<V,E> cc = new ClosenessCentrality<V,E>(g,
new UnweightedShortestPath<V,E>(g));
return new VertexScoreTransformer<V, Double>(cc);
}
/**
* Returns the diameter of <code>g</code> using the metric
* specified by <code>d</code>. The diameter is defined to be
* the maximum, over all pairs of vertices <code>u,v</code>,
* of the length of the shortest path from <code>u</code> to
* <code>v</code>. If the graph is disconnected (that is, not
* all pairs of vertices are reachable from one another), the
* value returned will depend on <code>use_max</code>:
* if <code>use_max == true</code>, the value returned
* will be the the maximum shortest path length over all pairs of <b>connected</b>
* vertices; otherwise it will be <code>Double.POSITIVE_INFINITY</code>.
*
* @param g the graph for which distances are to be calculated
* @param d the distance metric to use for the calculation
* @param use_max if {@code true}, return the maximum shortest path length for all graphs;
* otherwise, return {@code Double.POSITIVE_INFINITY} for disconnected graphs
* @param <V> the vertex type
* @param <E> the edge type
* @return the longest distance from any vertex to any other
*/
public static <V, E> double diameter(Hypergraph<V,E> g, Distance<V> d, boolean use_max)
{
double diameter = 0;
Collection<V> vertices = g.getVertices();
for(V v : vertices) {
for(V w : vertices) {
if (v.equals(w) == false) // don't include self-distances
{
Number dist = d.getDistance(v, w);
if (dist == null)
{
if (!use_max)
return Double.POSITIVE_INFINITY;
}
else
diameter = Math.max(diameter, dist.doubleValue());
}
}
}
return diameter;
}
/**
* Returns the diameter of <code>g</code> using the metric
* specified by <code>d</code>. The diameter is defined to be
* the maximum, over all pairs of vertices <code>u,v</code>,
* of the length of the shortest path from <code>u</code> to
* <code>v</code>, or <code>Double.POSITIVE_INFINITY</code>
* if any of these distances do not exist.
* @see #diameter(Hypergraph, Distance, boolean)
*
* @param g the graph for which distances are to be calculated
* @param d the distance metric to use for the calculation
* @param <V> the vertex type
* @param <E> the edge type
* @return the longest distance from any vertex to any other
*/
public static <V, E> double diameter(Hypergraph<V,E> g, Distance<V> d)
{
return diameter(g, d, false);
}
/**
* Returns the diameter of <code>g</code>, ignoring edge weights.
* @see #diameter(Hypergraph, Distance, boolean)
*
* @param g the graph for which distances are to be calculated
* @param <V> the vertex type
* @param <E> the edge type
* @return the longest distance from any vertex to any other
*/
public static <V, E> double diameter(Hypergraph<V,E> g)
{
return diameter(g, new UnweightedShortestPath<V,E>(g));
}
}
| 40.463855 | 97 | 0.644038 |
98756c9ae930f010e3db12237a45f9f98c5a43d0 | 2,806 | /*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package jdk.jshell;
import jdk.jshell.Key.ImportKey;
/**
* Snippet for an import declaration.
* The Kind is {@link jdk.jshell.Snippet.Kind#IMPORT}.
* <p>
* {@code ImportSnippet} is immutable: an access to
* any of its methods will always return the same result.
* and thus is thread-safe.
*
* @since 9
* @jls 7.5 Import Declarations
*/
public class ImportSnippet extends PersistentSnippet {
final String fullname;
final String fullkey;
final boolean isStatic;
final boolean isStar;
ImportSnippet(ImportKey key, String userSource, Wrap guts,
String fullname, String name, SubKind subkind, String fullkey,
boolean isStatic, boolean isStar) {
super(key, userSource, guts, name, subkind, null);
this.fullname = fullname;
this.fullkey = fullkey;
this.isStatic = isStatic;
this.isStar = isStar;
}
/**
* The identifying name of the import. For on-demand imports
* ({@link jdk.jshell.Snippet.SubKind#TYPE_IMPORT_ON_DEMAND_SUBKIND} or
* ({@link jdk.jshell.Snippet.SubKind#STATIC_IMPORT_ON_DEMAND_SUBKIND})
* that is the full specifier including any
* qualifiers and the asterisks. For single imports
* ({@link jdk.jshell.Snippet.SubKind#SINGLE_TYPE_IMPORT_SUBKIND} or
* ({@link jdk.jshell.Snippet.SubKind#SINGLE_STATIC_IMPORT_SUBKIND}),
* it is the imported name. That is, the unqualified name.
* @return the name of the import.
*/
@Override
public String name() {
return key().name();
}
/**
*
* The qualified name of the import. For any imports
* ({@link jdk.jshell.Snippet.SubKind#TYPE_IMPORT_ON_DEMAND_SUBKIND},
* ({@link jdk.jshell.Snippet.SubKind#STATIC_IMPORT_ON_DEMAND_SUBKIND}),
* ({@link jdk.jshell.Snippet.SubKind#SINGLE_TYPE_IMPORT_SUBKIND} or
* ({@link jdk.jshell.Snippet.SubKind#SINGLE_STATIC_IMPORT_SUBKIND})
* that is the full specifier including any
* qualifiers and the asterisks.
* @return the fullname of the import
*/
public String fullname() {
return fullname;
}
/**
* Indicates whether this snippet represents a static import.
*
* @return {@code true} if this snippet represents a static import;
* otherwise {@code false}
*/
public boolean isStatic() {
return isStatic;
}
/**** internal access ****/
@Override
ImportKey key() {
return (ImportKey) super.key();
}
@Override
String importLine(JShell state) {
return guts().wrapped();
}
}
| 25.279279 | 79 | 0.647541 |
7283f4faf98b1240a5c3c30bf35c20394c0c028e | 13,810 | /*
* 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.harmony.test.func.api.java.beans.boundproperties;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListenerProxy;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.harmony.test.func.api.java.beans.boundproperties.auxiliary.AuxiliaryPropertyChangeListener0;
import org.apache.harmony.test.func.api.java.beans.boundproperties.auxiliary.AuxiliaryPropertyChangeListener1;
import org.apache.harmony.test.func.api.java.beans.boundproperties.auxiliary.AuxiliaryPropertyChangeListener2;
import org.apache.harmony.test.func.api.java.beans.boundproperties.auxiliary.SimpleListener;
import org.apache.harmony.share.MultiCase;
import org.apache.harmony.share.Result;
/**
* Under test: PropertyChangeSupport,PropertyChangeListenerProxy,
* PropertyChangeEvent.
* <p>
* Purpose: test firePropertyChange(PropertyChangeEvent evt),
* firePropertyChange(String propertyName, boolean oldValue, boolean newValue),
* firePropertyChange(String propertyName, int oldValue, int newValue),
* getPropertyChangeListeners(), getPropertyChangeListeners(String
* propertyName), hasListeners(String propertyName) methods from
* PropertyChangeSupport class.
*
*/
public class BasicTests extends MultiCase {
public static void main(String[] args) {
try {
System.exit(new BasicTests().test(args));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Verify that getPropertyChangeListeners() method returns listener
* registered for all properties.
* <p>
* Step-by-step encoding: register a listener for all properties. Verify
* that getPropertyChangeListeners() method returns the listener.
*/
public Result testGetPropertyChangeListeners01() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
propertyChangeSupport.addPropertyChangeListener(new SimpleListener());
assertEquals(propertyChangeSupport.getPropertyChangeListeners()[0]
.getClass(), SimpleListener.class);
return passed();
}
/**
* Verify that getPropertyChangeListeners(String selectedPropertyName)
* method returns listener registered for selected property.
* <p>
* Step-by-step encoding: register a listener for selected properties.
* Verify that getPropertyChangeListeners(String selectedPropertyName)
* method returns the listener.
*/
public Result testGetPropertyChangeListeners02() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
propertyChangeSupport.addPropertyChangeListener("property1",
new SimpleListener());
assertEquals(propertyChangeSupport
.getPropertyChangeListeners("property1")[0].getClass(),
SimpleListener.class);
return passed();
}
/**
* Verify that by default getPropertyChangeListeners() method returns empty
* array.
*/
public Result testGetPropertyChangeListeners03() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
assertEquals(propertyChangeSupport.getPropertyChangeListeners().length,
0);
return passed();
}
/**
* Verify that by default getPropertyChangeListeners(String propertyName)
* method returns empty array.
*/
public Result testGetPropertyChangeListeners04() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
assertEquals(propertyChangeSupport
.getPropertyChangeListeners("property1").length, 0);
return passed();
}
/**
* Verify that if a listener have been registered for selected property,
* then getPropertyChangeListeners() method returns
* PropertyChangeListenerProxy, which is a wrapper for the registered
* listener.
* <p>
* Step-by-step encoding:
* <ul>
* <li>Register a listener for selected properties.
* <li>Invoke getPropertyChangeListeners() method.
* <li>Verify that returned value is PropertyChangeListenerProxy object.
* <li>Verify that getListener() of PropertyChangeListenerProxy object
* returns registered listener.
* <li>Verify that getPropertyName() of PropertyChangeListenerProxy object
* returns a name of selected property.
*/
public Result testGetPropertyChangeListeners05() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
propertyChangeSupport.addPropertyChangeListener("property1",
new SimpleListener());
PropertyChangeListenerProxy propertyChangeListener2 = (PropertyChangeListenerProxy)propertyChangeSupport
.getPropertyChangeListeners()[0];
assertEquals(propertyChangeListener2.getListener().getClass(),
SimpleListener.class);
assertEquals(propertyChangeListener2.getPropertyName(), "property1");
return passed();
}
/**
* Verify that no event is fired if old and new values are equal.
* <p>
* Step-by-step encoding: register a listener for selected properties. Call
* firePropertyChange method for selected property with the same old and new
* values. Verify that no event is fired.
*/
public Result testFirePropertyChange01() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
SimpleListener simpleListener = new SimpleListener();
propertyChangeSupport.addPropertyChangeListener("property1",
simpleListener);
propertyChangeSupport.firePropertyChange("property1", "value", "value");
assertFalse(simpleListener.isInvoked());
return passed();
}
/**
* Verify that listener is notified when
* firePropertyChange(PropertyChangeEvent evt) method is invoked.
* <p>
* Step-by-step encoding: create PropertyChangeEvent, register a listener
* for selected properties, invoked firePropertyChange method for selected
* property. Verify that listener is notified.
*/
public Result testFirePropertyChange02() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
SimpleListener simpleListener = new SimpleListener();
propertyChangeSupport.addPropertyChangeListener(simpleListener);
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(
"bean1", "property1", "old value", "new value"));
assertTrue(simpleListener.isInvoked());
return passed();
}
/**
* Verify that listener is notified when firePropertyChange(String
* propertyName, boolean oldValue, boolean newValue) method is invoked.
* <p>
* Step-by-step encoding: register a listener for selected properties,
* invoked firePropertyChange method for selected property. Verify that
* listener is notified.
*/
public Result testFirePropertyChange03() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
SimpleListener simpleListener = new SimpleListener();
propertyChangeSupport.addPropertyChangeListener(simpleListener);
propertyChangeSupport.firePropertyChange("property1", false, true);
assertTrue(simpleListener.isInvoked());
return passed();
}
/**
* Verify that listener is notified when firePropertyChange(String
* propertyName, int oldValue, int newValue) method is invoked.
* <p>
* Step-by-step encoding: register a listener for selected properties,
* invoked firePropertyChange method for selected property. Verify that
* listener is notified.
*/
public Result testFirePropertyChange04() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
SimpleListener simpleListener = new SimpleListener();
propertyChangeSupport.addPropertyChangeListener(simpleListener);
propertyChangeSupport.firePropertyChange("property1", 0, 1);
assertTrue(simpleListener.isInvoked());
return passed();
}
/**
* Verify that hasListeners method returns true if there are any listeners
* for a specific property.
* <p>
* Step-by-step encoding: register a listener for selected property. Verify
* that hasListeners(String selectedPropertyName) method returns the
* listener.
*/
public Result testHasListeners01() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
propertyChangeSupport.addPropertyChangeListener("property1",
new SimpleListener());
assertTrue(propertyChangeSupport.hasListeners("property1"));
return passed();
}
/**
* Verify that by default hasListeners(String propertyName) method returns
* false.
*/
public Result testHasListeners02() {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
assertFalse(propertyChangeSupport.hasListeners("property1"));
return passed();
}
/**
* Verify that getPropagationId() of PropertyChangeEvent class returns
* propagationId.
* <p>
* Step-by-step encoding: set propagationId. Verify that getPropagationId()
* method returns PropagationId.
*/
public Result testPropagationId() {
PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(
"bean1", "property1", "old value", "new value");
propertyChangeEvent.setPropagationId("PropagationId");
assertEquals(propertyChangeEvent.getPropagationId(), "PropagationId");
return passed();
}
/**
* Verify that when one serializes PropertyChangeSupport class, all
* serializable listeners are serialized and non-serializable listeners
* aren't serialize.
* <p>
* Step-by-step encoding:
* <ul>
* <li>Add serializable listener#0 to all properties.
* <li>Add non-serializable listener#1 to certain property#1.
* <li>Add serializable listener#2 to certain property#2.
* <li>Verify that getPropertyChangeListeners() method returns massive
* consisting of two listeners. Verify that first listener is listener#0.
* <li>Verify that getPropertyChangeListeners(property#1) returns empty
* massive.
* <li>Verify that getPropertyChangeListeners(property#2) returns
* listener#2.
*/
public Result testSerialisation() throws Exception {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
"bean1");
propertyChangeSupport
.addPropertyChangeListener(new AuxiliaryPropertyChangeListener0());
propertyChangeSupport.addPropertyChangeListener("prop1",
new AuxiliaryPropertyChangeListener1());
propertyChangeSupport.addPropertyChangeListener("prop2",
new AuxiliaryPropertyChangeListener2());
PropertyChangeSupport propertyChangeSupport2 = serialisationDesirialisation(propertyChangeSupport);
assertEquals(
propertyChangeSupport2.getPropertyChangeListeners().length, 2);
assertEquals(
propertyChangeSupport2.getPropertyChangeListeners("prop1").length,
0);
assertEquals(
propertyChangeSupport2.getPropertyChangeListeners("prop2").length,
1);
assertEquals(
propertyChangeSupport2.getPropertyChangeListeners("prop2")[0]
.getClass(), AuxiliaryPropertyChangeListener2.class);
assertEquals(propertyChangeSupport2.getPropertyChangeListeners()[0]
.getClass(), AuxiliaryPropertyChangeListener0.class);
return passed();
}
/**
* Verify that NullPointerException isn't threw, if add listener to "null"
* property.
*/
public Result testNullProperty() {
new PropertyChangeSupport("bean1").addPropertyChangeListener(null,
new AuxiliaryPropertyChangeListener0());
return passed();
}
/**
* Serialize and deserialize object.
*/
private PropertyChangeSupport serialisationDesirialisation(
PropertyChangeSupport object) throws Exception {
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(outBytes);
objectOut.writeObject(object);
objectOut.close();
ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(outBytes.toByteArray()));
return (PropertyChangeSupport)objectInputStream.readObject();
}
} | 42.103659 | 112 | 0.706517 |
e9477716a63c5a6bf17eb26eeb610c715cf5e135 | 1,361 | //Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000,
// and there exists one unique longest palindromic substring.
package org.leituo.leetcode.stringM;
/**
* Created by leituo56 on 1/5/15.
*/
public class LongestPalindromicSubstring {
class Solution{
//mid part of palindrom always are either 'YXY' pattern or 'XX' pattern.
//for each [pos], [pos-1, pos], try to expend to find the biggest one from this center
public String longestPalindrome(String s) {
if(s == null || s.length() <= 1)
return s;
String result = "";
for(int i = 1; i < s.length(); i++){
String expOdd = expend(s, i, i);
String expEven = expend(s, i-1, i);
if(expOdd.length() > result.length())
result = expOdd;
if(expEven.length() > result.length())
result = expEven;
}
return result;
}
private String expend(String s, int left, int right){
while(left >= 0 && right < s.length()){
if(s.charAt(left)!=s.charAt(right))
break;
left--;
right++;
}
return s.substring(left+1, right);
}
}
}
| 35.815789 | 117 | 0.521675 |
f3e523c30bd2ccb27f5fb92d9a89807c1660e14c | 177 | package example.java;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JavaUnitTest {
@Test
public void test() {
assertTrue(true);
}
}
| 14.75 | 42 | 0.717514 |
fc5913f7ab3ddf552a06248c75aedc066cacf190 | 1,470 | /**
* generated by Xtext 2.22.0
*/
package org.sodalite.dsl.optimization.optimization;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>EAI Training Case</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.sodalite.dsl.optimization.optimization.EAITrainingCase#getAi_training <em>Ai training</em>}</li>
* </ul>
*
* @see org.sodalite.dsl.optimization.optimization.OptimizationPackage#getEAITrainingCase()
* @model
* @generated
*/
public interface EAITrainingCase extends EOptimizationCases
{
/**
* Returns the value of the '<em><b>Ai training</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Ai training</em>' containment reference.
* @see #setAi_training(EAITraining)
* @see org.sodalite.dsl.optimization.optimization.OptimizationPackage#getEAITrainingCase_Ai_training()
* @model containment="true"
* @generated
*/
EAITraining getAi_training();
/**
* Sets the value of the '{@link org.sodalite.dsl.optimization.optimization.EAITrainingCase#getAi_training <em>Ai training</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Ai training</em>' containment reference.
* @see #getAi_training()
* @generated
*/
void setAi_training(EAITraining value);
} // EAITrainingCase
| 30.625 | 154 | 0.676871 |
52f9b84a5fd99abf2204712e5bd819cf8d044da0 | 11,880 | /******************************************************************************
* Copyright © 2015-7532 NOX, Inc. [NEPOLIX]-(Behrooz Shahriari) *
* All rights reserved. *
* *
* The source code, other & all material, and documentation *
* contained herein are, and remains the property of HEX Inc. *
* and its suppliers, if any. The intellectual and technical *
* concepts contained herein are proprietary to NOX Inc. and its *
* suppliers and may be covered by U.S. and Foreign Patents, patents *
* in process, and are protected by trade secret or copyright law. *
* Dissemination of the foregoing material or reproduction of this *
* material is strictly forbidden forever. *
******************************************************************************/
package com.nepolix.misha.db.cold.client;
import com.nepolix.misha.commons.utils.Utils;
import com.nepolix.misha.commons.xstructures.ModelIDList;
import com.nepolix.misha.db.MishaDB;
import com.nepolix.misha.db.MishaDB$A;
import com.nepolix.misha.db.cold.ColdDBConstants;
import com.nepolix.misha.db.cold.service.athena.AthenaHandler;
import com.nepolix.misha.db.exception.MishaSQLFormatException;
import com.nepolix.misha.db.model.MModel;
import com.nepolix.misha.id.MIDConstants;
import com.nepolix.misha.id.client.MishaID;
import com.nepolix.misha.id.exception.MishaIDException;
import com.nepolix.misha.json.JSONArray;
import com.nepolix.misha.json.JSONObject;
import com.nepolix.misha.json.serialization.MJSON;
import com.nepolix.misha.socket.SocketChannel;
import com.nepolix.misha.socket.SocketChannelPool;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Behrooz Shahriari
* @since 2/22/18
*/
public
class MishaColdDB
extends MishaDB$A
{
private static MishaColdDB mishaColdDB = null;
private SocketChannelPool socketChannelPool;
public
MishaColdDB ( MishaID mishaID )
{
super ( mishaID );
socketChannelPool = SocketChannelPool.build ( 2 , ColdDBConstants.getStoreClusterAddress ( ) , ColdDBConstants.getPort ( ) , 120000 );
}
public static
void initInetAddress ( String[] storeClusterAddress ,
Integer regionIdx )
{
ColdDBConstants.initClusterAddresses ( storeClusterAddress , regionIdx );
}
public static
MishaColdDB init ( MishaID mishaID ,
String[] storeClusterAddress ,
Integer regionIdx ,
String AWS_ACCESS_KEY ,
String AWS_PRIVATE_KEY ,
String athenaURL ,
String accountId )
{
ColdDBConstants.setAwsAccessKey ( AWS_ACCESS_KEY );
ColdDBConstants.setAwsPrivateKey ( AWS_PRIVATE_KEY );
ColdDBConstants.setAthenaUrl ( athenaURL );
ColdDBConstants.setAccountId ( accountId );
initInetAddress ( storeClusterAddress , regionIdx );
if ( mishaColdDB == null ) mishaColdDB = new MishaColdDB ( mishaID );
return getInstance ( );
}
public static
MishaColdDB getInstance ( )
{
try
{
ColdDBConstants.getStoreClusterAddress ( );
}
catch ( Exception e )
{
throw new MissingResourceException ( "Please first call 'initInetAddress' to init the address of cluster nodes with region index" , MishaColdDB.class.getSimpleName ( ) , "cluster address" );
}
if ( mishaColdDB == null ) throw new NullPointerException ( "first initialize the misha-cold-db" );
else return mishaColdDB;
}
@Override
protected
void init ( )
{
}
public
void sync ( boolean deleteLocal )
{
JSONObject message = new JSONObject ( );
message.putOpt ( "method" , "sync" ).putOpt ( "misha_id_address" , MIDConstants.getMishaIdAddress ( ) ).putOpt ( "delete_local_files" , deleteLocal )
.putOpt ( "account" , ColdDBConstants.getAccountId ( ) );
SocketChannel socketChannel = socketChannelPool.getChannel ( );
try
{
socketChannel.writeMessage ( message.toString ( ) );
socketChannel.readMessage ( );
socketChannelPool.returnChannel ( socketChannel );
}
catch ( Exception e )
{
e.printStackTrace ( );
}
}
@Override
public
< T extends MModel > T findOne ( JSONObject query ,
Class< T > clazz )
{
List< T > list = find ( query , 1 , 0 , clazz );
if ( list != null && !list.isEmpty ( ) ) return list.get ( 0 );
return null;
}
@Override
public
< T extends MModel > T findOne ( String mid ,
Class< T > clazz )
{
Set< String > set = new LinkedHashSet<> ( );
set.add ( mid );
Set< T > result = findObjects ( set , clazz );
if ( result != null && !result.isEmpty ( ) ) return result.iterator ( ).next ( );
else return null;
}
@Override
public
JSONObject findOne ( String mid ,
String collectionName )
{
Set< String > mids = new LinkedHashSet<> ( );
mids.add ( mid );
List< JSONObject > list;
try
{
list = AthenaHandler.getAthenaHandler ( ).getLastObjects ( mids , collectionName );
if ( !list.isEmpty ( ) ) return list.get ( 0 );
}
catch ( SQLException e )
{
e.printStackTrace ( );
}
return null;
}
public
Map< String, List< JSONObject > > findObjects ( JSONObject query ,
int limit ,
Integer limitPerObject ,
String collectionName )
{
List< JSONObject > list = find ( query , limit , 0 , collectionName );
if ( list != null || !list.isEmpty ( ) )
{
Set< String > mids = new LinkedHashSet<> ( );
list.forEach ( v -> mids.add ( v.optString ( "mid" ) ) );
return fetchObjects ( mids , collectionName , limitPerObject );
}
return null;
}
public
< T extends MModel > Map< String, List< T > > findObjects ( JSONObject query ,
int limit ,
Integer limitPerObject ,
Class< T > clazz )
{
String collectionName = MModel.getModelName ( clazz );
Map< String, List< JSONObject > > map = findObjects ( query , limit , limitPerObject , collectionName );
if ( map != null )
{
Map< String, List< T > > models = new LinkedHashMap<> ( );
map.keySet ( ).forEach ( k -> {
List< T > list = new ArrayList<> ( );
map.get ( k ).forEach ( v -> list.add ( MJSON.toObject ( v , clazz ) ) );
models.put ( k , list );
} );
return models;
}
return null;
}
@Override
public
< T extends MModel > List< T > find ( JSONObject query ,
int limit ,
int offset ,
Class< T > clazz )
{
List< T > models = new ArrayList<> ( );
String collectionName = MModel.getModelName ( clazz );
List< JSONObject > list = find ( query , limit , offset , collectionName );
if ( list != null || !list.isEmpty ( ) )
{
list.forEach ( v -> models.add ( MJSON.toObject ( v , clazz ) ) );
}
return models;
}
@Override
public
List< JSONObject > find ( JSONObject query ,
int limit ,
int offset ,
String collectionName )
{
try
{
return AthenaHandler.getAthenaHandler ( ).find ( query , limit , collectionName );
}
catch ( MishaSQLFormatException e )
{
e.printStackTrace ( );
}
return null;
}
@Override
public
< T extends MModel > Set< T > findObjects ( Collection< String > mids ,
Class< T > clazz )
{
try
{
String collectionName = MModel.getModelName ( clazz );
Set< T > set = new LinkedHashSet<> ( );
AthenaHandler.getAthenaHandler ( ).getLastObjects ( mids , collectionName ).forEach ( v -> set.add ( MJSON.toObject ( v , clazz ) ) );
return set;
}
catch ( SQLException e )
{
e.printStackTrace ( );
}
return null;
}
public
< T extends MModel > Map< String, List< JSONObject > > fetchObjects ( final Collection< String > mids ,
String collectionName ,
Integer limitPerObject )
{
try
{
return AthenaHandler.getAthenaHandler ( ).getObjects ( mids , collectionName , limitPerObject );
}
catch ( SQLException e )
{
e.printStackTrace ( );
}
return null;
}
public
< T extends MModel > Map< String, List< T > > fetchObjects ( final Collection< String > mids ,
Class< T > clazz ,
Integer limitPerObject )
{
try
{
String collectionName = MModel.getModelName ( clazz );
Map< String, List< JSONObject > > mapModelsX = AthenaHandler.getAthenaHandler ( ).getObjects ( mids , collectionName , limitPerObject );
Map< String, List< T > > models = new LinkedHashMap<> ( );
mapModelsX.keySet ( ).forEach ( k -> {
List< T > list = new ArrayList<> ( );
mapModelsX.get ( k ).forEach ( v -> list.add ( MJSON.toObject ( v , clazz ) ) );
models.put ( k , list );
} );
return models;
}
catch ( SQLException e )
{
e.printStackTrace ( );
}
return null;
}
@Override
public
< T extends MModel > MishaDB save ( Collection< T > objects )
{
if ( objects != null && !objects.isEmpty ( ) )
{
JSONArray objectArray = new JSONArray ( );
AtomicReference< String > collectionName = new AtomicReference<> ( );
objects.forEach ( o -> {
objectArray.put ( MJSON.toJSON ( o ) );
o.setUpdateTime ( Utils.getCurrentUTCTime ( ) );
collectionName.set ( o.modelName ( ) );
} );
S3SaveHelper.getSaveHelper ( ).store ( socketChannelPool , collectionName.get ( ) , objectArray );
}
return this;
}
@Override
public
void save ( String collectionName ,
JSONObject object )
{
JSONArray objectArray = new JSONArray ( );
objectArray.put ( object );
S3SaveHelper.getSaveHelper ( ).store ( socketChannelPool , collectionName , objectArray );
}
@Override
public
void save ( MModel object )
throws
MishaIDException,
NullPointerException
{
if ( object != null )
{
if ( object.getMid ( ) == null || object.getMid ( ).isEmpty ( ) ) throw new MishaIDException ( "object must contain 'mid::String' field " + "is a unique " + "identifier" );
object.setUpdateTime ( Utils.getCurrentUTCTime ( ) );
save ( object.modelName ( ) , MJSON.toJSON ( object ) );
}
}
@Override
public
< T extends MModel > int delete ( JSONObject query ,
Class< T > clazz )
{
throw new UnsupportedOperationException ( "delete not supported for coldDB" );
}
@Override
public
int deleteObjects ( Collection< String > mids ,
String collectionName )
{
throw new UnsupportedOperationException ( "deleteObjects not supported for coldDB" );
}
@Override
public
< T extends MModel > ModelIDList getCollectionIDs ( Class< T > modelClass )
{
return null;
}
}
| 30.777202 | 196 | 0.564226 |
9d8cc2699e053f120aaee2c41f9ac8213d9a7bac | 374 | package com.is4ii4s.controlepontoacesso.repository;
import com.is4ii4s.controlepontoacesso.model.Localidade;
import com.is4ii4s.controlepontoacesso.model.NivelAcesso;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LocalidadeRepository extends JpaRepository<Localidade, Long> {
} | 37.4 | 79 | 0.86631 |
54981e2481799b29fb7c55e72541852f6de9c6e5 | 927 | package net.glowstone.net.message.play.entity;
import com.flowpowered.networking.Message;
public final class SpawnLightningStrikeMessage implements Message {
private final int id, mode, x, y, z;
public SpawnLightningStrikeMessage(int id, int x, int y, int z) {
this(id, 1, x, y, z);
}
public SpawnLightningStrikeMessage(int id, int mode, int x, int y, int z) {
this.id = id;
this.mode = mode;
this.x = x;
this.y = y;
this.z = z;
}
public int getId() {
return id;
}
public int getMode() {
return mode;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
@Override
public String toString() {
return "SpawnLightningStrikeMessage{id=" + id + ",mode=" + mode + ",x=" + x + ",y=" + y + ",z=" + z + "}";
}
}
| 19.723404 | 114 | 0.541532 |
02ff55ec7b65a28e32c314501ef1978b43c01bbd | 15,456 |
package de.unikn.inf.disy.nuntifix.dtn.simulator.bloomfilter;
import java.util.Enumeration;
import java.util.LinkedList;
import de.unikn.inf.disy.nuntifix.dtn.simulator.metaclasses.Device;
import de.unikn.inf.disy.nuntifix.dtn.simulator.metaclasses.MeetingStats;
/*
* ************************************************************************* *
* General Purpose Hash Function Algorithms Library * * Author: Arash Partow -
* 2002 * URL: http://www.partow.net * URL:
* http://www.partow.net/programming/hashfunctions/index.html * * Copyright
* notice: * Free use of the General Purpose Hash Function Algorithms Library is *
* permitted under the guidelines and in accordance with the most current *
* version of the Common Public License. *
* http://www.opensource.org/licenses/cpl.php * *
* *************************************************************************
*/
class BloomFilterLibrary {
float tune = (float) 0.6;
public long RSHash(String str) {
int b = 378551;
int a = 63689;
long hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = hash * a + str.charAt(i);
a = a * b;
}
return Math.abs(hash);
}
/* End Of RS Hash Function */
public long JSHash(String str) {
long hash = 1315423911;
for (int i = 0; i < str.length(); i++) {
hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2));
}
return Math.abs(hash);
}
/* End Of JS Hash Function */
public long PJWHash(String str) {
long BitsInUnsignedInt = (long) (4 * 8);
long ThreeQuarters = (long) ((BitsInUnsignedInt * 3) / 4);
long OneEighth = (long) (BitsInUnsignedInt / 8);
long HighBits = (long) (0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth);
long hash = 0;
long test = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash << OneEighth) + str.charAt(i);
if ((test = hash & HighBits) != 0) {
hash = ((hash ^ (test >> ThreeQuarters)) & (~HighBits));
}
}
return Math.abs(hash);
}
/* End Of P. J. Weinberger Hash Function */
public long ELFHash(String str) {
long hash = 0;
long x = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash << 4) + str.charAt(i);
if ((x = hash & 0xF0000000L) != 0) {
hash ^= (x >> 24);
}
hash &= ~x;
}
return Math.abs(hash);
}
/* End Of ELF Hash Function */
public long BKDRHash(String str) {
long seed = 131; // 31 131 1313 13131 131313 etc..
long hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash * seed) + str.charAt(i);
}
return Math.abs(hash);
}
/* End Of BKDR Hash Function */
public long SDBMHash(String str) {
long hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash;
}
return Math.abs(hash);
}
/* End Of SDBM Hash Function */
public long DJBHash(String str) {
long hash = 5381;
for (int i = 0; i < str.length(); i++) {
hash = ((hash << 5) + hash) + str.charAt(i);
}
return Math.abs(hash);
}
/* End Of DJB Hash Function */
public long DEKHash(String str) {
long hash = str.length();
for (int i = 0; i < str.length(); i++) {
hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);
}
return Math.abs(hash);
}
/* End Of DEK Hash Function */
public long BPHash(String str) {
long hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = hash << 7 ^ str.charAt(i);
}
return Math.abs(hash);
}
/* End Of BP Hash Function */
public long FNVHash(String str) {
long fnv_prime = 0x811C9DC5;
long hash = 0;
for (int i = 0; i < str.length(); i++) {
hash *= fnv_prime;
hash ^= str.charAt(i);
}
return Math.abs(hash);
}
/* End Of FNV Hash Function */
public long APHash(String str) {
long hash = 0xAAAAAAAA;
for (int i = 0; i < str.length(); i++) {
if ((i & 1) == 0) {
hash ^= ((hash << 7) ^ str.charAt(i) ^ (hash >> 3));
} else {
hash ^= (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5)));
}
}
return Math.abs(hash);
}
/* End Of AP Hash Function */
/*
* public void UpdateVal(Device dtemp, Device dtemp2,float bval,LinkedList
* tabdevList){ int bfilterlength = dtemp.bloom[0].size(); switch
* ((int)Math.round((Math.log10(bfilterlength)/Math.log10(2))*tune)){ case 11:
* if(dtemp.bloom[0].get((int)(RSHash(dtemp2.mac)%bfilterlength)).proximity<bval)
* dtemp.bloom[0].set( (int)(RSHash(dtemp2.mac)%bfilterlength), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 10:
* if(dtemp.bloom[0].get((int)((JSHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((JSHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 9:
* if(dtemp.bloom[0].get((int)((PJWHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((PJWHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 8:
* if(dtemp.bloom[0].get((int)((ELFHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((ELFHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 7:
* if(dtemp.bloom[0].get((int)((BKDRHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((BKDRHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 6:
* if(dtemp.bloom[0].get((int)((DJBHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((DJBHash(dtemp.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 5:
* if(dtemp.bloom[0].get((int)((DEKHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((DEKHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 4:
* if(dtemp.bloom[0].get((int)((BPHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((BPHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 3:
* if(dtemp.bloom[0].get((int)(FNVHash(dtemp2.mac)%bfilterlength)).proximity<bval)
* dtemp.bloom[0].set( (int)((FNVHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 2:
* if(dtemp.bloom[0].get((int)((SDBMHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((SDBMHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); case 1:
* if(dtemp.bloom[0].get((int)((APHash(dtemp2.mac)%bfilterlength))).proximity<bval)
* dtemp.bloom[0].set( (int)((APHash(dtemp2.mac)%bfilterlength)), new
* BloomValue(tabdevList.indexOf(dtemp2.mac),bval)); break; } }
*/
/*
* public int []GetHash(Device dtemp, String mac){ int bfilterlength =
* dtemp.bloom[0].size(); int []hashval = new int
* [(int)Math.round((Math.log10(bfilterlength)/Math.log10(2))*tune)]; switch
* ((int)Math.round((Math.log10(bfilterlength)/Math.log10(2))*tune)){ case 11:
* hashval[10]= (int)(RSHash(mac)%bfilterlength); case 10: hashval[9]=
* (int)(JSHash(mac)%bfilterlength); case 9: hashval[8]=
* (int)(PJWHash(mac)%bfilterlength); case 8: hashval[7]=
* (int)(ELFHash(mac)%bfilterlength); case 7: hashval[6]=
* (int)(BKDRHash(mac)%bfilterlength); case 6: hashval[5]=
* (int)(DJBHash(mac)%bfilterlength); case 5: hashval[4]=
* (int)(DEKHash(mac)%bfilterlength); case 4: hashval[3]=
* (int)(BPHash(mac)%bfilterlength); case 3: hashval[2]=
* (int)(FNVHash(mac)%bfilterlength); case 2: hashval[1]=
* (int)(SDBMHash(mac)%bfilterlength); case 1: hashval[0]=
* (int)(APHash(mac)%bfilterlength); break; } return hashval; } void
* ExchangeBF(Device dtemp, Device dtemp2,int path_length,LinkedList
* tabdevList){ int size1 = dtemp.bloom[0].size(); int size2=
* dtemp2.bloom[0].size(); for (int i=0;i<path_length-1;i++){ for(int j=0;j<size1;j++){
* if(dtemp.bloom[i+1].get(j).proximity<dtemp2.bloom[i].get(j).proximity)
* dtemp.bloom[i+1].set(j, new
* BloomValue(tabdevList.indexOf(dtemp2.mac),dtemp2.bloom[i].get(j).proximity)); }
* for(int j=0;j<size2;j++){ if(dtemp2.bloom[i+1].get(j).proximity<dtemp.bloom[i].get(j).proximity)
* dtemp2.bloom[i+1].set(j, new
* BloomValue(tabdevList.indexOf(dtemp.mac),dtemp.bloom[i].get(j).proximity)); } } }
* public void AttenuateBF(Device dtemp, int path_len){ int
* size=dtemp.bloom[0].size(); for(int i=0;i<path_len-1;i++){ for(int j=i+1;j<path_len;j++){
* for(int k=0;k<size;k++){
* if(dtemp.bloom[i].get(k).proximity>dtemp.bloom[j].get(k).proximity)
* dtemp.bloom[j].set(k, dtemp.bloom[i].get(k)); } } } } void
* AdjustBloomFilter(float val,Device dtemp,Device dtemp2,int path_length,int
* optBFlen, LinkedList tabdevList){ /*int deslen= (int)Math.pow(2, optBFlen);
* for(int j=0;j<path_length;j++){ if(dtemp.bloom[j].size()<deslen) {
* for(int i=dtemp.bloom[j].size();i<deslen;i++) dtemp.bloom[j].add(new
* BloomValue(-1,0)); } int size1=dtemp.bloom[j].size(); int
* size2=dtemp2.bloom[j].size(); if(size2>size1) { for(double i=size1;i<size2;i+=1)
* dtemp.bloom[j].add(new BloomValue(-1,0)); } if(size2<size1){ for(double
* i=size2;i<size1;i+=1) dtemp2.bloom[j].add(new BloomValue(-1,0)); } }
* UpdateVal(dtemp,dtemp2,10/val,tabdevList);
* UpdateVal(dtemp2,dtemp,10/val,tabdevList);
* ExchangeBF(dtemp,dtemp2,path_length); AttenuateBF(dtemp,path_length);
* AttenuateBF(dtemp2,path_length);/ }
*/
public static double getBvalue(MeetingStats ms) {
double avgwtime = ms.waitTime / ms.meetingcnt;
if (avgwtime > 8000)
return 0;
return (1 / (double) Math.log(avgwtime + 1.1));// *Math.log((ms.meetingcnt+0.718281828459045))*Math.log(ms.duration);
}
public static double normalisingfact(Device dtemp2) {
Enumeration denum2 = dtemp2.meetStat.keys();
double total = 0;
while (denum2.hasMoreElements())
total += dtemp2.meetStat.get(denum2.nextElement()).meetingcnt;
return total;
}
public void UpdateVal(MeetingStats ms, Device dtemp2, int path_length,
int bfilterlength, LinkedList tabdevList) {
MeetingStats ms2;
double total = normalisingfact(dtemp2);
Enumeration denum2 = dtemp2.meetStat.keys();
while (denum2.hasMoreElements()) {
String mac = (String) denum2.nextElement();
ms2 = dtemp2.meetStat.get(mac);
/*
* if(ms2.meetingcnt==1) continue;
*/
// double value = getBvalue(ms2);
double value = ms2.meetingcnt / total;
}
/*
* if(ms.getval((int)(RSHash(mac)%bfilterlength))<value)
* ms.insertval((int)(RSHash(mac)%bfilterlength),0,value);
*/
/*
* if(value==0) continue; if(ms.getval((int)(JSHash(mac)%bfilterlength))<value)
* ms.insertval((int)(JSHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(PJWHash(mac)%bfilterlength))<value)
* ms.insertval((int)(PJWHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(ELFHash(mac)%bfilterlength))<value)
* ms.insertval((int)(ELFHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(BKDRHash(mac)%bfilterlength))<value)
* ms.insertval((int)(BKDRHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(SDBMHash(mac)%bfilterlength))<value)
* ms.insertval((int)(SDBMHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(DJBHash(mac)%bfilterlength))<value)
* ms.insertval((int)(DJBHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(DEKHash(mac)%bfilterlength))<value)
* ms.insertval((int)(DEKHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(BPHash(mac)%bfilterlength))<value)
* ms.insertval((int)(BPHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(FNVHash(mac)%bfilterlength))<value)
* ms.insertval((int)(FNVHash(mac)%bfilterlength),1,value);
* if(ms.getval((int)(APHash(mac)%bfilterlength))<value)
* ms.insertval((int)(APHash(mac)%bfilterlength),1,value); }
* /////////////////////////////////////////////////////////////// /*int
* bfilterlength = dtemp.mstat.get(dtemp2.mac).bloom[0].length; MeetingStats
* ms,ms2; ms = dtemp.mstat.get(dtemp2.mac); Enumeration denum2 =
* dtemp2.mstat.keys(); while(denum2.hasMoreElements()){ String mac =
* (String)denum2.nextElement(); ms2 = dtemp2.mstat.get(mac);
* if(ms2.meetingcnt<2) continue; if(ms2.waitTime==0) ms2.waitTime++; float
* value=0; /*int j = ms2.waitingtime.length>ms2.meetingcnt ?
* ms2.meetingcnt:ms2.waitingtime.length; for(int i=0;i<j;i++) value +=
* ms2.waitingtime[i]; value /=j;
*/
/*
* value = (float)(1/(ms2.waitTime/ms2.meetingcnt));//' +
* (float)(0.0001*ms2.duration/ms2.meetingcnt); if(value>5) value=value+1-1;
*/
/*
* if(ms.bloom[0][(int)(RSHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(RSHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(JSHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(JSHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(PJWHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(PJWHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(ELFHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(ELFHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(BKDRHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(BKDRHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(DJBHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(DJBHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(DEKHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(DEKHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(BPHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(BPHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(FNVHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(FNVHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(SDBMHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(SDBMHash(mac)%bfilterlength)] =value;
* if(ms.bloom[0][(int)(APHash(mac)%bfilterlength)]<value)
* ms.bloom[0][(int)(APHash(mac)%bfilterlength)] =value; } denum2 =
* dtemp2.mstat.keys(); while(denum2.hasMoreElements()){ ms2 =
* dtemp2.mstat.get(denum2.nextElement()); for(int i=1;i<path_length;i++){
* for(int k=0;k<bfilterlength;k++){ if( ms.bloom[i][k]<ms2.bloom[i-1][k])
* ms.bloom[i][k]=ms2.bloom[i-1][k] ; } for(int k=0;k<bfilterlength;k++){
* if( ms.bloom[i][k]<ms.bloom[i-1][k]) ms.bloom[i][k]=ms.bloom[i-1][k] ; } } }
*/
}
public int[] GetHash(int bfilterlength, String mac) {
int[] hashval = new int[11];
hashval[10] = (int) (RSHash(mac) % bfilterlength);
hashval[9] = (int) (JSHash(mac) % bfilterlength);
hashval[8] = (int) (PJWHash(mac) % bfilterlength);
hashval[7] = (int) (ELFHash(mac) % bfilterlength);
hashval[6] = (int) (BKDRHash(mac) % bfilterlength);
hashval[5] = (int) (SDBMHash(mac) % bfilterlength);
hashval[4] = (int) (DJBHash(mac) % bfilterlength);
hashval[3] = (int) (DEKHash(mac) % bfilterlength);
hashval[2] = (int) (BPHash(mac) % bfilterlength);
hashval[1] = (int) (FNVHash(mac) % bfilterlength);
hashval[0] = (int) (APHash(mac) % bfilterlength);
return hashval;
}
}
| 38.543641 | 121 | 0.619371 |
1e4b32590691008258240bda0af875198bd4c592 | 5,130 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.lang.xpath.xslt.validation.inspections;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.lang.LanguageNamesValidation;
import com.intellij.lang.refactoring.NamesValidator;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.XmlElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.intellij.lang.xpath.XPathFileType;
import org.intellij.lang.xpath.xslt.XsltSupport;
import org.intellij.lang.xpath.xslt.psi.XsltElementFactory;
import org.intellij.lang.xpath.xslt.psi.XsltNamedElement;
import org.intellij.lang.xpath.xslt.psi.XsltTemplate;
import org.intellij.lang.xpath.xslt.validation.DeclarationChecker;
import org.jetbrains.annotations.NotNull;
public class XsltDeclarationInspection extends XsltInspection {
private XsltElementFactory myXsltElementFactory;
private NamesValidator myNamesValidator;
@Override
@NotNull
public String getDisplayName() {
return "Declaration Problems";
}
@Override
@NotNull
public String getShortName() {
return "XsltDeclarations";
}
@Override
@NotNull
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.ERROR;
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
if (!(holder.getFile() instanceof XmlFile)) return PsiElementVisitor.EMPTY_VISITOR;
return new XmlElementVisitor() {
@Override
public void visitXmlTag(final XmlTag tag) {
final XmlAttribute nameAttr = tag.getAttribute("name", null);
if (nameAttr == null || PsiTreeUtil.hasErrorElements(nameAttr)) return;
if (XsltSupport.isVariableOrParam(tag)) {
final XsltNamedElement instance = getXsltElementFactory().wrapElement(tag, XsltNamedElement.class);
checkDeclaration(instance, nameAttr.getValue(), holder);
} else if (XsltSupport.isTemplate(tag)) {
final XsltTemplate tmpl = getXsltElementFactory().wrapElement(tag, XsltTemplate.class);
checkDeclaration(tmpl, nameAttr.getValue(), holder);
}
}
private void checkDeclaration(final XsltNamedElement element, final String name, ProblemsHolder holder) {
final XmlTag tag = element.getTag();
final PsiElement token = element.getNameIdentifier();
if (name == null || name.length() == 0) {
if (token != null) {
holder.registerProblem(token, "Empty name not permitted");
} else {
final XmlAttribute attribute = element.getNameAttribute();
if (attribute != null) {
final XmlAttributeValue e = attribute.getValueElement();
if (e != null) {
holder.registerProblem(e, "Empty name not permitted");
}
}
}
} else if (!isLegalName(name, holder.getManager().getProject())) {
assert token != null;
holder.registerProblem(token, "Illegal name");
} else {
assert token != null;
final XmlFile file = (XmlFile)tag.getContainingFile();
final XmlTag duplicatedSymbol = DeclarationChecker.getInstance(file).getDuplicatedSymbol(tag);
if (duplicatedSymbol != null) {
if (duplicatedSymbol.getContainingFile() == file) {
holder.registerProblem(token, "Duplicate declaration");
} else {
holder.registerProblem(token, "Duplicates declaration from '" + duplicatedSymbol.getContainingFile().getName() + "'");
}
}
}
}
private boolean isLegalName(String value, Project project) {
return getNamesValidator().isIdentifier(value, project);
}
};
}
public XsltElementFactory getXsltElementFactory() {
if (myXsltElementFactory == null) {
myXsltElementFactory = XsltElementFactory.getInstance();
}
return myXsltElementFactory;
}
public NamesValidator getNamesValidator() {
if (myNamesValidator == null) {
myNamesValidator = LanguageNamesValidation.INSTANCE.forLanguage(XPathFileType.XPATH.getLanguage());
}
return myNamesValidator;
}
} | 43.474576 | 142 | 0.633138 |
2b900bffd9d94e3dbc3268bf2abb2993efe7e1c4 | 356 | package net.savantly.coach.repository;
import net.savantly.coach.domain.Upload;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Upload entity.
*/
@SuppressWarnings("unused")
@Repository
public interface UploadRepository extends JpaRepository<Upload, Long> {
}
| 22.25 | 71 | 0.794944 |
196986cfea452413ce8f8e9ae3322c49e80d90f9 | 1,460 | /**
* Copyright (c) 2014 SQUARESPACE, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squarespace.less.model;
/**
* Identifies the type of each node in the system.
*/
public enum NodeType {
ALPHA,
ANONYMOUS,
ARGUMENT,
ASSIGNMENT,
ATTRIBUTE_ELEMENT,
BLOCK,
BLOCK_DIRECTIVE,
COLOR,
COMBINATOR,
COMMENT,
COMPOSITE_PROPERTY,
CONDITION,
DEFINITION,
DETACHED_RULESET,
DIMENSION,
DIRECTIVE,
DUMMY,
EXPRESSION,
EXPRESSION_LIST,
EXTEND,
EXTEND_LIST,
FALSE,
FEATURE,
FEATURES,
FUNCTION_CALL,
GENERIC_BLOCK,
GUARD,
IMPORT,
IMPORT_MARKER,
KEYWORD,
MEDIA,
MIXIN,
MIXIN_ARGS,
MIXIN_CALL,
MIXIN_MARKER,
MIXIN_PARAMS,
OPERATION,
PARAMETER,
PAREN,
PARSE_ERROR,
PROPERTY,
QUOTED,
RATIO,
RULE,
RULESET,
SELECTOR,
SELECTORS,
SHORTHAND,
STYLESHEET,
TEXT_ELEMENT,
TRUE,
UNICODE_RANGE,
URL,
VALUE_ELEMENT,
VARIABLE,
WILDCARD_ELEMENT;
}
| 17.590361 | 75 | 0.711644 |
6d4515d61269bf8ddec3f1202da4d77089a6ddb7 | 726 | package com.devtty.neb27k;
/**
* Constants used in several parts of the application
*
* @author Denis
*/
public class Constants {
public final static String RB27 = "RB27";
public final static String CHANGES = "changes";
public final static String LAST_TWEET = "lasttweet";
public final static String NO_CHANGES = "Keine Nachrichten verfügbar.";
public final static String CSS_SEARCH_NEWS = ".news";
public final static String CSS_SEARCH_WARNING = ".achtung";
public final static String URL_MAIN = "http://www.neb.de/";
public final static String URL_CHANGES = "http://www.neb.de/service/baustellenfahrplanaenderungen/";
public final static int PAGING_OFFSET = 1;
}
| 31.565217 | 104 | 0.706612 |
b29fce23b188a3187e961c9e2d5285bbc6ac5346 | 3,154 | package org.cyy.fw.android.dborm;
import java.util.HashMap;
import java.util.Map;
/**
*
* O-R map information<BR>
*
* @author cyy
* @version [V1.0, 2012-11-5]
*/
public class ORMapInfo {
/**
*
* relation info<BR>
*
* @author cyy
* @version [V1.0, 2012-11-17]
*/
public static class AssociateInfo {
private String field;
private String sourceField;
private Class<?> target;
private String targetField;
public String getField() {
return field;
}
public String getSourceField() {
return sourceField;
}
public Class<?> getTarget() {
return target;
}
public String getTargetField() {
return targetField;
}
public void setField(String field) {
this.field = field;
}
public void setSourceField(String sourceField) {
this.sourceField = sourceField;
}
public void setTarget(Class<?> target) {
this.target = target;
}
public void setTargetField(String targetField) {
this.targetField = targetField;
}
}
/**
* relation info
*/
private Map<Class<?>, AssociateInfo> associateInfo = new HashMap<Class<?>, AssociateInfo>();
/**
* Class
*/
private Class<?> clazz;
/**
*
* table column->class attribute mappings
*/
private Map<String, String> columnFieldMap = new HashMap<String, String>();
/**
* class attribute->table column mappings
*/
private Map<String, String> fieldColumnMap = new HashMap<String, String>();
/**
* Primary key generated by framework
*/
private boolean genUIDBySelf;
/**
* auto-increment primary key
*/
private boolean pkSequence;
private String primaryKeyColumn;
private String primaryKeyField;
private String tableName;
public Map<Class<?>, AssociateInfo> getAssociateInfo() {
return associateInfo;
}
public Class<?> getClazz() {
return clazz;
}
public Map<String, String> getColumnFieldMap() {
return columnFieldMap;
}
public Map<String, String> getFieldColumnMap() {
return fieldColumnMap;
}
public String getPrimaryKeyColumn() {
return primaryKeyColumn;
}
public String getPrimaryKeyField() {
return primaryKeyField;
}
public String getTableName() {
return tableName;
}
public boolean isGenUIDBySelf() {
return genUIDBySelf;
}
public boolean isPkSequence() {
return pkSequence;
}
public void setAssociateInfo(Map<Class<?>, AssociateInfo> associateInfo) {
this.associateInfo = associateInfo;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
public void setColumnFieldMap(Map<String, String> columnFieldMap) {
this.columnFieldMap = columnFieldMap;
}
public void setFieldColumnMap(Map<String, String> columnMap) {
this.fieldColumnMap = columnMap;
}
public void setGenUIDBySelf(boolean genUIDBySelf) {
this.genUIDBySelf = genUIDBySelf;
}
public void setPkSequence(boolean pkSequence) {
this.pkSequence = pkSequence;
}
public void setPrimaryKeyColumn(String primaryKeyColumn) {
this.primaryKeyColumn = primaryKeyColumn;
}
public void setPrimaryKeyField(String primaryKeyField) {
this.primaryKeyField = primaryKeyField;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
| 19 | 93 | 0.704819 |
df2c16652360871121fc30312abc9aff8cfd285d | 10,394 | package com.nmpa.nmpaapp.modules.office;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.nmpa.nmpaapp.R;
import com.nmpa.nmpaapp.base.BaseActivity;
public class MapForOfficeActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "MapForOfficeActivity";
private MapView mMapView;
private BaiduMap mBaiduMap;
public LocationClient mLocClient = null;
private MyLocationListener myListener = new MyLocationListener();
boolean isFirstLoc = true; // 是否首次定位
private double mLatitude;
private double mLongitude;
private String mAddress;
private void initMap() {
mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding),
0x0f1679b3, 0xAA00FF00));
// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
option.setOpenGps(true); // 打开gps
option.setIsNeedAddress(true);
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(3000);
mLocClient.setLocOption(option);
mLocClient.start();
}
@Override
public void onBeforeSetContentView() {
}
@Override
public int getLayoutResID() {
return R.layout.activity_map_for_office;
}
@Override
public void initContentView(@Nullable Bundle savedInstanceState) {
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
mLatitude = getIntent().getDoubleExtra("latitude", 0.0f);
mLongitude = getIntent().getDoubleExtra("longitude", 0.0f);
mAddress = getIntent().getStringExtra("address");
Log.e(TAG,"mAddress="+mAddress);
if (mAddress != null && !mAddress.equals("")) {
initSearch();
}
initView();
initMap();
}
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
String province = location.getProvince(); //获取省份
String city = location.getCity(); //获取城市
String district = location.getDistrict(); //获取区县
String street = location.getStreet(); //获取街道信息
mAddress = province + city + district + street;
//获取纬度信息
// mLatitude = location.getLatitude();
// //获取经度信息
// mLongitude = location.getLongitude();
Log.d("flag", "onReceiveLocation: " + mLatitude + ":" + mLongitude);
if(mLatitude == 0.0 && mLongitude == 0.0) {
MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection())
// .direction(100)
.latitude(location.getLatitude()).longitude(location.getLongitude())
.build();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
mBaiduMap.setMyLocationData(locData);
} else {
MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection())
.latitude(mLatitude).longitude(mLongitude)
.build();
mBaiduMap.setMyLocationData(locData);
}
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(mLatitude, mLongitude);
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
// 当不需要定位图层时关闭定位图层
// mBaiduMap.setMyLocationEnabled(false);
}
}
private void initView() {
TextView title = findViewById(R.id.title);
title.setText("地图");
LinearLayout back = findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
TextView type_normal = findViewById(R.id.type_normal);
TextView type_satellite = findViewById(R.id.type_satellite);
TextView map_position = findViewById(R.id.map_position);
TextView confirm = findViewById(R.id.confirm);
type_normal.setOnClickListener(this);
type_satellite.setOnClickListener(this);
map_position.setOnClickListener(this);
confirm.setOnClickListener(this);
mMapView = findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Log.e(TAG, "onMapClick latitude: "+latLng.latitude );//经度
}
@Override
public void onMapPoiClick(MapPoi mapPoi) {
Log.e(TAG, "onMapPoiClick latitude: "+mapPoi.getName()+","+mapPoi.getPosition()+","+mapPoi.getUid() );//经度
LatLng latLng = mapPoi.getPosition();
setMarkPoint(latLng.latitude,latLng.longitude);
mLatitude = latLng.latitude;
mLongitude = latLng.longitude;
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.type_normal:
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
break;
case R.id.type_satellite:
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
break;
case R.id.map_position:
mLocClient.start();
break;
case R.id.confirm:
Intent intent = new Intent();
intent.putExtra("latitude", mLatitude);
intent.putExtra("longitude", mLongitude);
intent.putExtra("address", mAddress);
Log.d("flag", "onClick: "+mLatitude+":"+mLongitude+":"+mAddress);
setResult(RESULT_OK, intent);
finish();
break;
}
}
LatLng point;
private void setMarkPoint(double jingdu,double weidu) {
//定义Maker坐标点
mBaiduMap.clear();
point = new LatLng(jingdu, weidu);
//构建Marker图标
BitmapDescriptor bitmap = BitmapDescriptorFactory
.fromResource(R.mipmap.icon_gcoding);
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(point)
.icon(bitmap);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
GeoCoder mSearch;
private void initSearch() {
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
@Override
public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
Log.e(TAG, "onGetGeoCodeResult latitude: "+geoCodeResult.getLocation() );//经度
LatLng latLng = geoCodeResult.getLocation();
if (latLng != null) {
mLatitude = latLng.latitude;
mLongitude = latLng.longitude;
}
isFirstLoc = true;
// setMarkPoint(mLatitude, mLongitude);
// mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(geoCodeResult
// .getLocation()));
// mLocClient.start();
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
Log.e(TAG, "onGetReverseGeoCodeResult latitude: "+reverseGeoCodeResult.getLocation() );//经度
}
});
mSearch.geocode(new GeoCodeOption().city(mAddress).address(mAddress));
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mLocClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
}
}
| 38.213235 | 127 | 0.621128 |
1d773ff6e66b586459b69cb191f6a2cd1b6cbdae | 762 | /* Copyright (c) 2007-2014 MIT 6.005 course staff, all rights reserved.
* Redistribution of original or derived work requires permission of course staff.
*/
package turtle;
/**
* Represents a drawable turtle action.
*/
public class Action {
ActionType type;
String displayString;
LineSegment lineSeg;
public Action(ActionType type, String displayString, LineSegment lineSeg) {
this.type = type;
this.displayString = displayString;
this.lineSeg = lineSeg;
}
public String toString() {
if (displayString == null) {
return "";
} else {
return displayString;
}
}
}
/**
* Enumeration of turtle action types.
*/
enum ActionType {
FORWARD, TURN, COLOR
}
| 21.166667 | 82 | 0.635171 |
116965adbd1f818042826748b9383eed7a1352e8 | 3,708 | /*
* Copyright 2004-2010 Information & Software Engineering Group (188/1)
* Institute of Software Technology and Interactive Systems
* Vienna University of Technology, Austria
*
* 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.ifs.tuwien.ac.at/dm/somtoolbox/license.html
*
* 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 at.tuwien.ifs.somtoolbox.apps.helper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import com.martiansoftware.jsap.JSAPResult;
import at.tuwien.ifs.somtoolbox.apps.config.OptionFactory;
import at.tuwien.ifs.somtoolbox.util.FileUtils;
import at.tuwien.ifs.somtoolbox.util.StringUtils;
/**
* Chops a vector file down to the instance names provided in a separate file.
*
* @author Rudolf Mayer
* @version $Id: VectorFileChopper.java 3589 2010-05-21 10:42:01Z mayer $
*/
public class VectorFileChopper {
public static void main(String[] args) throws IOException {
// register and parse all options
JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_VECTORFILE_CHOPPER);
String inputFileName = config.getString("input");
String keepFile = config.getString("keepFile");
String outputFileName = config.getString("output");
boolean gzip = false; // TODO: make parameter
ArrayList<String> keepInputs = FileUtils.readLinesAsList(keepFile);
ArrayList<String> missingInputs = new ArrayList<String>(keepInputs);
ArrayList<String> lines = new ArrayList<String>();
int keptInputsCounter = 0;
int lineCounter = 1;
BufferedReader br = FileUtils.openFile("Input vector", inputFileName);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("$")) {
lines.add(line);
} else {
String[] lineElements = line.split(StringUtils.REGEX_SPACE_OR_TAB);
String label = lineElements[lineElements.length - 1];
if (keepInputs.contains(label)) {
lines.add(line);
keptInputsCounter++;
missingInputs.remove(label);
} else {
// System.out.println("Skipping input " + label);
}
}
System.out.print("\rReading line " + lineCounter);
lineCounter++;
}
System.out.println("... finished!");
System.out.println("Kept " + keptInputsCounter + " input vectors.");
if (missingInputs.size() > 0) {
System.out.println("\tDid not find the following inputs supposed to keep: " + missingInputs);
} else {
System.out.println("\tFound all inputs supposed to keep");
}
System.out.println("Writing to " + outputFileName);
PrintWriter pw = FileUtils.openFileForWriting("Vector file", outputFileName, gzip);
for (String string : lines) {
if (string.trim().startsWith("$XDIM")) {
pw.println("$XDIM " + keptInputsCounter);
} else {
pw.println(string);
}
}
br.close();
pw.close();
}
}
| 37.836735 | 105 | 0.631607 |
6862698951bac2c7c6a9b823debef722f2f4c254 | 292 | package vswe.stevescarts.Modules.Addons;
import vswe.stevescarts.Carts.MinecartModular;
public class ModuleSmelterAdv extends ModuleSmelter {
public ModuleSmelterAdv(MinecartModular cart) {
super(cart);
}
@Override
protected boolean canUseAdvancedFeatures() {
return true;
}
}
| 17.176471 | 53 | 0.784247 |
30d449a3c6209a903141b01997ef03cb6cec445e | 9,287 | /*
* BSD 3-Clause License - imaJe
*
* Copyright (c) 2016, Michael Ludwig
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.lhkbob.imaje.color.icc.reader;
import com.lhkbob.imaje.color.icc.GenericColorValue;
import com.lhkbob.imaje.color.icc.Signature;
import java.nio.ByteBuffer;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
/**
* FIXME update this to use Bytes and other data types as necessary
*/
public final class ICCDataTypeUtil {
public static class PositionNumber {
private final long offset;
private final long size;
public PositionNumber(long offset, long size) {
this.offset = offset;
this.size = size;
}
public void configureBuffer(ByteBuffer data, int start) {
data.limit(Math.toIntExact(start + offset + size));
data.position(Math.toIntExact(start + offset));
}
public long getOffset() {
return offset;
}
public long getSize() {
return size;
}
}
private ICCDataTypeUtil() {}
// FIXME write unit tests for this one
public static String nextASCIIString(ByteBuffer data, int maxStringLength) {
if (maxStringLength >= 0) {
require(data, maxStringLength);
}
StringBuilder sb = new StringBuilder();
int i = 1;
char c;
while ((maxStringLength < 0 || i < maxStringLength) && (c = (char) data.get()) != '\0') {
sb.append(c);
i++;
}
if (maxStringLength >= 0) {
// If a maximum number of bytes is provided then this is a string within a fixed-length
// byte field so advance to the end of the field even if the null character was found
// before the limit was reached.
skip(data, maxStringLength - i);
}
return sb.toString();
}
public static ZonedDateTime nextDateTimeNumber(ByteBuffer data) {
require(data, 12);
int year = nextUInt16Number(data);
int month = nextUInt16Number(data); // 1 - 12
int dom = nextUInt16Number(data); // 1 - 31
int hours = nextUInt16Number(data); // 0 - 23
int minutes = nextUInt16Number(data);
int seconds = nextUInt16Number(data);
return ZonedDateTime.of(year, month, dom, hours, minutes, seconds, 0, ZoneOffset.UTC);
}
public static double nextFloat32Number(ByteBuffer data) {
// This should not include NaNs, infinities, and un-normalized numbers but
// otherwise follows IEEE 754 so we can just use this when interpreting the data.
require(data, 4);
return Float.intBitsToFloat((int) nextUInt32Number(data));
}
public static GenericColorValue nextLABNumber16(ByteBuffer data) {
require(data, 6);
double l = 100.0 * nextUInt16Number(data) / 65535.0;
double a = nextUInt16Number(data) / 257.0 - 128.0;
double b = nextUInt16Number(data) / 257.0 - 128.0;
return GenericColorValue.pcsLAB(l, a, b);
}
public static GenericColorValue nextLABNumber8(ByteBuffer data) {
require(data, 3);
double l = 100.0 * nextUInt8Number(data) / 255.0;
double a = nextUInt8Number(data) - 128.0;
double b = nextUInt8Number(data) - 128.0;
return GenericColorValue.pcsLAB(l, a, b);
}
public static GenericColorValue nextLABNumberFloat(ByteBuffer data) {
return nextPCSNumberFloat(data, true);
}
public static GenericColorValue nextLABNumberLegacy16(ByteBuffer data) {
require(data, 6);
double l = 100.0f * data.get() / 255.0 + data.get() / 652.80;
double a = nextU8Fixed8Number(data) - 128.0;
double b = nextU8Fixed8Number(data) - 128.0;
return GenericColorValue.pcsLAB(l, a, b);
}
public static PositionNumber nextPositionNumber(ByteBuffer data) {
require(data, 8);
long offset = nextUInt32Number(data);
long length = nextUInt32Number(data);
return new PositionNumber(offset, length);
}
public static double nextS15Fixed16Number(ByteBuffer data) {
// Don't mask out the first byte since it contains the sign bit and we want
// to preserve that.
require(data, 4);
int signedInt = (data.get() << 8) | (0xff & data.get());
double fraction = nextUInt16Number(data) / 65536.0;
return signedInt + fraction;
}
public static Signature nextSignature(ByteBuffer data) {
return Signature.fromBitField(nextUInt32Number(data));
}
public static double nextU16Fixed16Number(ByteBuffer data) {
require(data, 4);
int unsignedInt = nextUInt16Number(data);
double fraction = nextUInt16Number(data) / 65536.0;
return unsignedInt + fraction;
}
public static double nextU1Fixed15Number(ByteBuffer data) {
require(data, 2);
int bitField = nextUInt16Number(data);
int integer = ((bitField & 0x8000) == 0 ? 0 : 1);
double fraction = (bitField & 0x7fff) / 32768.0;
return integer + fraction;
}
public static double nextU8Fixed8Number(ByteBuffer data) {
require(data, 2);
int integer = (0xff & data.get());
double fraction = (0xff & data.get()) / 256.0;
return integer + fraction;
}
public static int nextUInt16Number(ByteBuffer data) {
require(data, 2);
return ((0xff & data.get()) << 8) | (0xff & data.get());
}
public static long nextUInt32Number(ByteBuffer data) {
require(data, 4);
return ((0xffL & data.get()) << 24) | ((0xffL & data.get()) << 16) | ((0xffL & data.get()) << 8)
| (0xffL & data.get());
}
public static long nextUInt64Number(ByteBuffer data) {
require(data, 8);
return ((0xffL & data.get()) << 56) | ((0xffL & data.get()) << 48) | ((0xffL & data.get())
<< 40) | ((0xffL & data.get()) << 32) | ((0xffL & data.get()) << 24) | ((0xffL & data.get())
<< 16) | ((0xffL & data.get()) << 8) | (0xffL & data.get());
}
public static int nextUInt8Number(ByteBuffer data) {
require(data, 1);
return (0xff & data.get());
}
public static GenericColorValue nextXYZNumber(ByteBuffer data, GenericColorValue.ColorType type) {
require(data, 12);
double x = nextS15Fixed16Number(data);
double y = nextS15Fixed16Number(data);
double z = nextS15Fixed16Number(data);
switch (type) {
case CIEXYZ:
return GenericColorValue.cieXYZ(x, y, z);
case NORMALIZED_CIEXYZ:
return GenericColorValue.nCIEXYZ(x, y, z);
case PCSXYZ:
return GenericColorValue.pcsXYZ(x, y, z);
default:
throw new IllegalArgumentException("Not an XYZ color type: " + type);
}
}
public static GenericColorValue nextXYZNumber16(ByteBuffer data) {
require(data, 6);
double x = nextU1Fixed15Number(data);
double y = nextU1Fixed15Number(data);
double z = nextU1Fixed15Number(data);
return GenericColorValue.pcsXYZ(x, y, z);
}
// FIXME write unit tests for new XYZ and LAB number functions
public static GenericColorValue nextXYZNumberFloat(ByteBuffer data) {
return nextPCSNumberFloat(data, false);
}
public static void require(ByteBuffer data, int requireAmount) {
if (data.remaining() < requireAmount) {
throw new IllegalArgumentException(
"Requires " + requireAmount + " bytes to be available, but only has " + data.remaining());
}
}
public static void skip(ByteBuffer data, int skipAmount) {
data.position(data.position() + skipAmount);
}
public static void skipToBoundary(ByteBuffer data) {
int remainder = data.position() % 4;
// If remainder is 0 we don't want to skip ahead another 4 bytes
// since we are already at a 4byte boundary
if (remainder > 0) {
skip(data, 4 - remainder);
}
}
private static GenericColorValue nextPCSNumberFloat(ByteBuffer data, boolean lab) {
require(data, 12);
double c1 = nextFloat32Number(data);
double c2 = nextFloat32Number(data);
double c3 = nextFloat32Number(data);
return (lab ? GenericColorValue.pcsLAB(c1, c2, c3) : GenericColorValue.pcsXYZ(c1, c2, c3));
}
}
| 35.17803 | 100 | 0.686551 |
2fe0a764c196ca74f785e8ef699519cb66892201 | 3,281 | package com.thinkbiganalytics.oauth;
/*-
* #%L
* thinkbig-oauth-server
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.security.Principal;
/**
* Code used from:
* https://spring.io/blog/2015/02/03/sso-with-oauth2-angular-js-and-spring-security-part-v
*
* and from the 1.3 migration:
* https://spring.io/blog/2015/11/30/migrating-oauth2-apps-from-spring-boot-1-2-to-1-3
* TODO once implement change the client and secret
*/
@SpringBootApplication
@RestController
@EnableResourceServer
@EnableAuthorizationServer
public class DataLakeOauthServerApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DataLakeOauthServerApplication.class, args);
}
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("authorization_code", "refresh_token",
"password").scopes("openid");
}
}
}
| 37.712644 | 116 | 0.761353 |
ee45e2630b6194afdf271907a5d8e2b68b4212ab | 1,267 | //,temp,AbstractCamelContext.java,1654,1679,temp,AbstractCamelContext.java,1626,1652
//,2
public class xxx {
public String getLanguageParameterJsonSchema(String languageName) throws IOException {
// use the language factory finder to find the package name of the
// language class, which is the location
// where the documentation exists as well
FactoryFinder finder = getFactoryFinder(DefaultLanguageResolver.LANGUAGE_RESOURCE_PATH);
Class<?> clazz = finder.findClass(languageName).orElse(null);
if (clazz == null) {
return null;
}
String packageName = clazz.getPackage().getName();
packageName = packageName.replace('.', '/');
String path = packageName + "/" + languageName + ".json";
ClassResolver resolver = getClassResolver();
InputStream inputStream = resolver.loadResourceAsStream(path);
LOG.debug("Loading language JSON Schema for: {} using class resolver: {} -> {}", languageName, resolver, inputStream);
if (inputStream != null) {
try {
return IOHelper.loadText(inputStream);
} finally {
IOHelper.close(inputStream);
}
}
return null;
}
}; | 40.870968 | 126 | 0.633781 |
c527d4f4456b7dff3cb2a6bf201f197688c83654 | 3,331 | /*
* Copyright 2014,2016 agwlvssainokuni
*
* 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 cherry.fundamental.navi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cherry.fundamental.navi.Navigator.Node;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/appctx-fundamental-test.xml")
public class NavigatorImplTest {
@Autowired
private ObjectMapper objectMapper;
@Test
public void testEmptyDef() throws IOException {
Navigator navigator = create("{}");
List<Node> list = navigator.navigate("aa");
assertTrue(list.isEmpty());
}
@Test
public void testSingleNode() throws IOException {
Navigator navigator = create("{\"name\":\"1\",\"uri\":\"uri/1\"}");
List<Node> list = navigator.navigate("1");
assertEquals(1, list.size());
int i = 1;
for (Node node : list) {
assertEquals(String.valueOf(i), node.getName());
assertEquals("uri/" + i, node.getUri());
assertTrue(node.isLast());
assertEquals("Navigator.Node[name=" + i + ",uri=uri/" + i + ",last=true]", node.toString());
i += 1;
}
}
@Test
public void testHierNode() throws IOException {
Navigator navigator = create("{\"name\":\"1\",\"uri\":\"uri/1\",\"children\":[{\"name\":\"2\",\"uri\":\"uri/2\"}]}");
List<Node> list = navigator.navigate("2");
assertEquals(2, list.size());
int i = 1;
for (Node node : list) {
assertEquals(String.valueOf(i), node.getName());
assertEquals("uri/" + i, node.getUri());
if (i == 2) {
assertTrue(node.isLast());
} else {
assertFalse(node.isLast());
}
i += 1;
}
}
@Test
public void testMisc() {
NavigatorImpl.NaviNode node = new NavigatorImpl.NaviNode();
node.setName("A");
node.setUri("U");
node.setChildren(new ArrayList<NavigatorImpl.NaviNode>());
assertEquals("NavigatorImpl.NaviNode[name=A,uri=U,children=[]]", node.toString());
}
private Navigator create(String def) throws IOException {
NavigatorImpl impl = new NavigatorImpl();
impl.setObjectMapper(objectMapper);
impl.setNavigationDef(new ByteArrayResource(def.getBytes(StandardCharsets.UTF_8)));
impl.initialize();
return impl;
}
}
| 32.028846 | 120 | 0.695887 |
4a8b80cd18f0d46994a6a88fcd9aeafea6e3db7c | 321 | package ca.bc.gov.open.ecrc;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
@SpringBootTest
@TestPropertySource("classpath:application-test.properties")
class EcrcApiApplicationTests {
@Test
void contextLoads() {
}
}
| 20.0625 | 60 | 0.809969 |
bfd3c4827c15258fcfec209a6a19e7a15391b229 | 397 | package com.neulab.rein.skill;
import com.neulab.rein.player.Player;
import java.io.Serializable;
import java.util.List;
public interface Skill {
public void apply(Player caster, List<Player> targetPlayers);
public Boolean isAvailable(Player caster, List<Player> targetPlayers);
public Integer getSkillType();
public String getName();
public String getDisplayName();
}
| 19.85 | 74 | 0.748111 |
fd60df2d977920f196ac6139caa864d37a79def7 | 307 | package app.utilities;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InputParser {
public InputParser() {}
public List<String> parseInput(String inputLine) {
return new ArrayList<>(Arrays.asList(inputLine.split("\\s+")));
}
}
| 20.466667 | 72 | 0.667752 |
55cb4e7dc8ee6f4643715b1be9e0b6c501dec4b1 | 60,612 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.jenkins.kubernetes.wrapper;
import com.microsoft.jenkins.kubernetes.util.Constants;
import com.microsoft.jenkins.kubernetes.util.KubernetesJsonUtils;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.AutoscalingV1Api;
import io.kubernetes.client.openapi.apis.BatchV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.apis.NetworkingV1Api;
import io.kubernetes.client.openapi.apis.RbacAuthorizationV1Api;
import io.kubernetes.client.openapi.models.V1ClusterRole;
import io.kubernetes.client.openapi.models.V1ClusterRoleBinding;
import io.kubernetes.client.openapi.models.V1ConfigMap;
import io.kubernetes.client.openapi.models.V1DaemonSet;
import io.kubernetes.client.openapi.models.V1Deployment;
import io.kubernetes.client.openapi.models.V1HorizontalPodAutoscaler;
import io.kubernetes.client.openapi.models.V1Job;
import io.kubernetes.client.openapi.models.V1Namespace;
import io.kubernetes.client.openapi.models.V1NetworkPolicy;
import io.kubernetes.client.openapi.models.V1PersistentVolume;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodSpec;
import io.kubernetes.client.openapi.models.V1ReplicaSet;
import io.kubernetes.client.openapi.models.V1ReplicationController;
import io.kubernetes.client.openapi.models.V1Role;
import io.kubernetes.client.openapi.models.V1RoleBinding;
import io.kubernetes.client.openapi.models.V1Secret;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceAccount;
import io.kubernetes.client.openapi.models.V1ServicePort;
import io.kubernetes.client.openapi.models.V1StatefulSet;
import io.kubernetes.client.openapi.models.V1Status;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.microsoft.jenkins.kubernetes.util.Constants.DRY_RUN_ALL;
import static com.microsoft.jenkins.kubernetes.util.Constants.KUBERNETES_CONTROLLER_UID_FIELD;
import static com.microsoft.jenkins.kubernetes.util.Constants.KUBERNETES_JOB_NAME_FIELD;
public class V1ResourceManager extends ResourceManager {
private final CoreV1Api coreV1ApiInstance;
private final AppsV1Api appsV1ApiInstance;
private final BatchV1Api batchV1ApiInstance;
private final AutoscalingV1Api autoscalingV1Api;
private final NetworkingV1Api networkingV1Api;
private final RbacAuthorizationV1Api rbacV1Api;
private V1ResourceUpdateMonitor resourceUpdateMonitor = V1ResourceUpdateMonitor.NOOP;
public V1ResourceManager(ApiClient client) {
super(true);
checkNotNull(client);
coreV1ApiInstance = new CoreV1Api(client);
appsV1ApiInstance = new AppsV1Api(client);
batchV1ApiInstance = new BatchV1Api(client);
autoscalingV1Api = new AutoscalingV1Api(client);
networkingV1Api = new NetworkingV1Api(client);
rbacV1Api = new RbacAuthorizationV1Api(client);
}
public V1ResourceManager(ApiClient client, boolean pretty) {
super(pretty);
checkNotNull(client);
coreV1ApiInstance = new CoreV1Api(client);
appsV1ApiInstance = new AppsV1Api(client);
batchV1ApiInstance = new BatchV1Api(client);
autoscalingV1Api = new AutoscalingV1Api(client);
networkingV1Api = new NetworkingV1Api(client);
rbacV1Api = new RbacAuthorizationV1Api(client);
}
/**
* In the case of different image names, the default imagePullPolicy will be different.
* E.g. Nginx => Always Nginx:1.79 => IfNotPresent
* This method is used to mask the default value caused by dryRun.
*
* @param origin object in kubernetes cluster
* @param yaml user applied object
* @param target dryRun return object
*/
private static void recoverPodImagePullPolicy(V1PodSpec origin, V1PodSpec yaml, V1PodSpec target) {
if (origin.getInitContainers() != null) {
checkNotNull(yaml.getInitContainers());
checkNotNull(target.getInitContainers());
// should not change size
if (origin.getInitContainers().size() != yaml.getInitContainers().size()
|| origin.getInitContainers().size() != target.getInitContainers().size()) {
return;
}
for (int i = 0; i < origin.getInitContainers().size(); i++) {
if (StringUtils.isBlank(yaml.getInitContainers().get(i).getImagePullPolicy())) {
target.getInitContainers().get(i).imagePullPolicy(
origin.getInitContainers().get(i).getImagePullPolicy());
}
}
}
if (origin.getContainers() != null) {
checkNotNull(yaml.getContainers());
checkNotNull(target.getContainers());
// should not change size
if (origin.getContainers().size() != yaml.getContainers().size()
|| origin.getContainers().size() != target.getContainers().size()) {
return;
}
for (int i = 0; i < origin.getContainers().size(); i++) {
if (StringUtils.isBlank(yaml.getContainers().get(i).getImagePullPolicy())) {
target.getContainers().get(i).imagePullPolicy(
origin.getContainers().get(i).getImagePullPolicy());
}
}
}
return;
}
public V1ResourceUpdateMonitor getResourceUpdateMonitor() {
return resourceUpdateMonitor;
}
public V1ResourceManager withResourceUpdateMonitor(V1ResourceUpdateMonitor monitor) {
checkNotNull(monitor);
this.resourceUpdateMonitor = monitor;
return this;
}
class ReplicaSetUpdater extends ResourceUpdater<V1ReplicaSet> {
ReplicaSetUpdater(V1ReplicaSet rs) {
super(rs);
}
@Override
V1ReplicaSet getCurrentResource() {
V1ReplicaSet replicaSet = null;
try {
replicaSet = appsV1ApiInstance.readNamespacedReplicaSet(getName(), getNamespace(), getPretty(),
true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return replicaSet;
}
@Override
V1ReplicaSet applyResource(V1ReplicaSet original, V1ReplicaSet current) {
V1ReplicaSet replicaSet = null;
try {
replicaSet = appsV1ApiInstance.replaceNamespacedReplicaSet(getName(), getNamespace(), current,
getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return replicaSet;
}
@Override
V1ReplicaSet createResource(V1ReplicaSet current) {
V1ReplicaSet replicaSet = null;
try {
replicaSet = appsV1ApiInstance.createNamespacedReplicaSet(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return replicaSet;
}
@Override
V1Status deleteResource(V1ReplicaSet current) {
V1Status result = null;
try {
result = appsV1ApiInstance.deleteNamespacedReplicaSet(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ReplicaSet original, V1ReplicaSet current) {
resourceUpdateMonitor.onReplicaSetUpdate(original, current);
}
}
class DeploymentUpdater extends ResourceUpdater<V1Deployment> {
DeploymentUpdater(V1Deployment deployment) {
super(deployment);
}
@Override
V1Deployment getCurrentResource() {
V1Deployment deployment = null;
try {
deployment = appsV1ApiInstance.readNamespacedDeployment(getName(), getNamespace(), getPretty(),
true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return deployment;
}
@Override
V1Deployment applyResource(V1Deployment original, V1Deployment current) {
V1Deployment deployment = null;
try {
deployment = appsV1ApiInstance.replaceNamespacedDeployment(getName(), getNamespace(), current,
getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return deployment;
}
@Override
V1Deployment createResource(V1Deployment current) {
V1Deployment deployment = null;
try {
deployment = appsV1ApiInstance.createNamespacedDeployment(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return deployment;
}
@Override
V1Status deleteResource(V1Deployment current) {
V1Status result = null;
try {
result = appsV1ApiInstance.deleteNamespacedDeployment(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Deployment original, V1Deployment current) {
resourceUpdateMonitor.onDeploymentUpdate(original, current);
}
}
class DaemonSetUpdater extends ResourceUpdater<V1DaemonSet> {
DaemonSetUpdater(V1DaemonSet ds) {
super(ds);
}
@Override
V1DaemonSet getCurrentResource() {
V1DaemonSet daemonSet = null;
try {
daemonSet = appsV1ApiInstance.readNamespacedDaemonSet(getName(), getNamespace(), getPretty(),
true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return daemonSet;
}
@Override
V1DaemonSet applyResource(V1DaemonSet original, V1DaemonSet current) {
V1DaemonSet daemonSet = null;
try {
daemonSet = appsV1ApiInstance.replaceNamespacedDaemonSet(getName(), getNamespace(), current,
getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return daemonSet;
}
@Override
V1DaemonSet createResource(V1DaemonSet current) {
V1DaemonSet daemonSet = null;
try {
daemonSet = appsV1ApiInstance.createNamespacedDaemonSet(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return daemonSet;
}
@Override
V1Status deleteResource(V1DaemonSet current) {
V1Status result = null;
try {
result = appsV1ApiInstance.deleteNamespacedDaemonSet(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1DaemonSet original, V1DaemonSet current) {
resourceUpdateMonitor.onDaemonSetUpdate(original, current);
}
}
class ReplicationControllerUpdater extends ResourceUpdater<V1ReplicationController> {
ReplicationControllerUpdater(V1ReplicationController rc) {
super(rc);
}
@Override
V1ReplicationController getCurrentResource() {
V1ReplicationController replicationController = null;
try {
replicationController = coreV1ApiInstance.readNamespacedReplicationController(getName(),
getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return replicationController;
}
@Override
V1ReplicationController applyResource(V1ReplicationController original, V1ReplicationController current) {
V1ReplicationController replicationController = null;
try {
replicationController = coreV1ApiInstance.replaceNamespacedReplicationController(getName(),
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return replicationController;
}
@Override
V1ReplicationController createResource(V1ReplicationController current) {
V1ReplicationController replicationController = null;
try {
replicationController = coreV1ApiInstance.createNamespacedReplicationController(getNamespace(),
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return replicationController;
}
@Override
V1Status deleteResource(V1ReplicationController current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedReplicationController(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ReplicationController original, V1ReplicationController current) {
resourceUpdateMonitor.onReplicationControllerUpdate(original, current);
}
}
class ServiceUpdater extends ResourceUpdater<V1Service> {
ServiceUpdater(V1Service service) {
super(service);
}
@Override
V1Service getCurrentResource() {
V1Service service = null;
try {
service = coreV1ApiInstance.readNamespacedService(getName(), getNamespace(), getPretty(),
true, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return service;
}
@Override
V1Service applyResource(V1Service original, V1Service current) {
List<V1ServicePort> originalPorts = original.getSpec().getPorts();
List<V1ServicePort> currentPorts = current.getSpec().getPorts();
// Pin the nodePort to the public port
// The kubernetes-client library will compare the server config and the current applied config,
// and compute the difference, which will be sent to the PATCH API of Kubernetes. The missing nodePort
// will be considered as deletion, which will cause the Kubernetes to assign a new nodePort to the
// service, which may have problem with the port forwarding as in the load balancer.
//
// "kubectl apply" handles the service update in the same way.
if (originalPorts != null && currentPorts != null) {
Map<Integer, Integer> portToNodePort = new HashMap<>();
for (V1ServicePort servicePort : originalPorts) {
Integer port = servicePort.getPort();
Integer nodePort = servicePort.getNodePort();
if (port != null && nodePort != null) {
portToNodePort.put(servicePort.getPort(), servicePort.getNodePort());
}
}
for (V1ServicePort servicePort : currentPorts) {
// if the nodePort is defined in the config, use it
Integer currentNodePort = servicePort.getNodePort();
if (currentNodePort != null && currentNodePort != 0) {
continue;
}
// otherwise try to copy the nodePort from the current service status
Integer port = servicePort.getPort();
if (port != null) {
Integer nodePort = portToNodePort.get(port);
if (nodePort != null) {
servicePort.setNodePort(nodePort);
}
}
}
}
// this should be no-op, keep it in case current.getSpec().getPorts() behavior changes in future
current.getSpec().setPorts(currentPorts);
// update svc need to set resourceVersion
current.getMetadata().setResourceVersion(original.getMetadata().getResourceVersion());
// clusterIP is immutable, if the clusterIP is empty, it is set to the original clusterIP
if (StringUtils.isBlank(current.getSpec().getClusterIP())) {
current.getSpec().setClusterIP(original.getSpec().getClusterIP());
}
V1Service service = null;
try {
service = coreV1ApiInstance.replaceNamespacedService(getName(), getNamespace(),
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return service;
}
@Override
V1Service createResource(V1Service current) {
V1Service service = null;
try {
service = coreV1ApiInstance.createNamespacedService(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return service;
}
@Override
V1Status deleteResource(V1Service current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedService(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Service original, V1Service current) {
resourceUpdateMonitor.onServiceUpdate(original, current);
}
}
class JobUpdater extends ResourceUpdater<V1Job> {
JobUpdater(V1Job job) {
super(job);
}
@Override
V1Job getCurrentResource() {
V1Job job = null;
try {
job = batchV1ApiInstance.readNamespacedJob(getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return job;
}
@Override
V1Job applyResource(V1Job original, V1Job current) {
V1Job job = null;
V1Job putJob = getPutObject(original, current);
try {
job = batchV1ApiInstance.replaceNamespacedJob(
getName(), getNamespace(), putJob, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return job;
}
/**
* Get PutObject with server-dryRun.
* Only some of the fields in the job resource can be modified.
* Directly putting the original object of the user will cause some immutable
* fields with defaultValue to be modified.
* This method is a workaround that populates the default value with the server dryRun implementation.
* https://kubernetes.io/blog/2019/01/14/apiserver-dry-run-and-kubectl-diff/
*
* @param original Current Object in Cluster
* @param current Current object submitted by the user
* @return Job With Default Value
*/
V1Job getPutObject(V1Job original, V1Job current) {
// Clone Object to avoid modifications to the original object.
V1Job dryRunReq = KubernetesJsonUtils.getKubernetesJson().deserialize(
KubernetesJsonUtils.getKubernetesJson().serialize(current), V1Job.class);
// Build dryRun Request Object
V1Job dryRunRes = null;
dryRunReq.getMetadata().setName(null);
dryRunReq.getMetadata().setGenerateName(getName());
dryRunReq.getMetadata().setNamespace(getNamespace());
try {
dryRunRes = batchV1ApiInstance.createNamespacedJob(dryRunReq.getMetadata().getNamespace(),
dryRunReq, getPretty(), DRY_RUN_ALL, null);
} catch (ApiException e) {
handleApiException(e);
}
checkNotNull(dryRunRes);
// Recover metadata
dryRunRes.getMetadata().
name(getName()).
creationTimestamp(original.getMetadata().getCreationTimestamp()).
selfLink(original.getMetadata().getSelfLink()).
uid(original.getMetadata().getUid()).
resourceVersion(original.getMetadata().getUid()).
ownerReferences(original.getMetadata().getOwnerReferences()).
generateName(null);
// Recover label/selector
// According to
// https://github.com/kubernetes/kubernetes/blob/152b09ac550d50deeeff7162093332b4f7f0397d/pkg/registry/batch/job/strategy.go#L101
// https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector
if (BooleanUtils.isNotTrue(current.getSpec().getManualSelector())) {
String controllerUid = original.getMetadata().getLabels().get(KUBERNETES_CONTROLLER_UID_FIELD);
dryRunRes.getMetadata().getLabels().put(KUBERNETES_CONTROLLER_UID_FIELD, controllerUid);
dryRunRes.getMetadata().getLabels().put(KUBERNETES_JOB_NAME_FIELD, getName());
dryRunRes.getSpec().getSelector().putMatchLabelsItem(KUBERNETES_CONTROLLER_UID_FIELD, controllerUid);
dryRunRes.getSpec().getTemplate().getMetadata().getLabels().put(
KUBERNETES_CONTROLLER_UID_FIELD, controllerUid);
dryRunRes.getSpec().getTemplate().getMetadata().getLabels().put(KUBERNETES_JOB_NAME_FIELD, getName());
}
V1ResourceManager.recoverPodImagePullPolicy(original.getSpec().getTemplate().getSpec(),
current.getSpec().getTemplate().getSpec(),
dryRunRes.getSpec().getTemplate().getSpec());
return dryRunRes;
}
@Override
V1Job createResource(V1Job current) {
V1Job job = null;
try {
job = batchV1ApiInstance.createNamespacedJob(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return job;
}
@Override
V1Status deleteResource(V1Job current) {
V1Status result = null;
try {
result = batchV1ApiInstance.deleteNamespacedJob(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Job original, V1Job current) {
resourceUpdateMonitor.onJobUpdate(original, current);
}
}
class PodUpdater extends ResourceUpdater<V1Pod> {
PodUpdater(V1Pod pod) {
super(pod);
}
@Override
V1Pod getCurrentResource() {
V1Pod pod = null;
try {
pod = coreV1ApiInstance.readNamespacedPod(getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return pod;
}
@Override
V1Pod applyResource(V1Pod original, V1Pod current) {
V1Pod pod = null;
V1Pod putPod = getPutObject(original, current);
try {
pod = coreV1ApiInstance.replaceNamespacedPod(
getName(), getNamespace(), putPod, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return pod;
}
/**
* Get PutObject with server-dryRun.
* Only some of the fields in the job resource can be modified.
* Directly putting the original object of the user will cause some immutable
* fields with defaultValue to be modified.
* This method is a workaround that populates the default value with the server dryRun implementation.
* https://kubernetes.io/blog/2019/01/14/apiserver-dry-run-and-kubectl-diff/
*
* @param original Current Object in Cluster
* @param current Current object submitted by the user
* @return Pod With Default Value
*/
V1Pod getPutObject(V1Pod original, V1Pod current) {
// Clone Object to avoid modifications to the original object.
V1Pod dryRunReq = KubernetesJsonUtils.getKubernetesJson().deserialize(
KubernetesJsonUtils.getKubernetesJson().serialize(current), V1Pod.class);
// Build dryRun Request Object
V1Pod dryRunRes = null;
dryRunReq.getMetadata().setName(null);
dryRunReq.getMetadata().setGenerateName(getName());
dryRunReq.getMetadata().setNamespace(getNamespace());
try {
dryRunRes = coreV1ApiInstance.createNamespacedPod(dryRunReq.getMetadata().getNamespace(),
dryRunReq, getPretty(), DRY_RUN_ALL, null);
} catch (ApiException e) {
handleApiException(e);
}
checkNotNull(dryRunRes);
// Recover metadata
dryRunRes.getMetadata().
name(getName()).
creationTimestamp(original.getMetadata().getCreationTimestamp()).
selfLink(original.getMetadata().getSelfLink()).
uid(original.getMetadata().getUid()).
resourceVersion(original.getMetadata().getUid()).
ownerReferences(original.getMetadata().getOwnerReferences()).
generateName(null);
// Recover node
// According to https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodename
dryRunRes.getSpec().
nodeName(original.getSpec().getNodeName());
V1ResourceManager.recoverPodImagePullPolicy(
original.getSpec(),
current.getSpec(),
dryRunRes.getSpec());
return dryRunRes;
}
@Override
V1Pod createResource(V1Pod current) {
V1Pod pod = null;
try {
pod = coreV1ApiInstance.createNamespacedPod(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return pod;
}
@Override
V1Status deleteResource(V1Pod current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedPod(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Pod original, V1Pod current) {
resourceUpdateMonitor.onPodUpdate(original, current);
}
}
class ConfigMapUpdater extends ResourceUpdater<V1ConfigMap> {
ConfigMapUpdater(V1ConfigMap configMap) {
super(configMap);
}
@Override
V1ConfigMap getCurrentResource() {
V1ConfigMap configMap = null;
try {
configMap = coreV1ApiInstance.readNamespacedConfigMap(getName(), getNamespace(),
getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return configMap;
}
@Override
V1ConfigMap applyResource(V1ConfigMap original, V1ConfigMap current) {
V1ConfigMap configMap = null;
try {
configMap = coreV1ApiInstance.replaceNamespacedConfigMap(getName(), getNamespace(),
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return configMap;
}
@Override
V1ConfigMap createResource(V1ConfigMap current) {
V1ConfigMap configMap = null;
try {
configMap = coreV1ApiInstance.createNamespacedConfigMap(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return configMap;
}
@Override
V1Status deleteResource(V1ConfigMap current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedConfigMap(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ConfigMap original, V1ConfigMap current) {
resourceUpdateMonitor.onConfigMapUpdate(original, current);
}
}
class SecretUpdater extends ResourceUpdater<V1Secret> {
SecretUpdater(V1Secret secret) {
super(secret);
}
@Override
V1Secret getCurrentResource() {
V1Secret secret = null;
try {
secret = coreV1ApiInstance.readNamespacedSecret(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return secret;
}
@Override
V1Secret applyResource(V1Secret original, V1Secret current) {
V1Secret secret = null;
try {
secret = coreV1ApiInstance.replaceNamespacedSecret(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return secret;
}
@Override
V1Secret createResource(V1Secret current) {
V1Secret secret = null;
try {
secret = coreV1ApiInstance.createNamespacedSecret(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return secret;
}
@Override
V1Status deleteResource(V1Secret current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedSecret(
getName(), getNamespace(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Secret original, V1Secret current) {
resourceUpdateMonitor.onSecretUpdate(original, current);
}
@Override
void logApplied(V1Secret res) {
// do not show the secret details
getConsoleLogger().println(Messages.KubernetesClientWrapper_applied("Secret", "name: " + getName()));
}
@Override
void logCreated(V1Secret res) {
getConsoleLogger().println(Messages.KubernetesClientWrapper_created(getKind(), "name: " + getName()));
}
}
class NamespaceUpdater extends ResourceUpdater<V1Namespace> {
NamespaceUpdater(V1Namespace namespace) {
super(namespace);
}
@Override
V1Namespace getCurrentResource() {
V1Namespace result = null;
try {
result = coreV1ApiInstance.readNamespace(getName(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1Namespace applyResource(V1Namespace original, V1Namespace current) {
V1Namespace result = null;
try {
result = coreV1ApiInstance.replaceNamespace(getName(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Namespace createResource(V1Namespace current) {
V1Namespace result = null;
try {
result = coreV1ApiInstance.createNamespace(current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1Namespace current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespace(
getName(), getPretty(), null, null, null, null, null);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Namespace original, V1Namespace current) {
resourceUpdateMonitor.onNamespaceUpdate(original, current);
}
}
class HorizontalPodAutoscalerUpdater extends ResourceUpdater<V1HorizontalPodAutoscaler> {
HorizontalPodAutoscalerUpdater(V1HorizontalPodAutoscaler namespace) {
super(namespace);
}
@Override
V1HorizontalPodAutoscaler getCurrentResource() {
V1HorizontalPodAutoscaler result = null;
try {
result = autoscalingV1Api.readNamespacedHorizontalPodAutoscaler(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1HorizontalPodAutoscaler applyResource(V1HorizontalPodAutoscaler original, V1HorizontalPodAutoscaler current) {
V1HorizontalPodAutoscaler result = null;
try {
result = autoscalingV1Api.replaceNamespacedHorizontalPodAutoscaler(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1HorizontalPodAutoscaler createResource(V1HorizontalPodAutoscaler current) {
V1HorizontalPodAutoscaler result = null;
try {
result = autoscalingV1Api.createNamespacedHorizontalPodAutoscaler(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1HorizontalPodAutoscaler current) {
V1Status result = null;
try {
result = autoscalingV1Api.deleteNamespacedHorizontalPodAutoscaler(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1HorizontalPodAutoscaler original, V1HorizontalPodAutoscaler current) {
resourceUpdateMonitor.onHorizontalPodAutoscalerUpdate(original, current);
}
}
class StatefulSetUpdater extends ResourceUpdater<V1StatefulSet> {
StatefulSetUpdater(V1StatefulSet namespace) {
super(namespace);
}
@Override
V1StatefulSet getCurrentResource() {
V1StatefulSet result = null;
try {
result = appsV1ApiInstance.readNamespacedStatefulSet(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1StatefulSet applyResource(V1StatefulSet original, V1StatefulSet current) {
V1StatefulSet result = null;
try {
V1StatefulSet putStatefulSet = getPutObject(original, current);
result = appsV1ApiInstance.replaceNamespacedStatefulSet(
getName(), getNamespace(), putStatefulSet, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1StatefulSet createResource(V1StatefulSet current) {
V1StatefulSet result = null;
try {
result = appsV1ApiInstance.createNamespacedStatefulSet(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1StatefulSet current) {
V1Status result = null;
try {
result = appsV1ApiInstance.deleteNamespacedStatefulSet(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
/**
* Get PutObject with server-dryRun.
* Only some of the fields in the job resource can be modified.
* Directly putting the original object of the user will cause some immutable
* fields with defaultValue to be modified.
* This method is a workaround that populates the default value with the server dryRun implementation.
* https://kubernetes.io/blog/2019/01/14/apiserver-dry-run-and-kubectl-diff/
*
* @param original Current Object in Cluster
* @param current Current object submitted by the user
* @return StatefulSet With Default Value
*/
V1StatefulSet getPutObject(V1StatefulSet original, V1StatefulSet current) {
// Clone Object to avoid modifications to the original object.
V1StatefulSet dryRunReq = KubernetesJsonUtils.getKubernetesJson().deserialize(
KubernetesJsonUtils.getKubernetesJson().serialize(current), V1StatefulSet.class);
// Build dryRun Request Object
V1StatefulSet dryRunRes = null;
dryRunReq.getMetadata().setName(null);
dryRunReq.getMetadata().setGenerateName(getName());
dryRunReq.getMetadata().setNamespace(getNamespace());
try {
dryRunRes = appsV1ApiInstance.createNamespacedStatefulSet(dryRunReq.getMetadata().getNamespace(),
dryRunReq, getPretty(), DRY_RUN_ALL, null);
} catch (ApiException e) {
handleApiException(e);
}
checkNotNull(dryRunRes);
// Recover metadata
dryRunRes.getMetadata().
name(getName()).
creationTimestamp(original.getMetadata().getCreationTimestamp()).
selfLink(original.getMetadata().getSelfLink()).
uid(original.getMetadata().getUid()).
resourceVersion(original.getMetadata().getUid()).
ownerReferences(original.getMetadata().getOwnerReferences()).
generateName(null);
V1ResourceManager.recoverPodImagePullPolicy(
original.getSpec().getTemplate().getSpec(),
current.getSpec().getTemplate().getSpec(),
dryRunRes.getSpec().getTemplate().getSpec());
return dryRunRes;
}
@Override
void notifyUpdate(V1StatefulSet original, V1StatefulSet current) {
resourceUpdateMonitor.onStatefulSetUpdate(original, current);
}
}
class PersistentVolumeClaimUpdater extends ResourceUpdater<V1PersistentVolumeClaim> {
PersistentVolumeClaimUpdater(V1PersistentVolumeClaim namespace) {
super(namespace);
}
@Override
V1PersistentVolumeClaim getCurrentResource() {
V1PersistentVolumeClaim result = null;
try {
result = coreV1ApiInstance.readNamespacedPersistentVolumeClaim(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1PersistentVolumeClaim applyResource(V1PersistentVolumeClaim original, V1PersistentVolumeClaim current) {
// The kubernetes-client library will compare the server config and the current applied config,
// and compute the difference, which will be sent to the PATCH API of Kubernetes. The missing field
// will be considered as deletion, which will cause the Kubernetes misunderstanding the update request.
//
// "kubectl apply" handles the pvc update in the same way.
if (current.getSpec() != null && original.getSpec() != null) {
if (current.getSpec().getStorageClassName() == null) {
current.getSpec().setStorageClassName(original.getSpec().getStorageClassName());
}
if (current.getSpec().getVolumeName() == null) {
current.getSpec().setVolumeName(original.getSpec().getVolumeName());
}
if (current.getSpec().getVolumeMode() == null) {
current.getSpec().setVolumeMode(original.getSpec().getVolumeMode());
}
if (current.getSpec().getResources() == null) {
current.getSpec().setResources(original.getSpec().getResources());
}
}
V1PersistentVolumeClaim result = null;
try {
result = coreV1ApiInstance.replaceNamespacedPersistentVolumeClaim(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1PersistentVolumeClaim createResource(V1PersistentVolumeClaim current) {
V1PersistentVolumeClaim result = null;
try {
result = coreV1ApiInstance.createNamespacedPersistentVolumeClaim(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1PersistentVolumeClaim current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedPersistentVolumeClaim(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1PersistentVolumeClaim original, V1PersistentVolumeClaim current) {
resourceUpdateMonitor.onPersistentVolumeClaimUpdate(original, current);
}
}
class PersistentVolumeUpdater extends ResourceUpdater<V1PersistentVolume> {
PersistentVolumeUpdater(V1PersistentVolume persistentVolume) {
super(persistentVolume);
}
@Override
V1PersistentVolume getCurrentResource() {
V1PersistentVolume result = null;
try {
result = coreV1ApiInstance.readPersistentVolume(
getName(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1PersistentVolume applyResource(V1PersistentVolume original, V1PersistentVolume current) {
V1PersistentVolume result = null;
try {
result = coreV1ApiInstance.replacePersistentVolume(
getName(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1PersistentVolume createResource(V1PersistentVolume current) {
V1PersistentVolume result = null;
try {
result = coreV1ApiInstance.createPersistentVolume(
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1PersistentVolume current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deletePersistentVolume(
getName(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1PersistentVolume original, V1PersistentVolume current) {
resourceUpdateMonitor.onPersistentVolumeUpdate(original, current);
}
}
class NetworkPolicyUpdater extends ResourceUpdater<V1NetworkPolicy> {
NetworkPolicyUpdater(V1NetworkPolicy networkPolicy) {
super(networkPolicy);
}
@Override
V1NetworkPolicy getCurrentResource() {
V1NetworkPolicy result = null;
try {
result = networkingV1Api.readNamespacedNetworkPolicy(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1NetworkPolicy applyResource(V1NetworkPolicy original, V1NetworkPolicy current) {
V1NetworkPolicy result = null;
try {
result = networkingV1Api.replaceNamespacedNetworkPolicy(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1NetworkPolicy createResource(V1NetworkPolicy current) {
V1NetworkPolicy result = null;
try {
result = networkingV1Api.createNamespacedNetworkPolicy(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1NetworkPolicy current) {
V1Status result = null;
try {
result = networkingV1Api.deleteNamespacedNetworkPolicy(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1NetworkPolicy original, V1NetworkPolicy current) {
resourceUpdateMonitor.onNetworkPolicyUpdate(original, current);
}
}
class RoleUpdater extends ResourceUpdater<V1Role> {
RoleUpdater(V1Role role) {
super(role);
}
@Override
V1Role getCurrentResource() {
V1Role result = null;
try {
result = rbacV1Api.readNamespacedRole(
getName(), getNamespace(), getPretty());
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1Role applyResource(V1Role original, V1Role current) {
V1Role result = null;
try {
result = rbacV1Api.replaceNamespacedRole(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Role createResource(V1Role current) {
V1Role result = null;
try {
result = rbacV1Api.createNamespacedRole(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1Role current) {
V1Status result = null;
try {
result = rbacV1Api.deleteNamespacedRole(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1Role original, V1Role current) {
resourceUpdateMonitor.onRoleUpdate(original, current);
}
}
class RoleBindingUpdater extends ResourceUpdater<V1RoleBinding> {
RoleBindingUpdater(V1RoleBinding roleBinding) {
super(roleBinding);
}
@Override
V1RoleBinding getCurrentResource() {
V1RoleBinding result = null;
try {
result = rbacV1Api.readNamespacedRoleBinding(
getName(), getNamespace(), getPretty());
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1RoleBinding applyResource(V1RoleBinding original, V1RoleBinding current) {
V1RoleBinding result = null;
try {
result = rbacV1Api.replaceNamespacedRoleBinding(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1RoleBinding createResource(V1RoleBinding current) {
V1RoleBinding result = null;
try {
result = rbacV1Api.createNamespacedRoleBinding(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1RoleBinding current) {
V1Status result = null;
try {
result = rbacV1Api.deleteNamespacedRoleBinding(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1RoleBinding original, V1RoleBinding current) {
resourceUpdateMonitor.onRoleBindingUpdate(original, current);
}
}
class ServiceAccountUpdater extends ResourceUpdater<V1ServiceAccount> {
ServiceAccountUpdater(V1ServiceAccount serviceAccount) {
super(serviceAccount);
}
@Override
V1ServiceAccount getCurrentResource() {
V1ServiceAccount result = null;
try {
result = coreV1ApiInstance.readNamespacedServiceAccount(
getName(), getNamespace(), getPretty(), true, true);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1ServiceAccount applyResource(V1ServiceAccount original, V1ServiceAccount current) {
V1ServiceAccount result = null;
try {
result = coreV1ApiInstance.replaceNamespacedServiceAccount(
getName(), getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1ServiceAccount createResource(V1ServiceAccount current) {
V1ServiceAccount result = null;
try {
result = coreV1ApiInstance.createNamespacedServiceAccount(
getNamespace(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1ServiceAccount current) {
V1Status result = null;
try {
result = coreV1ApiInstance.deleteNamespacedServiceAccount(
getName(), getNamespace(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ServiceAccount original, V1ServiceAccount current) {
resourceUpdateMonitor.onServiceAccountUpdate(original, current);
}
}
class ClusterRoleUpdater extends ResourceUpdater<V1ClusterRole> {
ClusterRoleUpdater(V1ClusterRole clusterRole) {
super(clusterRole);
}
@Override
V1ClusterRole getCurrentResource() {
V1ClusterRole result = null;
try {
result = rbacV1Api.readClusterRole(
getName(), getPretty());
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1ClusterRole applyResource(V1ClusterRole original, V1ClusterRole current) {
V1ClusterRole result = null;
try {
result = rbacV1Api.replaceClusterRole(
getName(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1ClusterRole createResource(V1ClusterRole current) {
V1ClusterRole result = null;
try {
result = rbacV1Api.createClusterRole(
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1ClusterRole current) {
V1Status result = null;
try {
result = rbacV1Api.deleteClusterRole(
getName(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ClusterRole original, V1ClusterRole current) {
resourceUpdateMonitor.onClusterRoleUpdate(original, current);
}
}
class ClusterRoleBindingUpdater extends ResourceUpdater<V1ClusterRoleBinding> {
ClusterRoleBindingUpdater(V1ClusterRoleBinding clusterRoleBinding) {
super(clusterRoleBinding);
}
@Override
V1ClusterRoleBinding getCurrentResource() {
V1ClusterRoleBinding result = null;
try {
result = rbacV1Api.readClusterRoleBinding(
getName(), getPretty());
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
V1ClusterRoleBinding applyResource(V1ClusterRoleBinding original, V1ClusterRoleBinding current) {
V1ClusterRoleBinding result = null;
try {
result = rbacV1Api.replaceClusterRoleBinding(
getName(), current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1ClusterRoleBinding createResource(V1ClusterRoleBinding current) {
V1ClusterRoleBinding result = null;
try {
result = rbacV1Api.createClusterRoleBinding(
current, getPretty(), null, null);
} catch (ApiException e) {
handleApiException(e);
}
return result;
}
@Override
V1Status deleteResource(V1ClusterRoleBinding current) {
V1Status result = null;
try {
result = rbacV1Api.deleteClusterRoleBinding(
getName(), getPretty(),
null, null, null, null, Constants.BACKGROUND_DELETEION);
} catch (ApiException e) {
handleApiExceptionExceptNotFound(e);
}
return result;
}
@Override
void notifyUpdate(V1ClusterRoleBinding original, V1ClusterRoleBinding current) {
resourceUpdateMonitor.onClusterRoleBindingUpdate(original, current);
}
}
}
| 38.630975 | 141 | 0.577625 |
d35092de8517de503473a47e3e8f53da75cea1a8 | 5,729 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.siddhi.core.query.eventwindow;
import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;
public class SortEventWindowTestCase {
private static final Logger log = Logger.getLogger(SortEventWindowTestCase.class);
private int inEventCount;
private int removeEventCount;
private boolean eventArrived;
@Before
public void init() {
inEventCount = 0;
removeEventCount = 0;
eventArrived = false;
}
@Test
public void testSortWindow1() throws InterruptedException {
log.info("SortWindow test1");
SiddhiManager siddhiManager = new SiddhiManager();
String cseEventStream = "" +
"define stream cseEventStream (symbol string, price float, volume long); " +
"define window cseEventWindow (symbol string, price float, volume long) sort(2,volume, 'asc'); ";
String query = "" +
"@info(name = 'query0') " +
"from cseEventStream " +
"insert into cseEventWindow; " +
"" +
"@info(name = 'query1') " +
"from cseEventWindow " +
"select volume " +
"insert all events into outputStream ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(cseEventStream + query);
executionPlanRuntime.addCallback("query1", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
inEventCount = inEventCount + inEvents.length;
}
if (removeEvents != null) {
removeEventCount = removeEventCount + removeEvents.length;
}
eventArrived = true;
}
});
InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
executionPlanRuntime.start();
inputHandler.send(new Object[]{"WSO2", 55.6f, 100l});
inputHandler.send(new Object[]{"IBM", 75.6f, 300l});
inputHandler.send(new Object[]{"WSO2", 57.6f, 200l});
inputHandler.send(new Object[]{"WSO2", 55.6f, 20l});
inputHandler.send(new Object[]{"WSO2", 57.6f, 40l});
Thread.sleep(1000);
Assert.assertEquals(5, inEventCount);
Assert.assertEquals(3, removeEventCount);
Assert.assertTrue(eventArrived);
executionPlanRuntime.shutdown();
}
@Test
public void testSortWindow2() throws InterruptedException {
log.info("SortWindow test2");
SiddhiManager siddhiManager = new SiddhiManager();
String cseEventStream = "" +
"define stream cseEventStream (symbol string, price float, volume long); " +
"define window cseEventWindow (symbol string, price float, volume long) sort(2,volume, 'asc', price, 'desc'); ";
String query = "" +
"@info(name = 'query0') " +
"from cseEventStream " +
"insert into cseEventWindow; " +
"" +
"@info(name = 'query1') " +
"from cseEventWindow " +
"select volume " +
"insert all events into outputStream ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(cseEventStream + query);
executionPlanRuntime.addCallback("query1", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
inEventCount = inEventCount + inEvents.length;
}
if (removeEvents != null) {
removeEventCount = removeEventCount + removeEvents.length;
}
eventArrived = true;
}
});
InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
executionPlanRuntime.start();
inputHandler.send(new Object[]{"WSO2", 50, 100l});
inputHandler.send(new Object[]{"IBM", 20, 100l});
inputHandler.send(new Object[]{"WSO2", 40, 50l});
inputHandler.send(new Object[]{"WSO2", 100, 20l});
inputHandler.send(new Object[]{"WSO2", 50, 50l});
Thread.sleep(1000);
Assert.assertEquals(5, inEventCount);
Assert.assertEquals(3, removeEventCount);
Assert.assertTrue(eventArrived);
executionPlanRuntime.shutdown();
}
}
| 38.709459 | 128 | 0.620003 |
045adbc8090ed8888856e6ff76254cfca62e47d2 | 1,604 | package com.datapath.kg.risks.api.dao.repository;
import com.datapath.kg.risks.api.dao.entity.ChecklistEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ChecklistRepository extends JpaRepository<ChecklistEntity, Integer>, JpaSpecificationExecutor<ChecklistEntity> {
ChecklistEntity getById(Integer id);
@Query(value = "SELECT * FROM checklist WHERE audit_name ILIKE CONCAT(:value, '%') LIMIT 10", nativeQuery = true)
List<ChecklistEntity> searchByAuditName(@Param("value") String value);
@Query(value = "SELECT * FROM checklist WHERE audit_name ILIKE CONCAT(:value, '%') AND status_id = 2 LIMIT 10", nativeQuery = true)
List<ChecklistEntity> searchByAuditNameForAdmin(@Param("value") String value);
@Query(value = "SELECT id FROM checklist WHERE auditor_id = :auditorId AND status_id = 1", nativeQuery = true)
List<Integer> getActiveChecklistsByAuditor(@Param("auditorId") Integer auditorId);
@Query(value = "SELECT count(id) FROM checklist WHERE auditor_id = :auditorId AND status_id = 2", nativeQuery = true)
Integer getCompletedChecklistCount(@Param("auditorId") Integer auditorId);
@Query(value = "SELECT * FROM checklist WHERE buyer_id = :buyerId AND status_id = 2 AND tender_id IS NOT NULL", nativeQuery = true)
List<ChecklistEntity> getTendersChecklistsByBuyerId(@Param("buyerId") Integer buyerId);
}
| 53.466667 | 135 | 0.774938 |
ce9cc64ece65a0abd48990ba9c79d29c31034fc1 | 4,796 | /**
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.doc;
import static org.apache.sling.jcr.resource.JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.sling.commons.testing.jcr.MockNode;
import org.apache.sling.commons.testing.jcr.MockNodeIterator;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
/**
*
*/
public class DocumentationWriterTest {
private String path = "/path/to/searchnode";
// Things that should be shown in the doc.
private String title = "-_-title";
private String description = "-_-description";
private String response = "-_-reponse";
private String shortDesc = "-_-shortDesc";
private String parameter = "{name: \"parName\", description: \"parDescription\"}";
// Things that should not be shown in the doc.
private String query = "//-_-query";
private DocumentationWriter writer;
private ByteArrayOutputStream baos;
private PrintWriter printWriter;
@Before
public void setUp() {
baos = new ByteArrayOutputStream();
printWriter = new PrintWriter(baos);
writer = new DocumentationWriter("Search nodes", printWriter);
}
@Test
public void testNode() throws RepositoryException, UnsupportedEncodingException {
Node node = createNode(path, title, description, response, shortDesc, parameter,
query);
Session session = mock(Session.class);
when(session.getItem(path)).thenReturn(node);
writer.writeSearchInfo(path, session);
printWriter.flush();
String s = baos.toString("UTF-8");
assertEquals(true, s.contains(path));
assertEquals(true, s.contains(title));
assertEquals(true, s.contains(description));
assertEquals(true, s.contains(response));
assertEquals(true, s.contains("parName"));
assertEquals(false, s.contains(query));
}
private Node createNode(String path, String title, String description, String response,
String shortDesc, String parameter, String query) throws RepositoryException {
MockNode node = new MockNode(path);
node.setProperty(SLING_RESOURCE_TYPE_PROPERTY, "sakai/solr-search");
node.setProperty(NodeDocumentation.TITLE, title);
node.setProperty(NodeDocumentation.DESCRIPTION, description);
node.setProperty(NodeDocumentation.RESPONSE, response);
node.setProperty(NodeDocumentation.SHORT_DESCRIPTION, shortDesc);
node.setProperty(NodeDocumentation.PARAMETERS, parameter);
node.setProperty("sakai:query", query);
return node;
}
@Test
public void testQuery() throws RepositoryException, UnsupportedEncodingException {
Session session = mock(Session.class);
Workspace workSpace = mock(Workspace.class);
QueryManager qm = mock(QueryManager.class);
Query q = mock(Query.class);
QueryResult result = mock(QueryResult.class);
String queryString = "//*[@sling:resourceType='sakai/sparse-search']";
Node node = createNode(path, title, description, response, shortDesc, parameter,
query);
NodeIterator nodeIterator = new MockNodeIterator(new Node[] { node });
// Mock execution of query.
when(session.getWorkspace()).thenReturn(workSpace);
when(workSpace.getQueryManager()).thenReturn(qm);
when(qm.createQuery(queryString, Query.XPATH)).thenReturn(q);
when(q.execute()).thenReturn(result);
when(result.getNodes()).thenReturn(nodeIterator);
writer.writeNodes(session, queryString, "/system/doc/proxy");
printWriter.flush();
String s = baos.toString("UTF-8");
assertTrue(s.contains(path));
}
}
| 36.892308 | 94 | 0.745204 |
d629d4988723ad1cec40ffaa004249c0fb2194db | 40 | duplicates test test extracted extracted | 40 | 40 | 0.9 |
2240fc0e5d1b6a0996120204ac6634c7a3fff2bb | 4,090 | package com.tencent.liteav.demo.play.net;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.liteav.demo.play.SuperPlayerModel;
import com.tencent.liteav.demo.play.utils.PlayInfoResponseParser;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by liyuejiao on 2018/7/3.
* 超级播放器内部获取点播信息
*/
public class SuperVodInfoLoader {
private static final String TAG = "SuperVodInfoLoader";
private Handler mMainHandler;
private boolean mIsHttps;
private final String BASE_URL = "http://playvideo.qcloud.com/getplayinfo/v2";
private final String BASE_URLS = "https://playvideo.qcloud.com/getplayinfo/v2";
private OnVodInfoLoadListener mOnVodInfoLoadListener;
public SuperVodInfoLoader() {
mMainHandler = new Handler(Looper.getMainLooper());
}
public void setOnVodInfoLoadListener(OnVodInfoLoadListener listener) {
mOnVodInfoLoadListener = listener;
}
public void getVodByFileId(final SuperPlayerModel model) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
String urlStr = makeUrlString(model.appid, model.fileid, null, null, -1, null);
TCHttpURLClient.getInstance().get(urlStr, new TCHttpURLClient.OnHttpCallback() {
@Override
public void onSuccess(String result) {
parseJson(result);
}
@Override
public void onError() {
//获取请求信息失败
if (mOnVodInfoLoadListener != null) {
mOnVodInfoLoadListener.onFail(-1);
}
}
});
}
});
}
private void parseJson(String content) {
if (TextUtils.isEmpty(content)) {
TXCLog.e(TAG, "parseJson err, content is empty!");
return;
}
try {
JSONObject jsonObject = new JSONObject(content);
int code = jsonObject.getInt("code");
if (code != 0) {
String message = jsonObject.getString("message");
TXCLog.e(TAG, message);
return;
}
final PlayInfoResponseParser playInfoResponse = new PlayInfoResponseParser(jsonObject);
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mOnVodInfoLoadListener != null) {
mOnVodInfoLoadListener.onSuccess(playInfoResponse);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
private String makeUrlString(int appId, String fileId, String timeout, String us, int exper, String sign) {
String urlStr;
if (mIsHttps) {
urlStr = String.format("%s/%d/%s", BASE_URL, appId, fileId);
} else {
urlStr = String.format("%s/%d/%s", BASE_URLS, appId, fileId);
}
String query = makeQueryString(timeout, us, exper, sign);
if (query != null) {
urlStr = urlStr + "?" + query;
}
return urlStr;
}
private String makeQueryString(String timeout, String us, int exper, String sign) {
StringBuilder str = new StringBuilder();
if (timeout != null) {
str.append("t=" + timeout + "&");
}
if (us != null) {
str.append("us=" + us + "&");
}
if (sign != null) {
str.append("sign=" + sign + "&");
}
if (exper >= 0) {
str.append("exper=" + exper + "&");
}
if (str.length() > 1) {
str.deleteCharAt(str.length() - 1);
}
return str.toString();
}
public interface OnVodInfoLoadListener {
void onSuccess(PlayInfoResponseParser response);
void onFail(int errCode);
}
}
| 31.461538 | 111 | 0.552567 |
64a4437bc98988087f2f97368e0aaa90477ba2ec | 4,217 | package com.alan.wechat.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.alan.wechat.entity.Message;
import com.alibaba.fastjson.JSON;
/**
* @author alanpan
* @title: WebSocketWeChatServer
* @projectName springboot-websocket
* @description: WebSocket 聊天服务端
* @date 2019/4/122:07
*/
@Component
@ServerEndpoint("/wechat/{username}")//WebSocket服务端 需指定端点的访问路径
public class WebSocketWeChatServer {
// 记录全部在线会话信息 使用线程安全 Map
private static Map<String, Session> onlineSessions
= new ConcurrentHashMap<>();
private static Map<String, WebSocketWeChatServer> clients = new ConcurrentHashMap<String, WebSocketWeChatServer>();
/**
* @return void
* @Author alan.Pan
* @Description //当客户端打开连接
* @Date 22:12 2019/4/1
* @Param [session]
**/
@OnOpen
public void onOpen(@PathParam("username") String username,Session session) {
//添加会话对象
onlineSessions.put(username, session);
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
//先给所有人发送通知,说我上线了
//更新在线人数
sendMessageToAll(Message.jsonStr(Message.TypeEnum.onLine.getCode(), username, "",null,"", onlineSessions.size()));
//给自己发一条消息:告诉自己现在都有谁在线
Set<String> set = onlineSessions.keySet();
//移除掉自己
sendMessageTo(Message.jsonStr(Message.TypeEnum.onLineList.getCode(), "", "",set,"", onlineSessions.size()), username);
}
/**
* @return void
* @Author alan.Pan
* @Description //当客户端发送消息
* @Date 22:13 2019/4/1
* @Param [session, msg]
**/
@OnMessage
public void onMessage(Session session, String jsonStr) {
Message message = JSON.parseObject(jsonStr, Message.class);
/* synchronized (session) { */
//所有人
if (!StringUtils.isEmpty(message.getTousername())&& message.getTousername().equals("所有"))
{
sendMessageToAll(Message.jsonStr(Message.TypeEnum.Other.getCode(), message.getUsername(),message.getTousername(),null, message.getMsg(), onlineSessions.size()));
}
else
{ //发给某一个人
sendMessageTo(Message.jsonStr(Message.TypeEnum.Other.getCode(), message.getUsername(),message.getTousername(),null, message.getMsg(), onlineSessions.size()),message.getTousername());
}
/* } */
}
/**
* @return void
* @Author alan.Pan
* @Description //关闭连接
* @Date 22:20 2019/4/1
* @Param []
**/
@OnClose
public void onClose(Session session) {
//从 在线人数中移除 对象
onlineSessions.remove(session.getId());
// 更新在线人数
Set<String> set = onlineSessions.keySet();
//告诉所有人 自己下线了
sendMessageToAll(Message.jsonStr(Message.TypeEnum.offLine.getCode(), "", "", set, "",onlineSessions.size()));
}
/**
* 当通信发生异常:打印错误日志
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* session.getBasicRemote().sendText(message); //同步发送
* session.getAsyncRemote().sendText(message); //异步发送
* 发送给单个人
* @param msg
* @param username
*/
private static void sendMessageTo(String msg,String username)
{
try {
for (Map.Entry<String, Session> entity: onlineSessions.entrySet())
{
if (entity.getKey().equals(username))
entity.getValue().getAsyncRemote().sendText(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送信息给所有人
*/
private static void sendMessageToAll(String msg) {
try {
for (Session session : onlineSessions.values())
{
session.getAsyncRemote().sendText(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 29.48951 | 198 | 0.640266 |
e90a9dcbecbcfc74eb98e0c208a68de7a7cb824f | 1,811 | package com.lambdaschool.todos.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
@Entity
@Table(name = "todos")
public class Todos extends Auditable // added auditing
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long todoid;
@Column(nullable = false, length = 10000)
private String description;
@Column(nullable = false)
private boolean completed = false;
// foreign key relationship to User
@ManyToOne
@JoinColumn(name = "userid", nullable = false)
@JsonIgnoreProperties(value = "todos")
private User user;
// default constructor
public Todos()
{
}
// constructor
// switched params following SeedData structure
public Todos( User user, String description) {
this.description = description;
this.user = user;
}
// getters and setters
public long getTodoid() {
return todoid;
}
public void setTodoid(long todoid) {
this.todoid = todoid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Todos{" +
"todoid=" + todoid +
", description='" + description + '\'' +
", completed=" + completed +
", user=" + user +
'}';
}
}
| 21.559524 | 61 | 0.600773 |
572e3ac84c8abc177fb0c81dd9fbe0c550745622 | 2,414 | /**
* Copyright © 2020 Futurewei Technologies, Inc. All rights reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
* Unless required by applicable law or agreed to in writing, software
*
* distributed under the License is distributed on an "AS IS" BASIS,
*
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
*
* limitations under the License.
*/
package com.futurewei.contact_shield_demo.network;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import static android.content.Context.MODE_PRIVATE;
/**
* This class requests the server to generate the ZIP file and upload this ZIP file to Google Storage
*
*/
public class GeneratePKZip extends NetworkTemplate {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
public GeneratePKZip(Context context, Handler handler){
super("Download New", context, handler, 5, "http://3.16.177.15:5000/zip");
this.requestBody = makeRequestBody();
}
RequestBody makeRequestBody(){
final SharedPreferences sharedPreferences = context.getSharedPreferences("last_download_timeStamp",MODE_PRIVATE);
long lastDownloadTimeStamp=sharedPreferences.getLong("last_download_timeStamp",0);
String user_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.e(TAG, "user_id:"+user_id);
Log.e(TAG, "timestamp:"+lastDownloadTimeStamp);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("timestamp", lastDownloadTimeStamp);
jsonObject.put("user_id", user_id);
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
Log.e(TAG, "last download timestamp: "+lastDownloadTimeStamp+"");
RequestBody formBody = RequestBody.create(jsonObject.toString(), JSON);
return formBody;
}
}
| 30.556962 | 121 | 0.711268 |
015fa4dbb5e0e299cdac14bf8be6fdf47df8fbe1 | 1,932 | package pl.temomuko.autostoprace.data.local.gms;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import javax.inject.Inject;
import javax.inject.Singleton;
import pl.temomuko.autostoprace.Constants;
import pl.temomuko.autostoprace.injection.AppContext;
import rx.Observable;
/**
* Created by Rafał Naniewicz on 15.02.2016.
*/
@Singleton
public class GmsLocationHelper {
private final Context mContext;
@Inject
public GmsLocationHelper(@AppContext Context context) {
mContext = context;
}
public Observable<Location> getDeviceLocation() {
return LocationObservable.create(mContext, getLocationRequest());
}
public Observable<LocationSettingsResult> checkLocationSettings() {
return ApiClientObservable.create(mContext, LocationServices.API)
.flatMap(googleApiClient -> PendingResultObservable.create(
LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
getLocationSettingsRequest(getLocationRequest()))));
}
private LocationSettingsRequest getLocationSettingsRequest(LocationRequest locationRequest) {
return new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
.setAlwaysShow(true)
.build();
}
private static LocationRequest getLocationRequest() {
return new LocationRequest()
.setFastestInterval(Constants.LOCATION_FASTEST_UPDATE_INTERVAL_MILLISECONDS)
.setInterval(Constants.LOCATION_UPDATE_INTERVAL_MILLISECONDS)
.setPriority(Constants.APP_LOCATION_ACCURACY);
}
}
| 34.5 | 97 | 0.731366 |
0cf8ebf904bfeae2263f6dc91388f5d61db4ae30 | 155 | package de.hawhamburg.vs.wise15.superteam.client.callback;
/**
* Created by florian on 07.12.15.
*/
public interface Callback {
void callback();
}
| 15.5 | 58 | 0.703226 |
6f6937147b95b6dc11ea6d7e818130753f3804a1 | 852 | /*
*算法名称:冒泡排序
*基本思想:
1,比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2,对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3,针对所有的元素重复以上的步骤,除了最后一个。
4,持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
*时间复杂度:O(n2)
*空间复杂度:O(n)
*/
package com.xujin.sorting;
public class BubbleSort {
public static void main(String...args){
int[] arr = {2,52,87,62,82,62,32,96,31,69};
bubbleSort(arr);
System.out.println("\n冒泡排序后:");
for(int i=0; i<10; i++){
System.out.print(arr[i] + ",");
}
}
private static void bubbleSort(int[] arr) {
if(arr.length < 2) return;
int right;//每次冒泡那个最大元素落在这个索引位置上
for(int i=0; i<arr.length-1; i++){//需要进行n-1次冒泡
right = arr.length - 1 - i;
for(int j=0; j<right; j++){
if(arr[j] > arr[j+1]){
//swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
| 20.285714 | 55 | 0.598592 |
55df14d64ec0f29cb1519dd79c5685cb33920662 | 13,323 | /*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2020 Fabian Prasser and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deidentifier.arx.test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.deidentifier.arx.ARXAnonymizer;
import org.deidentifier.arx.ARXClassificationConfiguration;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.AttributeType;
import org.deidentifier.arx.AttributeType.Hierarchy;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.DataType;
import org.deidentifier.arx.aggregates.StatisticsClassification;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.io.CSVHierarchyInput;
import org.junit.Test;
/**
* Test for statistical classification
*
* @author Johanna Eicher
*/
public class TestClassification {
/** Result */
private ARXResult result;
/**
* @return the class
*/
private String getClazz() {
return "marital-status";
}
/**
* Loads a dataset from disk
*
* @param dataset
* @return
* @throws IOException
*/
private Data getData(final String dataset) throws IOException {
// Load data
Data data = Data.create("data/" + dataset + ".csv", StandardCharsets.UTF_8, ';');
// Read generalization hierarchies
FilenameFilter hierarchyFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.matches(dataset + "_hierarchy_(.)+.csv")) {
return true;
} else {
return false;
}
}
};
// Create definition
File testDir = new File("data/");
File[] genHierFiles = testDir.listFiles(hierarchyFilter);
Pattern pattern = Pattern.compile("_hierarchy_(.*?).csv");
for (File file : genHierFiles) {
Matcher matcher = pattern.matcher(file.getName());
if (matcher.find()) {
CSVHierarchyInput hier = new CSVHierarchyInput(file, StandardCharsets.UTF_8, ';');
String attributeName = matcher.group(1);
data.getDefinition().setAttributeType(attributeName,
Hierarchy.create(hier.getHierarchy()));
}
}
return data;
}
/**
* @return the features
*/
private String[] getFeatures() {
return new String[] { "sex",
"age",
"race",
"marital-status",
"education",
"native-country",
"workclass",
"occupation",
"salary-class" };
}
/**
* Performs anonymization and returns result.
*
* @return
* @throws IOException
*/
private ARXResult getResult() throws IOException {
if (result == null) {
// Data
Data data = getData("adult");
data.getDefinition().setAttributeType("marital-status", AttributeType.INSENSITIVE_ATTRIBUTE);
data.getDefinition().setDataType("age", DataType.INTEGER);
// Config
ARXConfiguration config = ARXConfiguration.create();
config.addPrivacyModel(new KAnonymity(5));
config.setSuppressionLimit(1d);
ARXAnonymizer anonymizer = new ARXAnonymizer();
result = anonymizer.anonymize(data, config);
}
return result;
}
@Test
public void testLogisticRegression() throws IOException, ParseException {
// Config
ARXClassificationConfiguration<?> config = ARXClassificationConfiguration.createLogisticRegression();
// Classify
StatisticsClassification classResult = getResult().getOutput().getStatistics().getClassificationPerformance(getFeatures(), getClazz(), config);
// Accuracy
assertEquals(0.6953119819640607, classResult.getOriginalAccuracy(), 0.000000000000001d);
assertEquals(0.4663152310854718, classResult.getZeroRAccuracy(), 0.000000000000001d);
assertEquals(0.6625555334526888, classResult.getAccuracy(), 0.000000000000001d);
// Average error
assertEquals(0.43014671841651053, classResult.getOriginalAverageError(), 0.0000000000000001d);
assertEquals(0.5336847689145282, classResult.getZeroRAverageError(), 0.000000000000001d);
assertEquals(0.458087061525274, classResult.getAverageError(), 0.000000000000001d);
// Sensitivity
assertEquals(0.28713811105837683, classResult.getROCCurve("Divorced").getSensitivity(), 0.000000000000001d);
assertEquals(0d, classResult.getROCCurve("Married-spouse-absent").getSensitivity(), 0.000000000000001d);
assertEquals(0.3349455864570738, classResult.getROCCurve("Widowed").getSensitivity(), 0.000000000000001d);
assertEquals(0d, classResult.getROCCurve("Separated").getSensitivity(), 0.000000000000001d);
assertEquals(0d, classResult.getROCCurve("Married-AF-spouse").getSensitivity(), 0.000000000000001d);
assertEquals(0.8457163170991824, classResult.getROCCurve("Married-civ-spouse").getSensitivity(), 0.000000000000001d);
assertEquals(0.678799095208719, classResult.getROCCurve("Never-married").getSensitivity(), 0.000000000000001d);
// Specificity
assertEquals(0.9507091105287498, classResult.getROCCurve("Divorced").getSpecificity(), 0.000000000000001d);
assertEquals(0.9999328678839957, classResult.getROCCurve("Married-spouse-absent").getSpecificity(), 0.000000000000001d);
assertEquals(0.991545934890063, classResult.getROCCurve("Widowed").getSpecificity(), 0.000000000000001d);
assertEquals(0.9998973411354071, classResult.getROCCurve("Separated").getSpecificity(), 0.000000000000001d);
assertEquals(1d, classResult.getROCCurve("Married-AF-spouse").getSpecificity(), 0.000000000000001d);
assertEquals(0.6962166863390694, classResult.getROCCurve("Married-civ-spouse").getSpecificity(), 0.000000000000001d);
assertEquals(0.8162066940692895, classResult.getROCCurve("Never-married").getSpecificity(), 0.000000000000001d);
// Brier score
assertEquals(0.10443452758431408, classResult.getROCCurve("Divorced").getBrierScore(), 0.000000000000001d);
assertEquals(0.012016040652422648, classResult.getROCCurve("Married-spouse-absent").getBrierScore(), 0.000000000000001d);
assertEquals(0.02128820838095078, classResult.getROCCurve("Widowed").getBrierScore(), 0.000000000000001d);
assertEquals(0.02923421938927171, classResult.getROCCurve("Separated").getBrierScore(), 0.000000000000001d);
assertEquals(6.961954804848942E-4, classResult.getROCCurve("Married-AF-spouse").getBrierScore(), 0.000000000000001d);
assertEquals(0.15298256377665254, classResult.getROCCurve("Married-civ-spouse").getBrierScore(), 0.000000000000001d);
assertEquals(0.14548728696298602, classResult.getROCCurve("Never-married").getBrierScore(), 0.000000000000001d);
// AUC
assertEquals(0.7610124597337793, classResult.getROCCurve("Divorced").getAUC(), 0.000000000000001d);
assertEquals(0.7158230397421533, classResult.getROCCurve("Married-spouse-absent").getAUC(), 0.000000000000001d);
assertEquals(0.9062487311956317, classResult.getROCCurve("Widowed").getAUC(), 0.000000000000001d);
assertEquals(0.7386316240248749, classResult.getROCCurve("Separated").getAUC(), 0.000000000000001d);
assertEquals(0.5357992040583639, classResult.getROCCurve("Married-AF-spouse").getAUC(), 0.000000000000001d);
assertEquals(0.8556273433051558, classResult.getROCCurve("Married-civ-spouse").getAUC(), 0.000000000000001d);
assertEquals(0.8405758072618743, classResult.getROCCurve("Never-married").getAUC(), 0.000000000000001d);
// Other properties
assertEquals(7, classResult.getNumClasses(), 0d);
assertEquals(30162, classResult.getNumMeasurements(), 0d);
}
@Test
public void testNaiveBayes() throws IOException, ParseException {
// Config
ARXClassificationConfiguration<?> config = ARXClassificationConfiguration.createNaiveBayes();
// Classify
StatisticsClassification classResult = getResult().getOutput().getStatistics().getClassificationPerformance(getFeatures(), getClazz(), config);
// Accuracy
assertEquals(0.6447516742921557, classResult.getOriginalAccuracy(), 0d);
assertEquals(0.4663152310854718, classResult.getZeroRAccuracy(), 0d);
assertEquals(0.6271798952324117, classResult.getAccuracy(), 0d);
// Average error
assertEquals(0.38050937350272185, classResult.getOriginalAverageError(), 0d);
assertEquals(0.5336847689145282, classResult.getZeroRAverageError(), 0d);
assertEquals(0.39543922724482766, classResult.getAverageError(), 0d);
// Sensitivity
assertEquals(0.23706691979117228, classResult.getROCCurve("Divorced").getSensitivity(), 0d);
assertEquals(0.05675675675675676, classResult.getROCCurve("Married-spouse-absent").getSensitivity(), 0d);
assertEquals(0.4195888754534462, classResult.getROCCurve("Widowed").getSensitivity(), 0d);
assertEquals(0.12566560170394037, classResult.getROCCurve("Separated").getSensitivity(), 0d);
assertEquals(0d, classResult.getROCCurve("Married-AF-spouse").getSensitivity(), 0d);
assertEquals(0.6993956629932456, classResult.getROCCurve("Married-civ-spouse").getSensitivity(), 0d);
assertEquals(0.7808965659058195, classResult.getROCCurve("Never-married").getSensitivity(), 0d);
// Specificity
assertEquals(0.952597502697703, classResult.getROCCurve("Divorced").getSpecificity(), 0d);
assertEquals(0.990702201933405, classResult.getROCCurve("Married-spouse-absent").getSpecificity(), 0d);
assertEquals(0.9767513209476735, classResult.getROCCurve("Widowed").getSpecificity(), 0d);
assertEquals(0.973342914827362, classResult.getROCCurve("Separated").getSpecificity(), 0d);
assertEquals(1d, classResult.getROCCurve("Married-AF-spouse").getSpecificity(), 0d);
assertEquals(0.8227620053426105, classResult.getROCCurve("Married-civ-spouse").getSpecificity(), 0d);
assertEquals(0.7345860246623606, classResult.getROCCurve("Never-married").getSpecificity(), 0d);
// Brier score
assertEquals(0.12097803188289097, classResult.getROCCurve("Divorced").getBrierScore(), 0d);
assertEquals(0.017706173395676122, classResult.getROCCurve("Married-spouse-absent").getBrierScore(), 0d);
assertEquals(0.028104806010520456, classResult.getROCCurve("Widowed").getBrierScore(), 0d);
assertEquals(0.03838086078373676, classResult.getROCCurve("Separated").getBrierScore(), 0d);
assertEquals(6.962403023672171E-4, classResult.getROCCurve("Married-AF-spouse").getBrierScore(), 0d);
assertEquals(0.18835167736742914, classResult.getROCCurve("Married-civ-spouse").getBrierScore(), 0d);
assertEquals(0.18555815408265927, classResult.getROCCurve("Never-married").getBrierScore(), 0d);
// AUC
assertEquals(0.74388359062692, classResult.getROCCurve("Divorced").getAUC(), 0d);
assertEquals(0.6968275539234446, classResult.getROCCurve("Married-spouse-absent").getAUC(), 0d);
assertEquals(0.8900178462158798, classResult.getROCCurve("Widowed").getAUC(), 0d);
assertEquals(0.7291579637131129, classResult.getROCCurve("Separated").getAUC(), 0d);
assertEquals(0.5805491965539002, classResult.getROCCurve("Married-AF-spouse").getAUC(), 0d);
assertEquals(0.8467890484679544, classResult.getROCCurve("Married-civ-spouse").getAUC(), 0d);
assertEquals(0.8265624922645384, classResult.getROCCurve("Never-married").getAUC(), 0d);
// Other properties
assertEquals(7, classResult.getNumClasses(), 0d);
assertEquals(30162, classResult.getNumMeasurements(), 0d);
}
}
| 50.465909 | 152 | 0.678226 |
1c5abeb66d780cb6b939a624e78a4a30d6924784 | 1,654 | package com.mvvm.model;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.util.Log;
import com.mvvm.BR;
import java.io.Serializable;
/**
* Created by chiclaim on 2016/02/18
*/
public class User extends BaseObservable{
private String userName;
private String realName;
private String mobile;
private int age;
/**
* 注意: 在BR里对应的常量为follow
*/
private boolean isFollow;
public User(String realName, String mobile) {
this.realName = realName;
this.mobile = mobile;
Log.d("User", "user construct invoked");
}
public User() {
}
@Bindable
public boolean isFollow() {
return isFollow;
}
public void setIsFollow(boolean isFollow) {
this.isFollow = isFollow;
notifyPropertyChanged(BR.follow);
}
@Bindable
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
notifyPropertyChanged(BR.userName);
}
@Bindable
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
notifyPropertyChanged(BR.age);
}
@Bindable
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
notifyPropertyChanged(BR.realName);
}
@Bindable
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
notifyPropertyChanged(BR.mobile);
}
}
| 19.011494 | 49 | 0.623942 |
74d9600bf8352778bfe7d85ba30e0e375b467d4a | 2,967 | package RoboRaiders.Robot;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
/**
* PidIpdReceiver - will facilitate the sending and receiving of PID values
*
*/
public class PidUdpReceiver
{
private int port;
private double p, i, d, degrees, direction;
private Thread backgroundThread;
public PidUdpReceiver(int port)
{
this.port = port;
}
public PidUdpReceiver()
{
this(8087);
}
public void beginListening()
{
backgroundThread = new Thread(new Runnable()
{
@Override
public void run()
{
listen();
}
});
backgroundThread.start();
}
public void shutdown()
{
backgroundThread.interrupt();
}
public synchronized double getP()
{
return p;
}
public synchronized double getI()
{
return i;
}
public synchronized double getD()
{
return d;
}
public synchronized double getDegrees()
{
return degrees;
}
public synchronized double getDirection() { return direction; }
private void listen()
{
try
{
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] packet = new byte[40];
System.out.printf("Listening on udp:%s:%d%n", InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(packet, packet.length);
while (!Thread.currentThread().isInterrupted())
{
serverSocket.receive(receivePacket);
byte[] pVal = new byte[8];
byte[] iVal = new byte[8];
byte[] dVal = new byte[8];
byte[] degVal = new byte[8];
byte[] dirVal = new byte[8];
// System.out.printf("Byte array packet %n");
// for (byte b : packet) {
// String st = String.format("%02X", b);
// System.out.printf(st);
// }
// System.out.printf("%n");
System.arraycopy(packet, 0, pVal, 0, 8);
System.arraycopy(packet, 8, iVal, 0, 8);
System.arraycopy(packet, 16, dVal, 0, 8);
System.arraycopy(packet, 24, degVal, 0, 8);
System.arraycopy(packet, 32, dirVal, 0, 8);
p = toDouble(pVal);
i = toDouble(iVal);
d = toDouble(dVal);
degrees = toDouble(degVal);
direction = toDouble(dirVal);
}
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private double toDouble(byte[] bytes)
{
return ByteBuffer.wrap(bytes).getDouble();
}
} | 23.736 | 109 | 0.522076 |
05b474396ee18b60fbe8fa72cd7d3bebe84cd7ce | 3,587 | package org.apache.xmlbeans.impl.jam.internal.elements;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import org.apache.xmlbeans.impl.jam.JClass;
import org.apache.xmlbeans.impl.jam.JMethod;
import org.apache.xmlbeans.impl.jam.JParameter;
import org.apache.xmlbeans.impl.jam.internal.classrefs.DirectJClassRef;
import org.apache.xmlbeans.impl.jam.internal.classrefs.JClassRef;
import org.apache.xmlbeans.impl.jam.internal.classrefs.JClassRefContext;
import org.apache.xmlbeans.impl.jam.internal.classrefs.QualifiedJClassRef;
import org.apache.xmlbeans.impl.jam.internal.classrefs.UnqualifiedJClassRef;
import org.apache.xmlbeans.impl.jam.internal.elements.ClassImpl;
import org.apache.xmlbeans.impl.jam.internal.elements.InvokableImpl;
import org.apache.xmlbeans.impl.jam.mutable.MMethod;
import org.apache.xmlbeans.impl.jam.visitor.JVisitor;
import org.apache.xmlbeans.impl.jam.visitor.MVisitor;
public final class MethodImpl extends InvokableImpl implements MMethod {
private JClassRef mReturnTypeRef = null;
MethodImpl(String simpleName, ClassImpl containingClass) {
super(containingClass);
this.setSimpleName(simpleName);
}
public void setReturnType(String className) {
this.mReturnTypeRef = QualifiedJClassRef.create(className, (JClassRefContext)((ClassImpl)this.getContainingClass()));
}
public void setUnqualifiedReturnType(String unqualifiedTypeName) {
this.mReturnTypeRef = UnqualifiedJClassRef.create(unqualifiedTypeName, (ClassImpl)this.getContainingClass());
}
public void setReturnType(JClass c) {
this.mReturnTypeRef = DirectJClassRef.create(c);
}
public JClass getReturnType() {
return this.mReturnTypeRef == null?this.getClassLoader().loadClass("void"):this.mReturnTypeRef.getRefClass();
}
public boolean isFinal() {
return Modifier.isFinal(this.getModifiers());
}
public boolean isStatic() {
return Modifier.isStatic(this.getModifiers());
}
public boolean isAbstract() {
return Modifier.isAbstract(this.getModifiers());
}
public boolean isNative() {
return Modifier.isNative(this.getModifiers());
}
public boolean isSynchronized() {
return Modifier.isSynchronized(this.getModifiers());
}
public void accept(MVisitor visitor) {
visitor.visit((MMethod)this);
}
public void accept(JVisitor visitor) {
visitor.visit((JMethod)this);
}
public String getQualifiedName() {
StringWriter sbuf = new StringWriter();
sbuf.write(Modifier.toString(this.getModifiers()));
sbuf.write(32);
JClass returnJClass = this.getReturnType();
if(returnJClass == null) {
sbuf.write("void ");
} else {
sbuf.write(returnJClass.getQualifiedName());
sbuf.write(32);
}
sbuf.write(this.getSimpleName());
sbuf.write(40);
JParameter[] thrown = this.getParameters();
int i;
if(thrown != null && thrown.length > 0) {
for(i = 0; i < thrown.length; ++i) {
sbuf.write(thrown[i].getType().getQualifiedName());
if(i < thrown.length - 1) {
sbuf.write(44);
}
}
}
sbuf.write(41);
JClass[] var5 = this.getExceptionTypes();
if(var5 != null && var5.length > 0) {
sbuf.write(" throws ");
for(i = 0; i < var5.length; ++i) {
sbuf.write(var5[i].getQualifiedName());
if(i < var5.length - 1) {
sbuf.write(44);
}
}
}
return sbuf.toString();
}
}
| 31.464912 | 123 | 0.679677 |
6dd108584bd242662c9d5263da4dcd9be385d5d3 | 3,645 | package com.stripe.android.payments.core.injection;
import java.lang.System;
/**
* Provides dependencies for 3ds2 transaction.
*/
@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000\u001a\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\b!\u0018\u0000 \u00072\u00020\u0001:\u0001\u0007B\u0005\u00a2\u0006\u0002\u0010\u0002J\u0010\u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u0006H\'\u00a8\u0006\b"}, d2 = {"Lcom/stripe/android/payments/core/injection/Stripe3ds2TransactionModule;", "", "()V", "bindsStripe3ds2ChallengeResultProcessor", "Lcom/stripe/android/payments/core/authentication/threeds2/Stripe3ds2ChallengeResultProcessor;", "defaultStripe3ds2ChallengeResultProcessor", "Lcom/stripe/android/payments/core/authentication/threeds2/DefaultStripe3ds2ChallengeResultProcessor;", "Companion", "payments-core_release"})
@dagger.Module(subcomponents = {com.stripe.android.payments.core.injection.Stripe3ds2TransactionViewModelSubcomponent.class})
public abstract class Stripe3ds2TransactionModule {
@org.jetbrains.annotations.NotNull()
public static final com.stripe.android.payments.core.injection.Stripe3ds2TransactionModule.Companion Companion = null;
public Stripe3ds2TransactionModule() {
super();
}
@org.jetbrains.annotations.NotNull()
@dagger.Binds()
public abstract com.stripe.android.payments.core.authentication.threeds2.Stripe3ds2ChallengeResultProcessor bindsStripe3ds2ChallengeResultProcessor(@org.jetbrains.annotations.NotNull()
com.stripe.android.payments.core.authentication.threeds2.DefaultStripe3ds2ChallengeResultProcessor defaultStripe3ds2ChallengeResultProcessor);
@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000*\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000b\n\u0000\n\u0002\u0018\u0002\n\u0000\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002J\b\u0010\u0003\u001a\u00020\u0004H\u0007J$\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u0007\u001a\u00020\b2\b\b\u0001\u0010\t\u001a\u00020\n2\b\b\u0001\u0010\u000b\u001a\u00020\fH\u0007\u00a8\u0006\r"}, d2 = {"Lcom/stripe/android/payments/core/injection/Stripe3ds2TransactionModule$Companion;", "", "()V", "provideMessageVersionRegistry", "Lcom/stripe/android/stripe3ds2/transaction/MessageVersionRegistry;", "provideStripeThreeDs2Service", "Lcom/stripe/android/stripe3ds2/service/StripeThreeDs2Service;", "context", "Landroid/content/Context;", "enableLogging", "", "workContext", "Lkotlin/coroutines/CoroutineContext;", "payments-core_release"})
public static final class Companion {
private Companion() {
super();
}
@org.jetbrains.annotations.NotNull()
@javax.inject.Singleton()
@dagger.Provides()
public final com.stripe.android.stripe3ds2.transaction.MessageVersionRegistry provideMessageVersionRegistry() {
return null;
}
@org.jetbrains.annotations.NotNull()
@javax.inject.Singleton()
@dagger.Provides()
public final com.stripe.android.stripe3ds2.service.StripeThreeDs2Service provideStripeThreeDs2Service(@org.jetbrains.annotations.NotNull()
android.content.Context context, @javax.inject.Named(value = "enableLogging")
boolean enableLogging, @org.jetbrains.annotations.NotNull()
@IOContext()
kotlin.coroutines.CoroutineContext workContext) {
return null;
}
}
} | 75.9375 | 988 | 0.754184 |
bb7a8742a955f9f0f3b847a1665e4682202ba3fb | 2,212 | /*
* Copyright © 2017 camunda services GmbH (info@camunda.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.zeebe.client.impl.response;
import io.zeebe.client.api.response.BrokerInfo;
import io.zeebe.client.api.response.PartitionInfo;
import io.zeebe.gateway.protocol.GatewayOuterClass;
import java.util.ArrayList;
import java.util.List;
public final class BrokerInfoImpl implements BrokerInfo {
private final int nodeId;
private final String host;
private final int port;
private final String version;
private final List<PartitionInfo> partitions;
public BrokerInfoImpl(final GatewayOuterClass.BrokerInfo broker) {
nodeId = broker.getNodeId();
host = broker.getHost();
port = broker.getPort();
version = broker.getVersion();
partitions = new ArrayList<>();
for (final GatewayOuterClass.Partition partition : broker.getPartitionsList()) {
partitions.add(new PartitionInfoImpl(partition));
}
}
@Override
public int getNodeId() {
return nodeId;
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public String getAddress() {
return String.format("%s:%d", host, port);
}
@Override
public String getVersion() {
return version;
}
@Override
public List<PartitionInfo> getPartitions() {
return partitions;
}
@Override
public String toString() {
return "BrokerInfoImpl{"
+ "nodeId="
+ nodeId
+ ", host='"
+ host
+ '\''
+ ", port="
+ port
+ ", version="
+ version
+ ", partitions="
+ partitions
+ '}';
}
}
| 24.307692 | 84 | 0.671338 |
7246bc35cdc6b724f7b698c0d311c3fc28c4896f | 1,674 | package cn.edu.fudan.dsm.tslrm;
import cn.edu.fudan.dsm.tslrm.data.ForexData;
import java.io.Serializable;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: wangyang
* Date: 13-6-30
* Time: 上午10:42
* To change this template use File | Settings | File Templates.
*/
public class ForexCorrelation implements Serializable {
public String currencyX;
public String currencyY; // y = kx + b
public double error;
public double k;
public double b;
public int maxLength;
public transient ForexData forexDataX;
public transient ForexData forexDataY;
public Set<Integer> positions;
public ForexCorrelation(String currencyX, String currencyY, double error, double k, double b, int maxLength, ForexData forexDataX, ForexData forexDataY, Set<Integer> positions) {
this.currencyX = currencyX;
this.currencyY = currencyY;
this.error = error;
this.k = k;
this.b = b;
this.maxLength = maxLength;
this.forexDataX = forexDataX;
this.forexDataY = forexDataY;
this.positions = positions;
}
@Override
public String toString() {
return "ForexCorrelation{" +
"currencyX='" + currencyX + '\'' +
", currencyY='" + currencyY + '\'' +
", error=" + error +
", k=" + k +
", b=" + b +
", maxLength=" + maxLength +
", forexDataX=" + forexDataX +
", forexDataY=" + forexDataY +
", positions.size()=" + positions.size() +
'}';
}
}
| 30.436364 | 183 | 0.565114 |
3ff38ffe461501ebea0e07c2aa41eff7f0314546 | 581 | package net.atos.tenderingportal.domain.enums;
public enum Role {
SCRUMMASTER("SCRUM MASTER"),
DEVELOPER("DEVELOPER"),
TESTER("TESTER");
private String value;
Role(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static Role roleOf(String value){
if (value != null){
for (Role role: Role.values()){
if (value.equalsIgnoreCase(role.getValue())){
return role;
}
}
}
return null;
}
}
| 20.034483 | 61 | 0.523236 |
207e58f1781c538bf5b3aa67fa64cb3b40f80632 | 72 | package lk.ijse.dep.webmvc.services;
public interface SuperService {
}
| 14.4 | 36 | 0.791667 |
44364f53bd0492479c1dfb52a05d313e48222d42 | 5,841 | /*
* Copyright 2022 Starwhale, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.starwhale.test.domain.job;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import ai.starwhale.mlops.domain.job.JobType;
import ai.starwhale.mlops.domain.job.bo.Job;
import ai.starwhale.mlops.domain.job.bo.JobRuntime;
import ai.starwhale.mlops.domain.job.converter.JobBoConverter;
import ai.starwhale.mlops.domain.job.mapper.JobSWDSVersionMapper;
import ai.starwhale.mlops.domain.job.po.JobEntity;
import ai.starwhale.mlops.domain.job.status.JobStatus;
import ai.starwhale.mlops.domain.node.Device;
import ai.starwhale.mlops.domain.node.Device.Clazz;
import ai.starwhale.mlops.domain.runtime.mapper.RuntimeMapper;
import ai.starwhale.mlops.domain.runtime.mapper.RuntimeVersionMapper;
import ai.starwhale.mlops.domain.runtime.po.RuntimeEntity;
import ai.starwhale.mlops.domain.runtime.po.RuntimeVersionEntity;
import ai.starwhale.mlops.domain.swds.bo.SWDataSet;
import ai.starwhale.mlops.domain.swds.po.SWDatasetVersionEntity;
import ai.starwhale.mlops.domain.swmp.SWModelPackage;
import ai.starwhale.mlops.domain.swmp.mapper.SWModelPackageMapper;
import ai.starwhale.mlops.domain.swmp.po.SWModelPackageEntity;
import ai.starwhale.mlops.domain.swmp.po.SWModelPackageVersionEntity;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* a test for {@link JobBoConverter}
*/
public class JobBoConverterTest {
@Test
public void testJobBoConverter(){
JobEntity jobEntity = JobEntity.builder()
.id(1L)
.deviceAmount(1)
.deviceType(Clazz.CPU.getValue())
.jobStatus(JobStatus.RUNNING)
.type(JobType.EVALUATION)
.swmpVersionId(1L)
.swmpVersion(SWModelPackageVersionEntity.builder().id(1L).swmpId(1L).versionName("swmpvname").storagePath("swmp_path").build())
.resultOutputPath("job_result")
.jobUuid(UUID.randomUUID().toString())
.runtimeVersionId(1L)
.build();
JobSWDSVersionMapper jobSWDSVersionMapper = mock(JobSWDSVersionMapper.class);
when(jobSWDSVersionMapper.listSWDSVersionsByJobId(jobEntity.getId())).thenReturn(List.of(
SWDatasetVersionEntity.builder().id(1L).storagePath("path_swds").versionMeta("version_swds").versionName("name_swds").build()
,SWDatasetVersionEntity.builder().id(2L).storagePath("path_swds1").versionMeta("version_swds1").versionName("name_swds1").build()
));
SWModelPackageMapper swModelPackageMapper = mock(SWModelPackageMapper.class);
SWModelPackageEntity swModelPackageEntity = SWModelPackageEntity.builder().swmpName("name_swmp")
.build();
when(swModelPackageMapper.findSWModelPackageById(
jobEntity.getSwmpVersion().getSwmpId())).thenReturn(swModelPackageEntity);
RuntimeVersionMapper runtimeVersionMapper = mock(RuntimeVersionMapper.class);
RuntimeVersionEntity runtimeVersionEntity = RuntimeVersionEntity.builder().versionName("name_swrt_version").runtimeId(1L).storagePath("swrt_path").build();
when(runtimeVersionMapper.findVersionById(
jobEntity.getRuntimeVersionId())).thenReturn(runtimeVersionEntity);
RuntimeMapper runtimeMapper = mock(RuntimeMapper.class);
RuntimeEntity runtimeEntity = RuntimeEntity.builder().runtimeName("name_swrt").build();
when(runtimeMapper.findRuntimeById(
runtimeVersionEntity.getRuntimeId())).thenReturn(runtimeEntity);
JobBoConverter jobBoConverter = new JobBoConverter(jobSWDSVersionMapper,swModelPackageMapper,runtimeMapper,runtimeVersionMapper);
Job job = jobBoConverter.fromEntity(jobEntity);
Assertions.assertEquals(jobEntity.getJobStatus(),job.getStatus());
Assertions.assertEquals(jobEntity.getId(),job.getId());
Assertions.assertEquals(jobEntity.getType(),job.getType());
Assertions.assertEquals(jobEntity.getResultOutputPath(),job.getResultDir());
Assertions.assertEquals(jobEntity.getJobUuid(),job.getUuid());
JobRuntime swrt = job.getJobRuntime();
Assertions.assertNotNull(swrt);
Assertions.assertEquals(runtimeVersionEntity.getVersionName(),swrt.getVersion());
Assertions.assertEquals(runtimeEntity.getRuntimeName(),swrt.getName());
Assertions.assertEquals(runtimeVersionEntity.getStoragePath(),swrt.getStoragePath());
Assertions.assertEquals(jobEntity.getDeviceAmount(),swrt.getDeviceAmount());
Assertions.assertEquals(jobEntity.getDeviceType(),swrt.getDeviceClass().getValue());
SWModelPackage swmp = job.getSwmp();
Assertions.assertNotNull(swmp);
Assertions.assertEquals(jobEntity.getSwmpVersion().getVersionName(),swmp.getVersion());
Assertions.assertEquals(jobEntity.getSwmpVersion().getId(),swmp.getId());
Assertions.assertEquals(swModelPackageEntity.getSwmpName(),swmp.getName());
Assertions.assertEquals(jobEntity.getSwmpVersion().getStoragePath(),swmp.getPath());
List<SWDataSet> swDataSets = job.getSwDataSets();
Assertions.assertNotNull(swDataSets);
Assertions.assertEquals(2, swDataSets.size());
}
}
| 49.084034 | 163 | 0.746619 |
0cc8019023f7027ae70ca23381986c2b9ef555a9 | 1,441 | package com.dyz.gameserver.commons.message;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dyz.gameserver.commons.session.GameSession;
import com.dyz.gameserver.msg.processor.common.INotAuthProcessor;
import com.dyz.gameserver.msg.processor.common.MsgProcessor;
import com.dyz.gameserver.msg.processor.common.MsgProcessorRegister;
/**
* 消息分发器,根据消息号,找到相应的消息处理器
* @author dyz
*
*/
public class MsgDispatcher {
private static final Logger logger = LoggerFactory.getLogger(MsgDispatcher.class);
private Map<Integer, MsgProcessor> processorsMap = new HashMap<Integer, MsgProcessor>();
public MsgDispatcher(){
for(MsgProcessorRegister register :MsgProcessorRegister.values()){
processorsMap.put(register.getMsgCode(), register.getMsgProcessor());
}
logger.info("初始化 消息处理器成功。。。");
}
public MsgProcessor getMsgProcessor(int msgCode){
return processorsMap.get(msgCode);
}
public void dispatchMsg( GameSession gameSession,ClientRequest clientRequest) {
int msgCode = clientRequest.getMsgCode();
if(msgCode == 1000){//客户端请求断开链接
gameSession.close();
}
if(msgCode%2==0){//请求协议号必须是奇数
return;
}
MsgProcessor processor = getMsgProcessor(msgCode);
if(gameSession.isLogin() || processor instanceof INotAuthProcessor){
processor.handle(gameSession, clientRequest);
}
}
}
| 27.188679 | 90 | 0.736988 |
3624bc555d843a1d4e4f84ad85bbae172d0babf6 | 7,787 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.bsc.maven.reporting.renderer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.doxia.sink.Sink;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.report.projectinfo.ProjectInfoReportUtils;
import org.apache.maven.reporting.AbstractMavenReportRenderer;
import org.codehaus.plexus.i18n.I18N;
import org.codehaus.plexus.util.StringUtils;
/**
*
* @author bsorrentino
*/
public class PluginsRenderer extends AbstractMavenReportRenderer
{
private final Log log;
private final List<Artifact> plugins;
private final List<Artifact> reports;
private final Locale locale;
private final I18N i18n;
private final MavenProject project;
private final MavenProjectBuilder mavenProjectBuilder;
private final ArtifactFactory artifactFactory;
private final ArtifactRepository localRepository;
/**
* @param log
* @param sink
* @param locale
* @param i18n
* @param plugins
* @param reports
* @param project
* @param mavenProjectBuilder
* @param artifactFactory
* @param localRepository
*/
public PluginsRenderer(
Log log,
Sink sink,
Locale locale,
I18N i18n,
Set<Artifact> plugins,
Set<Artifact> reports,
MavenProject project,
MavenProjectBuilder mavenProjectBuilder,
ArtifactFactory artifactFactory,
ArtifactRepository localRepository )
{
super( sink );
this.log = log;
this.locale = locale;
this.plugins = new ArrayList<>( plugins );
this.reports = new ArrayList<>( reports );
this.i18n = i18n;
this.project = project;
this.mavenProjectBuilder = mavenProjectBuilder;
this.artifactFactory = artifactFactory;
this.localRepository = localRepository;
}
/** {@inheritDoc} */
public String getTitle()
{
return getReportString( "report.plugins.title" );
}
/** {@inheritDoc} */
public void renderBody()
{
// === Section: Project Plugins.
renderSectionPlugins( true );
// === Section: Project Reports.
renderSectionPlugins( false );
}
/**
* @param isPlugins <code>true</code> to use <code>plugins</code> variable, <code>false</code> to use
* <code>reports</code> variable.
*/
private void renderSectionPlugins( boolean isPlugins )
{
List<Artifact> list = ( isPlugins ? plugins : reports );
String[] tableHeader = getPluginTableHeader();
startSection( ( isPlugins ? getReportString( "report.plugins.title" )
: getReportString( "report.plugins.report.title" ) ) );
if ( list == null || list.isEmpty() )
{
paragraph( ( isPlugins ? getReportString( "report.plugins.nolist" )
: getReportString( "report.plugins.report.nolist" ) ) );
endSection();
return;
}
Collections.sort( list, getArtifactComparator() );
startTable();
tableHeader( tableHeader );
for ( Iterator<Artifact> iterator = list.iterator(); iterator.hasNext(); )
{
Artifact artifact = (Artifact) iterator.next();
VersionRange versionRange;
if ( StringUtils.isEmpty( artifact.getVersion() ) )
{
versionRange = VersionRange.createFromVersion( Artifact.RELEASE_VERSION );
}
else
{
versionRange = VersionRange.createFromVersion( artifact.getVersion() );
}
Artifact pluginArtifact = artifactFactory.createParentArtifact( artifact.getGroupId(), artifact
.getArtifactId(), versionRange.toString() );
List<?> artifactRepositories = project.getPluginArtifactRepositories();
if ( artifactRepositories == null )
{
artifactRepositories = new ArrayList<>();
}
try
{
MavenProject pluginProject = mavenProjectBuilder.buildFromRepository( pluginArtifact,
artifactRepositories,
localRepository );
tableRow( getPluginRow( pluginProject.getGroupId(), pluginProject.getArtifactId(), pluginProject
.getVersion(), pluginProject.getUrl() ) );
}
catch ( ProjectBuildingException e )
{
log.info( "Could not build project for: " + artifact.getArtifactId() + ":" + e.getMessage(), e );
tableRow( getPluginRow( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(),
null ) );
}
}
endTable();
endSection();
}
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
private String[] getPluginTableHeader()
{
// reused key...
String groupId = getReportString( "report.dependencyManagement.column.groupId" );
String artifactId = getReportString( "report.dependencyManagement.column.artifactId" );
String version = getReportString( "report.dependencyManagement.column.version" );
return new String[] { groupId, artifactId, version };
}
private String[] getPluginRow( String groupId, String artifactId, String version, String link )
{
artifactId = ProjectInfoReportUtils.getArtifactIdCell( artifactId, link );
return new String[] { groupId, artifactId, version };
}
private Comparator<Artifact> getArtifactComparator()
{
return new Comparator<Artifact>()
{
/** {@inheritDoc} */
public int compare( Artifact a1, Artifact a2 )
{
int result = a1.getGroupId().compareTo( a2.getGroupId() );
if ( result == 0 )
{
result = a1.getArtifactId().compareTo( a2.getArtifactId() );
}
return result;
}
};
}
private String getReportString( String key )
{
return i18n.getString( "project-info-report", locale, key );
}
}
| 34.303965 | 117 | 0.540516 |
20c640f7f8cfb115faca633a041803a581c6ba5a | 2,444 | package com.hackday.dmyphotogridview_parkhyerim;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
/**
* Created by hyerim on 2018. 5. 17....
*/
public class BaseActivity extends AppCompatActivity {
private final static String TAG = BaseActivity.class.getSimpleName();
private static final int REQUEST_READ_STORAGE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onRestart() {
super.onRestart();
}
protected void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestStoragePermission();
} else {
onPermissionGranted();
}
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_STORAGE);
}
protected void onPermissionGranted() {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_READ_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted();
} else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_LONG).show();
requestStoragePermission();
}
}
}
}
}
| 29.095238 | 141 | 0.657529 |
6e084f3da87c48472dd4345c2cde22b322ae4bcf | 1,419 | package com.github.yoma.core.service;
import java.util.List;
import com.github.yoma.core.dao.CoreRoleMenuDao;
import com.github.yoma.core.domain.CoreRoleMenu;
import com.github.yoma.core.dto.CoreRoleMenuQueryDTO;
import com.github.yoma.common.persistence.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageInfo;
/**
* 角色菜单 业务层
*
* @author 马世豪
* @version 2020-04-07
*/
@Service
@Transactional(readOnly = true)
public class CoreRoleMenuService extends CrudService<CoreRoleMenuDao, CoreRoleMenu> {
@Override
public CoreRoleMenu get(Long id) {
return super.get(id);
}
public List<CoreRoleMenu> findList(CoreRoleMenuQueryDTO queryDTO) {
return super.findList(queryDTO);
}
public PageInfo<CoreRoleMenu> findPage(CoreRoleMenuQueryDTO queryDTO) {
return super.findPage(queryDTO);
}
@Transactional(readOnly = false)
public int batchDelete(CoreRoleMenuQueryDTO queryDTO) {
int count = this.dao.batchDelete(queryDTO);
return count;
}
@Transactional(readOnly = false)
@Override
public void save(CoreRoleMenu coreRoleMenu) {
super.save(coreRoleMenu);
}
@Transactional(readOnly = false)
@Override
public int delete(CoreRoleMenu coreRoleMenu) {
return super.delete(coreRoleMenu);
}
}
| 25.8 | 85 | 0.727977 |
0782559036f31fa84778fcfdb5cb2c4070cfce93 | 530 | package ru.job4j.list.cycle;
/**
* @author Aleksey Kornetov (all-1313@yandex.ru)
* project junior
* Created on 05.07.2018.
*/
public class Cycle {
public boolean hasCycle(Node first) {
boolean res = false;
if (first != null && first.next != null && first.next.next != null) {
Node second = first.next.next;
while (second != null && second.next != null) {
if (first == second) {
res = true;
break;
}
first = first.next;
second = second.next.next;
}
}
return res;
}
}
| 21.2 | 71 | 0.586792 |
59ceab291b7cffd46538603bba780070affe3733 | 1,667 | package de.ck35.raspberry.happy.chameleon.terrarium.jpa;
import javax.persistence.EntityListeners;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
/**
* Entity listener which allows dependency injection inside entities.
* The listener can be registered via {@link EntityListeners} annotation.
*
* Dependency injection annotations like {@link Autowired} are supported.
*
* @author Christian Kaspari
* @since 1.0.0
*/
public class SpringEntityListener {
private static final Logger LOG = LoggerFactory.getLogger(SpringEntityListener.class);
private static final SpringEntityListener INSTANCE = new SpringEntityListener();
private volatile AutowireCapableBeanFactory beanFactory;
public static SpringEntityListener get() {
return INSTANCE;
}
public AutowireCapableBeanFactory getBeanFactory() {
return beanFactory;
}
public void setBeanFactory(AutowireCapableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@PostLoad
@PostPersist
public void inject(Object object) {
AutowireCapableBeanFactory beanFactory = get().getBeanFactory();
if(beanFactory == null) {
LOG.warn("Bean Factory not set! Depdendencies will not be injected into: '{}'", object);
return;
}
LOG.debug("Injecting dependencies into entity: '{}'.", object);
beanFactory.autowireBean(object);
}
} | 32.686275 | 100 | 0.725855 |
8648b782b74f079470f499b095b2397b7e9c0756 | 5,219 | package com.shareyi.molicode.interceptor;
import com.google.common.collect.Lists;
import com.shareyi.molicode.common.bean.LoginContext;
import com.shareyi.molicode.common.constants.CacheKeyConstant;
import com.shareyi.molicode.common.constants.CommonConstant;
import com.shareyi.molicode.common.utils.CookieUtils;
import com.shareyi.molicode.common.utils.ThreadLocalHolder;
import com.shareyi.molicode.domain.sys.AcUser;
import com.shareyi.molicode.manager.sys.AcUserManager;
import com.shareyi.molicode.service.common.CacheService;
import com.shareyi.molicode.service.common.CipherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
* 登录拦截
*
* @author david
* @date 2019/7/3
*/
@Service
public class LoginInterceptor extends BaseAbstractInterceptor implements HandlerInterceptor {
/**
* 请求token
*/
public static final String TOKEN_KEY = "token";
@Resource
private CipherService cipherService;
/**
* 忽略的url前缀
*/
private List<String> excludeUrlList = Lists.newArrayList("/dist/", "/loginfree/", "/error");
@Resource(name = "guavaCacheService")
private CacheService cacheService;
@Resource
private AcUserManager acUserManager;
/**
* 启用token模式
*/
@Value("${request.token.value:}")
private String tokenValue;
/**
* token模式的映射用户
*/
@Value("${request.token.userName:admin}")
private String tokenUserName;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
//如果是资源请求,如ResourceHttpRequestHandler, 直接返回true
if (!(handler instanceof HandlerMethod)) {
return true;
}
String url = httpServletRequest.getRequestURI();
for (String excludeUrl : excludeUrlList) {
if (url.startsWith(excludeUrl)) {
return true;
}
}
String reqToken = httpServletRequest.getParameter(TOKEN_KEY);
if (StringUtils.isNotBlank(tokenValue) && StringUtils.isNotBlank(reqToken)) {
if (Objects.equals(tokenValue, reqToken)) {
LoginContext loginContext = LoginContext.buildByUserName(tokenUserName);
loginContext.setByToken(true);
if (loadUserInfo(httpServletRequest, httpServletResponse, loginContext)) {
return true;
}
}
}
String loginStr = CookieUtils.getCookieValue(httpServletRequest, CommonConstant.MOLI_LOGIN_KEY);
if (StringUtils.isEmpty(loginStr)) {
responseNoAuth(httpServletRequest, httpServletResponse, true, StringUtils.EMPTY);
return false;
}
try {
String decryptStr = cipherService.decryptByRSA(loginStr);
LoginContext loginContext = LoginContext.buildByLoginInfo(decryptStr);
if (!loadUserInfo(httpServletRequest, httpServletResponse, loginContext)) {
return false;
}
} catch (Exception e) {
responseNoAuth(httpServletRequest, httpServletResponse, true, StringUtils.EMPTY);
return false;
}
return true;
}
private boolean loadUserInfo(HttpServletRequest request, HttpServletResponse response, LoginContext loginContext) throws IOException {
AcUser acUser = this.loadAcUserByUserName(loginContext.getUserName());
if (acUser == null || !loginContext.checkDataVersion(acUser.getDataVersion())) {
responseNoAuth(request, response, true, StringUtils.EMPTY);
return false;
}
loginContext.putExtInfo(CommonConstant.LoginContext.AC_USER, acUser);
ThreadLocalHolder.putRequestThreadInfo(CommonConstant.MOLI_LOGIN_KEY, loginContext);
return true;
}
/**
* 通过用户名称查询用户信息
*
* @param userName
* @return
*/
private AcUser loadAcUserByUserName(String userName) {
String cacheKey = CacheKeyConstant.getAcUserCacheKey(userName);
AcUser acUser = (AcUser) cacheService.getShortTime(cacheKey);
if (acUser != null) {
return acUser;
}
acUser = acUserManager.getByUserName(userName);
if (acUser == null) {
return acUser;
}
cacheService.saveShortTime(cacheKey, acUser);
return acUser;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
| 35.993103 | 162 | 0.695727 |
172cea5ad7d87d2355adcb48fa14cff410cd3a0a | 2,134 | /*
* Copyright 2013 Agorava
*
* 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.agorava.socializer;
import org.agorava.api.event.SocialEvent;
import org.agorava.api.event.StatusUpdated;
import org.agorava.linkedin.LinkedIn;
import org.agorava.linkedin.NetworkUpdateService;
import org.agorava.linkedin.model.NewShare;
import org.agorava.linkedin.model.NewShare.NewShareVisibility;
import org.agorava.linkedin.model.NewShare.NewShareVisibilityCode;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
//import org.jboss.solder.logging.Logger;
/**
* @author Antoine Sabot-Durand
*/
@Named
@RequestScoped
public class LinkedInController {
@Produces
@Named
private NewShare linkedInShare;
@Inject
@LinkedIn
private NetworkUpdateService updateService;
/* @Inject
Logger log;*/
@PostConstruct
public void init() {
linkedInShare = new NewShare("", null, new NewShareVisibility(NewShareVisibilityCode.CONNECTIONS_ONLY));
}
public String sendUpdate() {
updateService.share(linkedInShare);
return "ok";
}
protected void statusUpdateObserver(@Observes @LinkedIn StatusUpdated statusUpdate) {
if (statusUpdate.getStatus().equals(SocialEvent.Status.SUCCESS)) {
// log.debugf("Status update with : %s ", statusUpdate.getMessage());
init();
}
}
}
| 29.638889 | 113 | 0.711809 |
782e29535d86410958fc565357e03bdc174eec4e | 2,450 | package my.netty.rpc.compiler;
import javax.tools.*;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import java.util.Locale;
public class NativeCompiler implements Closeable {
private final File tempFolder;
private final URLClassLoader classLoader;
// Java URLClassLoader 和 ClassLoader类加载器:https://www.cnblogs.com/rogge7/p/7766522.html
NativeCompiler(File tempFolder) {
this.tempFolder = tempFolder;
this.classLoader = createClassLoader(tempFolder);
}
private static URLClassLoader createClassLoader(File tempFolder) {
try {
URL[] urls = {tempFolder.toURI().toURL()};
return new URLClassLoader(urls);
} catch (Exception e) {
throw new AssertionError(e);
}
}
public Class<?> compile(String className, String code) {
try {
JavaFileObject sourceFile = new StringJavaFileObject(className, code);
compileClass(sourceFile);
return classLoader.loadClass(className);
} catch (Exception e) {
throw new AssertionError(e);
}
}
private void compileClass(JavaFileObject sourceFile) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>(); // DiagnosticCollector实现了DiagnosticListener接口。
// DiagnosticListener - 诊断信息监听器, 编译过程触发.生成编译task(JavaCompiler#getTask())或获取FileManager(JavaCompiler#getStandardFileManager())时需要传递DiagnosticListener以便收集诊断信息。
// Java动态编译那些事: https://www.jianshu.com/p/44395ef6406f
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(collector, Locale.ROOT, null)) { // try-with-resources是jdk1.7以后才有的语法特性。
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(tempFolder));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, collector, null, null, Collections.singletonList(sourceFile));
task.call();
}
}
@Override
public void close() {
try {
classLoader.close(); // 见包中此方法的注释。
} catch (Exception e) {
throw new AssertionError(e);
}
}
public URLClassLoader getClassLoader() {
return classLoader;
}
}
| 36.567164 | 165 | 0.686122 |
d3f114bb8a0f54b1bef882ecff2fe12d605e9729 | 732 | package io.opensphere.arcgis2.esri;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonSubTypes.Type;
import org.codehaus.jackson.annotate.JsonTypeInfo;
/**
* The Class EsriFieldDomain.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = EsriFieldRangeDomain.class, name = "range"),
@Type(value = EsriFieldCodedValueDomain.class, name = "codedValue"),
@Type(value = EsriFieldInheritedDomain.class, name = "inherited") })
public abstract class EsriFieldDomain implements Serializable
{
/** Serial version UID. */
private static final long serialVersionUID = 1L;
}
| 34.857143 | 96 | 0.762295 |
be48ede845b65a9110fca615324841cffa20bc78 | 433 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for
* license information.
*/
package com.microsoft.azure.spring.messaging.listener;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessageHandler;
public interface AzureMessageHandler extends MessageHandler {
@Nullable
Class<?> getMessagePayloadType();
}
| 25.470588 | 70 | 0.78291 |
4f3358d449739fc2675983d3e47d2f2f28ce67bd | 15,924 | /*
* JBoss, Home of Professional Open Source
* Copyright 2007, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2007,
* @author JBoss Inc.
*/
package com.hp.mwtests.ts.arjuna.reaper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.jboss.byteman.contrib.bmunit.BMScript;
import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.arjuna.ats.arjuna.common.Uid;
import com.arjuna.ats.arjuna.coordinator.TransactionReaper;
/**
* Exercise cancellation behaviour of TransactionReaper with resources
* that time out and, optionally, get wedged either when a cancel is
* tried and/or when an interrupt is delivered
*
* @author Andrew Dinn (adinn@redhat.com), 2007-07-09
*/
@RunWith(BMUnitRunner.class)
@BMScript("reaper")
public class ReaperTestCase2 extends ReaperTestCaseControl
{
@Test
public void testReaper() throws Exception
{
TransactionReaper reaper = TransactionReaper.transactionReaper();
// create slow reapables some of which will not respond immediately
// to cancel requests and ensure that they get cancelled
// and that the reaper does not get wedged
// the rendezvous for the reapables are keyed by the reapable's uid
Uid uid0 = new Uid();
Uid uid1 = new Uid();
Uid uid2 = new Uid();
Uid uid3 = new Uid();
// reapable0 will return CANCELLED from cancel and will rendezvous inside the cancel call
// so we can delay it. prevent_commit should not get called so we don't care about the arguments
TestReapable reapable0 = new TestReapable(uid0, true, true, false, false);
// reapable1 will return CANCELLED from cancel and will not rendezvous inside the cancel call
// prevent_commit should not get called so we don't care about the arguments
TestReapable reapable1 = new TestReapable(uid1, true, false, false, false);
// reapable2 will return RUNNING from cancel and will rendezvous inside the cancel call
// the call will get delayed causing the worker to exit as a zombie
// prevent_commit will be called from the reaper thread and will fail but will not rendezvous
TestReapable reapable2 = new TestReapable(uid2, false, true, false, false);
// reapable3 will return RUNNING from cancel and will not rendezvous inside the cancel call
// prevent_commit should get called and should return true without a rendezvous
TestReapable reapable3 = new TestReapable(uid3, false, false, true, false);
// enable a repeatable rendezvous before checking the reapable queue
enableRendezvous("reaper1", true);
// enable a repeatable rendezvous when synchronizing on a timed out reapoer element so we can check that
// the element is the one we expect.
enableRendezvous("reaper element", true);
// enable a repeatable rendezvous before processing a timed out reapable
// enableRendezvous("reaper2", true);
// enable a repeatable rendezvous before scheduling a reapable in the worker queue for cancellation
// enableRendezvous("reaper3", true);
// enable a repeatable rendezvous before rescheduling a reapable in the worker queue for cancellation
// enableRendezvous("reaper4", true);
// enable a repeatable rendezvous before interrupting a cancelled reapable
// enableRendezvous("reaper5", true);
// enable a repeatable rendezvous before marking a worker thread as a zombie
// enableRendezvous("reaper6", true);
// enable a repeatable rendezvous before marking a reapable as rollback only from the reaper thread
// enableRendezvous("reaper7", true);
// enable a repeatable rendezvous before checking the worker queue
enableRendezvous("reaperworker1", true);
// enable a repeatable rendezvous before marking a reapable as cancel
// enableRendezvous("reaperworker2", true);
// enable a repeatable rendezvous before calling cancel
// enableRendezvous("reaperworker3", true);
// enable a repeatable rendezvous before marking a reapable as rollback only from the worker thread
// enableRendezvous("reaperworker4", true);
// enable a repeatable rendezvous for each of the test reapables which we have marked to
// perform a rendezvous
enableRendezvous(uid0, true);
enableRendezvous(uid2, true);
// STAGE I
// insert two reapables so they timeout at 1 second intervals then stall the first one and
// check progress of cancellations and rollbacks for both
reaper.insert(reapable0, 1);
reaper.insert(reapable1, 1);
//assertTrue(reaper.insert(reapable2, 1));
//assertTrue(reaper.insert(reapable3, 1));
// latch the reaper before it tries to process the queue
triggerRendezvous("reaper1");
// make sure they were all registered
// the transactions queue should be
// UID0 RUNNING
// UID1 RUNNING
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// wait long enough to ensure both reapables have timed out
triggerWait(1000);
// now let the reaper dequeue the first reapable, process it and queue it for the worker thread
// to deal with
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable0
assertTrue(checkAndClearFlag(reapable0));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// latch the reaperworker before it tries to dequeue from the worker queue
triggerRendezvous("reaperworker1");
// the transactions queue should be
// UID1 RUNNING
// UID0 CANCEL
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// now let the worker dequeue a reapable and proceed to call cancel
triggerRendezvous("reaperworker1");
// latch the first reapable inside cancel
triggerRendezvous(uid0);
// now let the reaper check the queue for the second reapable, dequeue it and add it to the
// worker queue
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable1
assertTrue(checkAndClearFlag(reapable1));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// the transactions queue should be
// UID0 CANCEL
// UID1 SCHEDULE_CANCEL
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// ensure we wait long enough for the cancel to time out
triggerWait(500);
// now let the reaper check the queue and interrupt the cancel for UID1
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable0
assertTrue(checkAndClearFlag(reapable0));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// unlatch the first reapable inside cancel
triggerRendezvous(uid0);
// latch the worker as it is about to process the queue again
triggerRendezvous("reaperworker1");
// the transactions queue should be
// UID1 SCHEDULE_CANCEL
assertEquals(1, reaper.numberOfTransactions());
assertEquals(1, reaper.numberOfTimeouts());
// let the worker clear and cancel the 2nd reapable
triggerRendezvous("reaperworker1");
// latch the worker before it reads the worker queue
triggerRendezvous("reaperworker1");
// the transactions queue should be empty
assertEquals(0, reaper.numberOfTransactions());
assertEquals(0, reaper.numberOfTimeouts());
// ensure that cancel was tried on reapable1 and that set rollback only was not tried on either
// we know cancel was tried on reapable0 because we got through the rendezvous
assertTrue(reapable1.getCancelTried());
assertTrue(!reapable0.getRollbackTried());
assertTrue(!reapable1.getRollbackTried());
assertTrue(checkAndClearFlag("interrupted"));
// STAGE II
// now use the next pair of reapables to check that a wedged reaperworker gets tuirned into a zombie and
// a new worker gets created to cancel the remaining reapables.
// insert reapables so they timeout at 1 second intervals then
// check progress of cancellations and rollbacks
reaper.insert(reapable2, 1);
reaper.insert(reapable3, 1);
// make sure they were all registered
// the transactions queue should be
// UID2 RUNNING
// UID3 RUNNING
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// wait long enough to ensure both reapables have timed out
triggerWait(1000);
// now let the reaper dequeue the first reapable, process it and queue it for the worker thread
// to deal with
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable2
assertTrue(checkAndClearFlag(reapable2));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// the transactions queue should be
// UID3 RUNNING
// UID2 CANCEL
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// now let the worker dequeue the fourth reapable and proceed to call cancel
triggerRendezvous("reaperworker1");
// latch the third reapable inside cancel
triggerRendezvous(uid2);
// now let the reaper check the queue for the fourth reapable, dequeue it and add it to the
// worker queue
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable3
assertTrue(checkAndClearFlag(reapable3));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// the transactions queue should be
// UID2 CANCEL
// UID3 SCHEDULE_CANCEL
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// ensure we wait long enough for the cancel to time out
triggerWait(500);
// now let the reaper check the queue and interrupt the cancel for UID3
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable2
assertTrue(checkAndClearFlag(reapable2));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
assertTrue(checkAndClearFlag("interrupted"));
// ensure we wait long enough for the cancel to time out
triggerWait(500);
// the transactions queue should be
// UID3 SCHEDULE_CANCEL
// UID2 CANCEL_INTERRUPTED
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// let the reaper check the queue and reschedule the fourth reapable
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable3
assertTrue(checkAndClearFlag(reapable3));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// the transactions queue should be
// UID2 CANCEL_INTERRUPTED
// UID3 SCHEDULE_CANCEL
assertEquals(2, reaper.numberOfTransactions());
assertEquals(2, reaper.numberOfTimeouts());
// let the reaper check the queue and mark the reaper worker as a zombie
triggerRendezvous("reaper1");
// latch the reaper at the reaper element check
triggerRendezvous("reaper element");
// check that we have dequeued reapable2
assertTrue(checkAndClearFlag(reapable2));
// unlatch the reaper so it can process the element
triggerRendezvous("reaper element");
// latch the reaper before it tests the queue again
triggerRendezvous("reaper1");
// the reaper should have marked the thread as a zombie
assertTrue(checkAndClearFlag("zombied"));
// the transactions queue should be
// UID3 SCHEDULE_CANCEL
assertEquals(1, reaper.numberOfTransactions());
assertEquals(1, reaper.numberOfTimeouts());
// unlatch the third reapable inside cancel
triggerRendezvous(uid2);
// latch the new worker as it is about to process the queue again
triggerRendezvous("reaperworker1");
// let the worker clear and cancel the 2nd reapable
triggerRendezvous("reaperworker1");
// latch the worker before it reads the worker queue
triggerRendezvous("reaperworker1");
// the transactions queue should be empty
assertEquals(0, reaper.numberOfTransactions());
assertEquals(0, reaper.numberOfTimeouts());
// ensure that cancel was tried on reapable3 and that set rollback only was tried on reapable2
// and reapable3 we know cancel was tried on reapable2 because we got through the rendezvous
assertTrue(reapable3.getCancelTried());
assertTrue(reapable2.getRollbackTried());
assertTrue(reapable3.getRollbackTried());
}
}
| 33.737288 | 112 | 0.67571 |
a2e7269957370dae5c288a4512c271c8fbf88c8c | 883 | package com.dji.sample.manage.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author sean.zhou
* @date 2021/11/19
* @version 0.1
*/
@TableName(value = "manage_camera_video")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CameraVideoEntity implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
@TableField(value = "camera_id")
private Integer cameraId;
@TableField(value = "video_index")
private String videoIndex;
@TableField(value = "video_type")
private String videoType;
} | 23.864865 | 56 | 0.771234 |
da1b692192428a03dcff130d1045f36fdaad0025 | 11,677 | package com.ider.overlauncher;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.ider.overlauncher.utils.DownloadUtil;
import com.ider.overlauncher.utils.InstallUtil;
import com.ider.overlauncher.utils.PreferenceManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.ider.overlauncher.utils.InstallUtil.installSlient;
public class AppInfo extends Activity {
String TAG = "AppInfo";
ImageView icon;
TextView label, description;
Button continueDownload;
Button reDownload;
String url;
String pkgName;
String tag;
int verCode;
String md5;
boolean downloading;
DownloadUtil downloadUtil;
private boolean isCustom=false;
private boolean isForceDown = false;
private PreferenceManager pmanager;
private boolean isDownloadComplete;
private static final int DOWNLOAD_SUCCESS = 1;
private static final int DOWNLOAD_FAILED = 2;
private static final int DOWNLOADING_WAIT = 3;
private static final int CHECK_ERROR = 4;
int ErrdownNum = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_info);
continueDownload = (Button) findViewById(R.id.download);
reDownload = (Button) findViewById(R.id.reDownload);
icon = (ImageView) findViewById(R.id.image);
label = (TextView) findViewById(R.id.label);
description = (TextView) findViewById(R.id.description);
pmanager = PreferenceManager.getInstance(this);
Intent intent = getIntent();
Bundle data = intent.getExtras();
Glide.with(AppContext.getAppContext()).load(data.getString("icon")).error(R.mipmap.fail).into(icon);
label.setText(data.getString("label"));
description.setText("简介:" + data.getString("description"));
this.url = data.getString("apk");
this.tag = data.getString("tag");
System.out.println("labelaaa" + data.getString("label"));
this.pkgName = data.getString("pkg");
this.verCode = data.getInt("verCode");
this.md5 = data.getString("md5");
isCustom = data.getBoolean("isCustom");
isForceDown= data.getBoolean("isForceDown",false);
isDownloadComplete = false;
File apk = new File(Constant.APK_CACHE_PATH + "/"
+ DownloadUtil.getInstance().getNameFromUrl(url));
File cacheApk = new File(Constant.APK_CACHE_PATH + "/"
+ DownloadUtil.getInstance().getCacheNameFromUrl(url));
if (!apk.exists() && !cacheApk.exists()) {
showDownloadButton();
} else {
continueDownload.setText("继续下载");
}
Log.i(TAG, "label = " + label + "/ url = " + url);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
reDownload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
reDownload();
}
});
continueDownload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
download();
}
});
if (isForceDown){
reDownload();
}
}
@Override
protected void onDestroy() {
unregisterReceiver(packageReceiver);
super.onDestroy();
}
public void download() {
showDownloadButton();
downloadUtil = DownloadUtil.getInstance();
if (!downloading) {
Log.i(TAG, "downloading = " + downloadUtil.downloading());
if (downloadUtil.downloading()
&& !downloadUtil.currentPackage().equals(pkgName)) {
Toast.makeText(AppInfo.this, R.string.downloading_wait,
Toast.LENGTH_SHORT).show();
} else {
downloading = true;
continueDownload.setText("正在下载…");
new DownloadThread(url).start();
handler.post(percent);
}
}
}
public void reDownload() {
showDownloadButton();
File file = new File(Constant.APK_CACHE_PATH + "/"
+ downloadUtil.getNameFromUrl(url));
File cacheFile = new File(Constant.APK_CACHE_PATH + "/"
+ downloadUtil.getCacheNameFromUrl(url));
file.delete();
cacheFile.delete();
if (!downloading) {
Log.i(TAG, "downloading = " + downloadUtil.downloading());
if (downloadUtil.downloading()
&& !downloadUtil.currentPackage().equals(pkgName)) {
Toast.makeText(AppInfo.this, R.string.downloading_wait,
Toast.LENGTH_SHORT).show();
} else {
downloading = true;
continueDownload.setText("正在下载…");
new DownloadThread(url).start();
handler.post(percent);
}
}
}
public void showDownloadButton() {
reDownload.setVisibility(View.GONE);
LayoutParams lp = (LayoutParams) continueDownload.getLayoutParams();
lp.width = 300;
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
continueDownload.setLayoutParams(lp);
downloadUtil = DownloadUtil.getInstance();
}
Runnable percent = new Runnable() {
@Override
public void run() {
String percent = downloadUtil.getPercent();
if (percent == null) {
percent = "";
}
continueDownload.setText(String.format(
getResources().getString(R.string.Downloading),
downloadUtil.getPercent()));
handler.postDelayed(this, 1000);
}
};
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_SUCCESS:
handler.removeCallbacks(percent);
isDownloadComplete = true;
continueDownload.setText(R.string.Installing);
final String path = (String) msg.obj;
new Thread(){
@Override
public void run(){
InstallUtil.installSlient(path,null,0);
}
}.start();
break;
case DOWNLOAD_FAILED:
downloading = false;
handler.removeCallbacks(percent);
continueDownload.setText(R.string.DownloadFailed);
break;
case DOWNLOADING_WAIT:
Toast.makeText(AppInfo.this, R.string.downloading_wait,
Toast.LENGTH_SHORT).show();
break;
case CHECK_ERROR:
ErrdownNum++;
downloading = false;
handler.removeCallbacks(percent);
if (ErrdownNum >= 3) {
String path2 = (String) msg.obj;
File file = new File(path2);
file.delete();
findViewById(R.id.errdown).setVisibility(View.GONE);
continueDownload.setText(R.string.errdownloadnumlimite);
continueDownload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AppInfo.this.finish();
}
});
} else {
reDownload();
findViewById(R.id.errdown).setVisibility(View.VISIBLE);
}
break;
default:
break;
}
}
};
class DownloadThread extends Thread {
String url;
public DownloadThread(String apkUrl) {
this.url = apkUrl;
}
@Override
public void run() {
String path = downloadUtil.download2Disk(url, pkgName);
if (path != null) {
if (path.endsWith("cfg")) {
path = path.substring(0, path.lastIndexOf("."));
}
File file = new File(path);
if (checkPkg(AppInfo.this, path, pkgName)
&& FileMd5(AppInfo.this, file, md5)) {
Message message = new Message();
message.obj = path;
message.what = DOWNLOAD_SUCCESS;
handler.sendMessage(message);
continueDownload.setClickable(false);
// 安装方式
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setDataAndType(Uri.fromFile(file),
// "application/vnd.android.package-archive");
// startActivity(intent);
} else {
Message message = new Message();
message.obj = path;
message.what = CHECK_ERROR;
handler.sendMessage(message);
}
} else {
handler.sendEmptyMessage(DOWNLOAD_FAILED);
}
}
}
BroadcastReceiver packageReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "package installed");
String data = intent.getDataString();
final String packgename = data.substring(data.indexOf(":") + 1,
data.length());
if (packgename.equals(AppInfo.this.pkgName)) {
downloading = false;
Intent resultIntent = new Intent();
if(isCustom){
resultIntent.putExtra("tag", tag);
}
resultIntent.putExtra("package", packgename);
AppInfo.this.setResult(RESULT_OK, resultIntent);
AppInfo.this.finish();
}
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (downloading) {
if (isDownloadComplete){
Toast.makeText(AppInfo.this,"正在安装!",Toast.LENGTH_LONG).show();
}else {
exitDialog();
}
return true;
}
default:
break;
}
return super.onKeyDown(keyCode, event);
}
public void exitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.Downloading_exit_warning);
builder.setNegativeButton(R.string.Cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
});
builder.setPositiveButton(R.string.Exit,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (isDownloadComplete){
Toast.makeText(AppInfo.this,"正在安装!",Toast.LENGTH_LONG).show();
return;
}
downloadUtil.stopDownload();
AppInfo.this.finish();
}
});
builder.create().show();
}
public boolean checkPkg(Context context, String path, String packageName) {
PackageInfo info=null;
if (packageName == null || packageName.equals("")) {
return false;
}
Log.i(TAG, path + "--------" + packageName + "-------");
PackageManager pm = context.getPackageManager();
try {
info= pm.getPackageArchiveInfo(path,
PackageManager.GET_ACTIVITIES);
System.out.println("infopackname" + info.packageName);
} catch (Exception e) {
// TODO: handle exception
return false;
}
return packageName.equals(info.packageName);
}
@SuppressWarnings("resource")
private boolean FileMd5(AppInfo appInfo, File file, String md5) {
// TODO Auto-generated method stub
if (md5 == null || md5.equals("")) {
return false;
}
if (!file.isFile()) {
return false;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BigInteger bigInt = new BigInteger(1, digest.digest());
String intss = bigInt.toString(16);
System.out.println("--------------intss" + intss + "-------md5====" + md5);
return intss.contains(md5);
//md5.equals(intss);
}
}
| 27.540094 | 102 | 0.695641 |
e8ee9e9a336e11b6fa57e4b9eec48c13bde581d9 | 1,322 | package Srv;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Plaquette extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PLAQUETTE_NAME = "Plaquette Sodibet v2016.pdf";
private static final String ATT_USER = "utilisateur";
public Plaquette() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.setHeader("Content-Type", "application/pdf");
//response.setHeader("Content-Disposition", "attachment;filename=\"" + PLAQUETTE_NAME + "\"");
HttpSession session = req.getSession();
if (session.getAttribute(ATT_USER)!=null) {
this.getServletContext().getRequestDispatcher("/WEB-INF/"+PLAQUETTE_NAME).forward(req, resp);
}
else {
resp.sendRedirect("Login");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| 32.243902 | 119 | 0.752648 |
a34187f348c8ed6c5901258109fc3b3c81c78461 | 293 | package top.hihuzi.collection.pick;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* <p>:
*
* <p>
*
* @author hihuzi 2018/10/17 17:25
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class Base extends Root {
private Date date0 = new Date();
}
| 14.65 | 36 | 0.692833 |
2ffa6b1c9998c8bf4e84976a16215b0948e55dbf | 3,288 | /*
Copyright (c) Lightstreamer Srl
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.lightstreamer.adapters.Dart.room;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class User {
private final ChatRoom chatRoom;
private String id;
private String nick;
private String statusId = "";
private String status = "";
private Map<String,String> extraProp = new HashMap<String,String>();
private Object statusHandle = null;
private Object messagesHandle = null;
private Set<Room> rooms = new HashSet<Room>();
private boolean active = false;
User(ChatRoom chatRoom, String id) {
this.chatRoom = chatRoom;
this.id = id;
}
public String getId() {
return this.id;
}
Map<String, String> getExtraProps() {
return this.extraProp;
}
Object getStatusHandle() {
return this.statusHandle;
}
void enterRoom(Room room) {
room.addUser(this);
this.rooms.add(room);
}
void leaveRoom(Room room) {
room.removeUser(this);
this.rooms.remove(room);
}
String getStatusId() {
return this.statusId;
}
void setNick(String nick) {
this.nick = nick;
if (this.statusHandle != null) {
this.chatRoom.sendUserStatusEvent(this, this.nick, null, null, null, this.statusHandle, ChatRoom.REALTIME);
}
}
void setStatus(String status, String statusId) {
this.status = status;
this.statusId = statusId;
if (this.statusHandle != null) {
this.chatRoom.sendUserStatusEvent(this, null, this.statusId, this.status, null, this.statusHandle, ChatRoom.REALTIME);
}
}
public synchronized void setExtraProps(Map<String,String> map) {
extraProp.putAll(map);
if (this.statusHandle != null) {
this.chatRoom.sendUserStatusEvent(this, null, null, null, map, this.statusHandle, ChatRoom.REALTIME);
}
}
boolean isListened() {
return this.statusHandle != null || this.messagesHandle != null;
}
String getNick() {
return this.nick;
}
String getStatus() {
return this.status;
}
void setStatusHandle(Object statusHandle) {
this.statusHandle = statusHandle;
}
void setHandle(Object messagesHandle) {
this.messagesHandle = messagesHandle;
}
Iterator<Room> getRooms() {
return rooms.iterator();
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isActive() {
return this.active;
}
} | 25.292308 | 130 | 0.630474 |
11d1b57f48f70710659b1aa19996266a9677ba41 | 4,513 | package com.facebook.LinkBench;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class PgsqlTestConfig {
// Hardcoded parameters for now
static String host = "localhost";
static int port = 5432;
static String user = "linkbench";
static String pass = "pw";
static String linktable = "test_linktable";
static String counttable = "test_counttable";
static String nodetable = "test_nodetable";
public static void fillPgsqlTestServerProps(Properties props) {
props.setProperty(Config.LINKSTORE_CLASS, LinkStorePgsql.class.getName());
props.setProperty(Config.NODESTORE_CLASS, LinkStorePgsql.class.getName());
props.setProperty(LinkStorePgsql.CONFIG_HOST, host);
props.setProperty(LinkStorePgsql.CONFIG_PORT, Integer.toString(port));
props.setProperty(LinkStorePgsql.CONFIG_USER, user);
props.setProperty(LinkStorePgsql.CONFIG_PASSWORD, pass);
props.setProperty(Config.LINK_TABLE, linktable);
props.setProperty(Config.COUNT_TABLE, counttable);
props.setProperty(Config.NODE_TABLE, nodetable);
}
static Connection createConnection(String testDB)
throws InstantiationException,
IllegalAccessException, ClassNotFoundException, SQLException, ReflectiveOperationException {
Logger.getLogger().info("create connection");
Class.forName("org.postgresql.Driver").getConstructor().newInstance();
String jdbcUrl = "jdbc:postgresql://"+ host + ":" + port + "/linkbench";
jdbcUrl += "?elideSetAutoCommits=true" +
"&useLocalTransactionState=true" +
"&allowMultiQueries=true" +
"&useLocalSessionState=true" +
"&useAffectedRows=true";
return DriverManager.getConnection(jdbcUrl, PgsqlTestConfig.user, PgsqlTestConfig.pass);
}
static void createTestTables(Connection conn, String testDB) throws SQLException {
Logger.getLogger().info("createTestTables");
Statement stmt = conn.createStatement();
stmt.executeUpdate("DROP SCHEMA IF EXISTS " + testDB + " CASCADE");
stmt.executeUpdate("CREATE SCHEMA " + testDB);
stmt.executeUpdate(String.format(
"CREATE TABLE %s.%s ( " +
" id1 bigint NOT NULL DEFAULT '0', " +
" id2 bigint NOT NULL DEFAULT '0', " +
" link_type bigint NOT NULL DEFAULT '0', " +
" visibility smallint NOT NULL DEFAULT '0', " +
" data bytea NOT NULL , " +
" time bigint NOT NULL DEFAULT '0', " +
" version int NOT NULL DEFAULT '0', " +
" PRIMARY KEY (link_type, id1,id2))",
testDB, PgsqlTestConfig.linktable));
stmt.executeUpdate(String.format(
"CREATE INDEX id1_type on %s.%s ( " +
" id1,link_type,visibility,time,id2,version,data)",
testDB, PgsqlTestConfig.linktable));
stmt.executeUpdate(String.format(
"CREATE TABLE %s.%s ( " +
" id bigint NOT NULL DEFAULT '0', " +
" link_type bigint NOT NULL DEFAULT '0', " +
" count bigint NOT NULL DEFAULT '0', " +
" time bigint NOT NULL DEFAULT '0', " +
" version bigint NOT NULL DEFAULT '0', " +
" PRIMARY KEY (id,link_type))",
testDB, PgsqlTestConfig.counttable));
stmt.executeUpdate(String.format(
"CREATE TABLE %s.%s ( " +
" id BIGSERIAL NOT NULL, " +
" type int NOT NULL, " +
" version bigint NOT NULL, " +
" time int NOT NULL, " +
" data bytea NOT NULL, " +
" PRIMARY KEY(id))",
testDB, PgsqlTestConfig.nodetable));
stmt.close();
}
static void dropTestTables(Connection conn, String testDB) throws SQLException {
Logger.getLogger().info("dropTestTables");
Statement stmt = conn.createStatement();
int rlink = stmt.executeUpdate(String.format("DROP TABLE IF EXISTS %s.%s",
testDB, PgsqlTestConfig.linktable));
int rcount = stmt.executeUpdate(String.format("DROP TABLE IF EXISTS %s.%s",
testDB, PgsqlTestConfig.counttable));
int rnode = stmt.executeUpdate(String.format("DROP TABLE IF EXISTS %s.%s",
testDB, PgsqlTestConfig.nodetable));
if (rlink != 0 || rcount != 0 || rnode != 0) {
throw new IllegalStateException("dropTestTables failed with (link,count,node)=(" +
rlink + "," + rcount + "," + rnode + ")");
}
stmt.close();
}
}
| 41.40367 | 98 | 0.644139 |
864762bb7f5e915cc0be4e81b725c2272d24d563 | 2,872 | /**
* Copyright 2017 Hortonworks.
* <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 com.hortonworks.streamline.storage.tool.sql;
import java.util.Map;
public class StorageProviderConfigurationReader {
private static final String STORAGE_PROVIDER_CONFIGURATION = "storageProviderConfiguration";
private static final String PROPERTIES = "properties";
private static final String DB_TYPE = "db.type";
private static final String DB_PROPERTIES = "db.properties";
private static final String DATA_SOURCE_URL = "dataSource.url";
private static final String DATA_SOURCE_USER = "dataSource.user";
private static final String DATA_SOURCE_PASSWORD = "dataSource.password";
private static final String CREDENTIALS_SECURED = "credentials.secured";
public StorageProviderConfiguration readStorageConfig(Map<String, Object> conf) {
Map<String, Object> storageConf = (Map<String, Object>) conf.get(
STORAGE_PROVIDER_CONFIGURATION);
if (storageConf == null) {
throw new RuntimeException("No storageProviderConfiguration in config file.");
}
Map<String, Object> properties = (Map<String, Object>) storageConf.get(PROPERTIES);
if (properties == null) {
throw new RuntimeException("No properties presented to storageProviderConfiguration.");
}
String dbType = (String) properties.get(DB_TYPE);
if (dbType == null) {
throw new RuntimeException("No db.type presented to properties.");
}
boolean credentialsSecured = (boolean) properties.get(CREDENTIALS_SECURED);
Map<String, Object> dbProps = (Map<String, Object>) properties.get(DB_PROPERTIES);
return readDatabaseProperties(dbProps, DatabaseType.fromValue(dbType), credentialsSecured);
}
private static StorageProviderConfiguration readDatabaseProperties(
Map<String, Object> dbProperties, DatabaseType databaseType, boolean credentialsSecured) {
String jdbcUrl = (String) dbProperties.get(DATA_SOURCE_URL);
String user = (String) dbProperties.getOrDefault(DATA_SOURCE_USER, "");
String password = (String) dbProperties.getOrDefault(DATA_SOURCE_PASSWORD, "");
return StorageProviderConfiguration.get(jdbcUrl, user, password, databaseType, credentialsSecured);
}
}
| 44.875 | 107 | 0.724582 |
d10fbdee154d0da0cd54f26306bfb171e3a723ee | 284 |
public class lidhjaProvimi {
private final Studenti studenti;
private final Kursi kursi;
private int Nota;
public lidhjaProvimi(Studenti s, Kursi k, int n)
{
studenti=s;
kursi=k;
Nota=n;
}
public String toString() {
return studenti +" "+ kursi+ " "+Nota;
}
}
| 14.2 | 49 | 0.665493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.