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
|
---|---|---|---|---|---|
2eb87dad939523a48ba4f810b8e3ca09dfd66b80 | 1,197 | package com.packtpub.a3ws.ch4.samples.vo;
import java.util.ArrayList;
import java.util.List;
public class BookVO {
private String id;
private String title;
private String description;
private String isbn;
private String author;
private String publisher;
private List<ReviewFormBean> reviews = new ArrayList<ReviewFormBean>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public List<ReviewFormBean> getReviews() {
return reviews;
}
public void setReviews(List<ReviewFormBean> reviews) {
this.reviews = reviews;
}
}
| 19.622951 | 72 | 0.719298 |
18a1bc13b3d1092c13ff6d0917f8b05d6f4ed1ef | 323 | package edu.tamu.scholars.middleware.view.model;
import javax.persistence.MappedSuperclass;
import edu.tamu.scholars.middleware.model.Named;
@MappedSuperclass
public abstract class View extends Named {
private static final long serialVersionUID = 413593021970972190L;
public View() {
super();
}
}
| 19 | 69 | 0.752322 |
75b5c072929fc74d0185896310944e1f85f9c440 | 1,148 | // AbstrRelationMapBased.java, created Fri Jun 30 11:17:10 2000 by salcianu
// Copyright (C) 2000 Alexandru SALCIANU <[email protected]>
// Licensed under the terms of the GNU GPL; see COPYING for details.
package jwutil.collections;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* <code>AbstrRelationMapBased</code>
*
* @author Alexandru SALCIANU <[email protected]>
* @version $Id: AbstrRelationMapBased.java,v 1.1 2004/09/27 22:42:32 joewhaley Exp $
*/
public abstract class AbstrRelationMapBased extends AbstrRelation
implements Serializable {
// A map from keys to sets of values.
protected Map map = null;
public void removeKey(Object key) {
hashCode = 0;
map.remove(key);
}
public Set getValues(Object key) {
Set retval = getValues2(key);
if(retval == null)
retval = Collections.EMPTY_SET;
return retval;
}
protected Set getValues2(Object key) {
return (Set) map.get(key);
}
public Set keys() {
return map.keySet();
}
}
| 24.425532 | 85 | 0.655923 |
b11054ef98a4e7f19062a17c9e765d7a0e00f93f | 355 | package com.abel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by yangyibo on 2018/6/28.
*/
@SpringBootApplication
public class PersonApplication {
public static void main(String[] args) {
SpringApplication.run(PersonApplication.class,args);
}
}
| 23.666667 | 68 | 0.766197 |
083530e829e44baf3be75e94ce807e85e1faf90f | 6,452 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.photos.library.v1;
import com.google.api.core.ApiClock;
import com.google.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.ExecutorProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.WatchdogProvider;
import com.google.common.collect.ImmutableSet;
import com.google.photos.library.v1.internal.InternalPhotosLibrarySettings;
import com.google.photos.library.v1.internal.stub.PhotosLibraryStubSettings;
import com.google.photos.library.v1.upload.UploadMediaItemRequest;
import com.google.photos.library.v1.upload.UploadMediaItemResponse;
import java.io.IOException;
import javax.annotation.Nullable;
import org.threeten.bp.Duration;
/**
* Settings for a {@link PhotosLibraryClient} for interacting with the Google Photos Library API.
*
* Use the {@link Builder} to create an instance of this class. You can configure the retry
* configuration for media upload requests using {@link UnaryCallSettings} through the
* {@link Builder#uploadMediaItemSettingsBuilder}.
*
* Note that this class is a wrapper of {@link InternalPhotosLibrarySettings} which should not be
* used directly. Instead, use this class and the {@link PhotosLibraryClient}.
*/
public final class PhotosLibrarySettings extends InternalPhotosLibrarySettings {
/** The default endpoint of the upload service. */
private static final String DEFAULT_UPLOAD_ENDPOINT =
"https://photoslibrary.googleapis.com/v1/uploads";
private final UnaryCallSettings<UploadMediaItemRequest, UploadMediaItemResponse>
uploadMediaItemSettings;
protected PhotosLibrarySettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
uploadMediaItemSettings = settingsBuilder.uploadMediaItemSettingsBuilder().build();
}
/** Returns the object with the settings used for calls to uploadMediaItem. */
public UnaryCallSettings<UploadMediaItemRequest, UploadMediaItemResponse>
uploadMediaItemSettings() {
return uploadMediaItemSettings;
}
/** Returns the upload endpoint used for calls to uploadMediaItem. */
public static String getUploadEndpoint() {
return DEFAULT_UPLOAD_ENDPOINT;
}
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Builder class for {@link PhotosLibrarySettings}. */
public static final class Builder extends InternalPhotosLibrarySettings.Builder {
/** RPC statuses for which upload requests should be retried. */
private static final ImmutableSet<StatusCode.Code> UPLOAD_RETRYABLE_CODE_DEFINITIONS =
ImmutableSet.of(StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE);
private final UnaryCallSettings.Builder<UploadMediaItemRequest, UploadMediaItemResponse>
uploadMediaItemSettingsBuilder = getUploadSettingsDefaults();
private Builder(PhotosLibraryStubSettings.Builder stubSettings) {
super(stubSettings);
}
@Override
public Builder setExecutorProvider(ExecutorProvider executorProvider) {
super.setExecutorProvider(executorProvider);
return this;
}
@Override
public Builder setCredentialsProvider(CredentialsProvider credentialsProvider) {
super.setCredentialsProvider(credentialsProvider);
return this;
}
@Override
public Builder setHeaderProvider(HeaderProvider headerProvider) {
super.setHeaderProvider(headerProvider);
return this;
}
@Override
protected Builder setInternalHeaderProvider(HeaderProvider internalHeaderProvider) {
super.setInternalHeaderProvider(internalHeaderProvider);
return this;
}
@Override
public Builder setTransportChannelProvider(TransportChannelProvider transportChannelProvider) {
super.setTransportChannelProvider(transportChannelProvider);
return this;
}
@Override
public Builder setClock(ApiClock clock) {
super.setClock(clock);
return this;
}
@Override
public Builder setEndpoint(String endpoint) {
super.setEndpoint(endpoint);
return this;
}
@Override
public Builder setWatchdogProvider(@Nullable WatchdogProvider watchdogProvider) {
super.setWatchdogProvider(watchdogProvider);
return this;
}
@Override
public Builder setWatchdogCheckInterval(@Nullable Duration checkInterval) {
super.setWatchdogCheckInterval(checkInterval);
return this;
}
@Override
public PhotosLibrarySettings build() throws IOException {
return new PhotosLibrarySettings(this);
}
/** Returns the builder for the settings used for calls to uploadMediaItem. */
public UnaryCallSettings.Builder<UploadMediaItemRequest, UploadMediaItemResponse>
uploadMediaItemSettingsBuilder() {
return uploadMediaItemSettingsBuilder;
}
public static Builder createDefault() {
return new Builder(PhotosLibraryStubSettings.newBuilder());
}
private static UnaryCallSettings.Builder<UploadMediaItemRequest, UploadMediaItemResponse>
getUploadSettingsDefaults() {
return UnaryCallSettings
.<UploadMediaItemRequest, UploadMediaItemResponse>newUnaryCallSettingsBuilder()
.setRetryableCodes(UPLOAD_RETRYABLE_CODE_DEFINITIONS)
.setRetrySettings(getUploadRetryDefaults());
}
private static RetrySettings getUploadRetryDefaults() {
return RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofSeconds(1))
.setRetryDelayMultiplier(1.3)
.setMaxAttempts(5)
.setMaxRetryDelay(Duration.ofSeconds(10))
.setTotalTimeout(Duration.ofMinutes(15))
.build();
}
}
}
| 36.451977 | 99 | 0.759454 |
0c03b1469c4e811d44779acc160da5fcaee8b351 | 3,965 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.hdfs.shortcircuit
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|shortcircuit
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|Closeable
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|MappedByteBuffer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|/** * A reference to a memory-mapped region used by an HDFS client. */
end_comment
begin_class
annotation|@
name|InterfaceAudience
operator|.
name|Private
DECL|class|ClientMmap
specifier|public
class|class
name|ClientMmap
implements|implements
name|Closeable
block|{
DECL|field|LOG
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|ClientMmap
operator|.
name|class
argument_list|)
decl_stmt|;
comment|/** * A reference to the block replica which this mmap relates to. */
DECL|field|replica
specifier|private
name|ShortCircuitReplica
name|replica
decl_stmt|;
comment|/** * The java ByteBuffer object. */
DECL|field|map
specifier|private
specifier|final
name|MappedByteBuffer
name|map
decl_stmt|;
comment|/** * Whether or not this ClientMmap anchors the replica into memory while * it exists. Closing an anchored ClientMmap unanchors the replica. */
DECL|field|anchored
specifier|private
specifier|final
name|boolean
name|anchored
decl_stmt|;
DECL|method|ClientMmap (ShortCircuitReplica replica, MappedByteBuffer map, boolean anchored)
name|ClientMmap
parameter_list|(
name|ShortCircuitReplica
name|replica
parameter_list|,
name|MappedByteBuffer
name|map
parameter_list|,
name|boolean
name|anchored
parameter_list|)
block|{
name|this
operator|.
name|replica
operator|=
name|replica
expr_stmt|;
name|this
operator|.
name|map
operator|=
name|map
expr_stmt|;
name|this
operator|.
name|anchored
operator|=
name|anchored
expr_stmt|;
block|}
comment|/** * Close the ClientMmap object. */
annotation|@
name|Override
DECL|method|close ()
specifier|public
name|void
name|close
parameter_list|()
block|{
if|if
condition|(
name|replica
operator|!=
literal|null
condition|)
block|{
if|if
condition|(
name|anchored
condition|)
block|{
name|replica
operator|.
name|removeNoChecksumAnchor
argument_list|()
expr_stmt|;
block|}
name|replica
operator|.
name|unref
argument_list|()
expr_stmt|;
block|}
name|replica
operator|=
literal|null
expr_stmt|;
block|}
DECL|method|getMappedByteBuffer ()
specifier|public
name|MappedByteBuffer
name|getMappedByteBuffer
parameter_list|()
block|{
return|return
name|map
return|;
block|}
block|}
end_class
end_unit
| 18.791469 | 814 | 0.788651 |
efc1d90575016f74eb208a773d11aa5915ce9c81 | 1,961 | /**
* Copyright (C) 2013 – 2015 SLUB Dresden & Avantgarde Labs GmbH (<[email protected]>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dswarm.persistence.model.resource.test;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Assert;
import org.junit.Test;
import org.dswarm.persistence.GuicedTest;
import org.dswarm.persistence.model.resource.Configuration;
import org.dswarm.persistence.util.DMPPersistenceUtil;
/**
* Created by tgaengler on 21/05/14.
*/
public class ConfigurationTest extends GuicedTest {
private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class);
@Test
public void simpleConfigurationTest() throws IOException {
final String configurationJSONString = DMPPersistenceUtil.getResourceAsString("configuration.json");
final Configuration configuration = objectMapper.readValue(configurationJSONString, Configuration.class);
final ObjectNode configurationJSON = objectMapper.readValue(configurationJSONString, ObjectNode.class);
final String finalExpectedConfigurationJSONString = objectMapper.writeValueAsString(configurationJSON);
final String finalActualConfigurationJSONString = objectMapper.writeValueAsString(configuration);
Assert.assertEquals(finalExpectedConfigurationJSONString.length(), finalActualConfigurationJSONString.length());
}
}
| 38.45098 | 114 | 0.800612 |
92ff6e47fadc6154d028993320319d5dd47e9146 | 2,476 | package com.linepro.modellbahn.service.impl;
/**
* AufbauService. CRUD service for Aufbau
* @author $Author:$
* @version $Id:$
*/
import static com.linepro.modellbahn.ModellBahnApplication.PREFIX;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.linepro.modellbahn.controller.impl.AcceptableMediaTypes;
import com.linepro.modellbahn.controller.impl.ApiNames;
import com.linepro.modellbahn.converter.entity.AufbauMapper;
import com.linepro.modellbahn.converter.request.AufbauRequestMapper;
import com.linepro.modellbahn.entity.Aufbau;
import com.linepro.modellbahn.io.FileService;
import com.linepro.modellbahn.model.AufbauModel;
import com.linepro.modellbahn.repository.AufbauRepository;
import com.linepro.modellbahn.repository.lookup.AufbauLookup;
import com.linepro.modellbahn.request.AufbauRequest;
@Service(PREFIX + "AufbauService")
public class AufbauService extends NamedItemServiceImpl<AufbauModel, AufbauRequest, Aufbau> {
private final AufbauRepository repository;
private final FileService fileService;
@Autowired
public AufbauService(AufbauRepository repository, AufbauRequestMapper requestMapper, AufbauMapper entityMapper, FileService fileService, AufbauLookup lookup) {
super(repository, requestMapper, entityMapper, lookup);
this.repository = repository;
this.fileService = fileService;
}
@Transactional
public Optional<AufbauModel> updateAbbildung(String name, MultipartFile multipart) {
return repository.findByName(name)
.map(a -> {
a.setAbbildung(fileService.updateFile(AcceptableMediaTypes.IMAGE_TYPES, multipart, ApiNames.AUFBAU, ApiNames.ABBILDUNG, name));
return repository.saveAndFlush(a);
})
.flatMap(e -> this.get(name));
}
@Transactional
public Optional<AufbauModel> deleteAbbildung(String name) {
return repository.findByName(name)
.map(a -> {
a.setAbbildung(fileService.deleteFile(a.getAbbildung()));
return repository.saveAndFlush(a);
})
.flatMap(e -> this.get(name));
}
}
| 38.092308 | 163 | 0.702342 |
550e89bf949548251a644925f27752b246ce13a9 | 1,221 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.lens.api.query.save;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The enum ParameterDataType
* Should be given based on the column data type.
*/
@XmlRootElement
public enum ParameterDataType {
/**
* String data type
*/
STRING,
/**
* Number data type
*/
NUMBER,
/**
* Decimal data type
*/
DECIMAL,
/**
* Boolean data type
*/
BOOLEAN;
}
| 24.918367 | 63 | 0.710074 |
c6c6e61444aba53498a5ed979a2aeb3f024db684 | 600 | package com.ieasy360.app.upgrade;
public class UpdateConstants {
// protected static final String APP_UPDATE_SERVER_URL = "http://192.168.205.33:8080/Hello/api/update";
// json {"url":"http://192.168.205.33:8080/Hello/medtime_v3.0.1_Other_20150116.apk","versionCode":2,"updateMessage":"版本更新信息"}
//我这里服务器返回的json数据是这样的,可以根据实际情况修改下面参数的名称
public static final String APK_DOWNLOAD_URL = "Url";
public static final String APK_UPDATE_CONTENT = "Name";
public static final String APK_VERSION_CODE = "versionCode";
public static final String APK_IS_AUTO_INSTALL = "isAutoInstall";
}
| 37.5 | 127 | 0.756667 |
b44e24872702efe17d8d1cb22b6029271366a3e7 | 2,365 | package jetbrains.mps.lang.editor.figures.library;
/*Generated by MPS */
import jetbrains.jetpad.model.property.Property;
import jetbrains.jetpad.model.property.ValueProperty;
import jetbrains.jetpad.cell.TextCell;
import jetbrains.jetpad.cell.toView.CellView;
import jetbrains.jetpad.values.Color;
import jetbrains.jetpad.mapper.MapperFactory;
import jetbrains.jetpad.mapper.Mapper;
import jetbrains.jetpad.mapper.Synchronizers;
import jetbrains.jetpad.model.property.WritableProperty;
import jetbrains.jetpad.base.Registration;
import jetbrains.jetpad.cell.text.TextEditing;
public class NamedBoxFigure extends BoxFigure {
public Property<Boolean> editable = new ValueProperty<Boolean>(true);
private TextCell myCell = new TextCell();
public NamedBoxFigure() {
this(new NamedBoxFigureMapperFactory());
}
public NamedBoxFigure(NamedBoxFigureMapperFactory factory) {
CellView cellView = new CellView();
myCell.textColor().set(Color.GRAY);
myCell.text().set("<<No text>>");
cellView.cell.set(myCell);
children().add(cellView);
if (factory != null) {
factory.createMapper(this).attachRoot();
}
}
public Property<String> nameText() {
return myCell.text();
}
private static class NamedBoxFigureMapperFactory implements MapperFactory<NamedBoxFigure, NamedBoxFigure> {
public Mapper<? extends NamedBoxFigure, ? extends NamedBoxFigure> createMapper(NamedBoxFigure figure) {
return new NamedBoxFigureMapper<NamedBoxFigure>(figure);
}
}
protected static class NamedBoxFigureMapper<T extends NamedBoxFigure> extends BoxFigure.BoxFigureMapper<T> {
protected NamedBoxFigureMapper(T figure) {
super(figure);
}
@Override
protected void registerSynchronizers(Mapper.SynchronizersConfiguration configuration) {
super.registerSynchronizers(configuration);
configuration.add(Synchronizers.forProperty(getSource().editable, new WritableProperty<Boolean>() {
private Registration myRegistration;
public void set(Boolean editable) {
if (editable) {
NamedBoxFigure source = getSource();
myRegistration = source.myCell.addTrait(TextEditing.textEditing());
} else if (myRegistration != null) {
myRegistration.remove();
myRegistration = null;
}
}
}));
}
}
}
| 35.833333 | 110 | 0.731078 |
dba3e078a31f6ccbbf83c12200e7724abb2eb750 | 2,254 | package com.github.lehjr.modularpowerarmor.item.tool;
import com.github.lehjr.modularpowerarmor.capabilities.PowerFistCap;
import com.github.lehjr.mpalib.util.string.AdditionalInfo;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolItem;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.energy.CapabilityEnergy;
import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.List;
public class AbstractElectricTool extends ToolItem {
public AbstractElectricTool(Item.Properties properties) {
super(0.0F,
0.0F,
MPAToolMaterial.EMPTY_TOOL,
new HashSet<>(),
properties);
}
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
if (worldIn != null) {
AdditionalInfo.addInformation(stack, worldIn, tooltip, flagIn);
}
}
@Nullable
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
return new PowerFistCap(stack);
}
/** Durability bar for showing energy level ------------------------------------------------------------------ */
@Override
public boolean showDurabilityBar(final ItemStack stack) {
return stack.getCapability(CapabilityEnergy.ENERGY)
.map( energyCap-> energyCap.getMaxEnergyStored() > 0).orElse(false);
}
@Override
public double getDurabilityForDisplay(final ItemStack stack) {
return stack.getCapability(CapabilityEnergy.ENERGY)
.map( energyCap-> 1 - energyCap.getEnergyStored() / (double) energyCap.getMaxEnergyStored()).orElse(1D);
}
@Override
public void setDamage(ItemStack stack, int damage) {
}
@Override
public boolean isDamageable() {
return false;
}
} | 34.151515 | 125 | 0.696096 |
f7c1c6e1f821dd807fe8c5b0a343c8ba8a363666 | 6,658 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/spanner/admin/database/v1/spanner_database_admin.proto
package com.google.spanner.admin.database.v1;
public interface RestoreDatabaseRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.spanner.admin.database.v1.RestoreDatabaseRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The name of the instance in which to create the
* restored database. This instance must be in the same project and
* have the same instance configuration as the instance containing
* the source backup. Values are of the form
* `projects/<project>/instances/<instance>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The name of the instance in which to create the
* restored database. This instance must be in the same project and
* have the same instance configuration as the instance containing
* the source backup. Values are of the form
* `projects/<project>/instances/<instance>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Required. The id of the database to create and restore to. This
* database must not already exist. The `database_id` appended to
* `parent` forms the full database name of the form
* `projects/<project>/instances/<instance>/databases/<database_id>`.
* </pre>
*
* <code>string database_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The databaseId.
*/
java.lang.String getDatabaseId();
/**
*
*
* <pre>
* Required. The id of the database to create and restore to. This
* database must not already exist. The `database_id` appended to
* `parent` forms the full database name of the form
* `projects/<project>/instances/<instance>/databases/<database_id>`.
* </pre>
*
* <code>string database_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for databaseId.
*/
com.google.protobuf.ByteString getDatabaseIdBytes();
/**
*
*
* <pre>
* Name of the backup from which to restore. Values are of the form
* `projects/<project>/instances/<instance>/backups/<backup>`.
* </pre>
*
* <code>string backup = 3 [(.google.api.resource_reference) = { ... }</code>
*
* @return Whether the backup field is set.
*/
boolean hasBackup();
/**
*
*
* <pre>
* Name of the backup from which to restore. Values are of the form
* `projects/<project>/instances/<instance>/backups/<backup>`.
* </pre>
*
* <code>string backup = 3 [(.google.api.resource_reference) = { ... }</code>
*
* @return The backup.
*/
java.lang.String getBackup();
/**
*
*
* <pre>
* Name of the backup from which to restore. Values are of the form
* `projects/<project>/instances/<instance>/backups/<backup>`.
* </pre>
*
* <code>string backup = 3 [(.google.api.resource_reference) = { ... }</code>
*
* @return The bytes for backup.
*/
com.google.protobuf.ByteString getBackupBytes();
/**
*
*
* <pre>
* Optional. An encryption configuration describing the encryption type and key
* resources in Cloud KMS used to encrypt/decrypt the database to restore to.
* If this field is not specified, the restored database will use
* the same encryption configuration as the backup by default, namely
* [encryption_type][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type] =
* `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`.
* </pre>
*
* <code>
* .google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig encryption_config = 4 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the encryptionConfig field is set.
*/
boolean hasEncryptionConfig();
/**
*
*
* <pre>
* Optional. An encryption configuration describing the encryption type and key
* resources in Cloud KMS used to encrypt/decrypt the database to restore to.
* If this field is not specified, the restored database will use
* the same encryption configuration as the backup by default, namely
* [encryption_type][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type] =
* `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`.
* </pre>
*
* <code>
* .google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig encryption_config = 4 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The encryptionConfig.
*/
com.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig getEncryptionConfig();
/**
*
*
* <pre>
* Optional. An encryption configuration describing the encryption type and key
* resources in Cloud KMS used to encrypt/decrypt the database to restore to.
* If this field is not specified, the restored database will use
* the same encryption configuration as the backup by default, namely
* [encryption_type][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type] =
* `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`.
* </pre>
*
* <code>
* .google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig encryption_config = 4 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfigOrBuilder
getEncryptionConfigOrBuilder();
public com.google.spanner.admin.database.v1.RestoreDatabaseRequest.SourceCase getSourceCase();
}
| 34.497409 | 135 | 0.687744 |
871989e5012e0606f4e9dc7f125db88627c6075c | 116 | package main.java;
public class GLPoly extends GLCurve {
public GLPoly(GLVec... vecs){
super(vecs);
}
}
| 11.6 | 37 | 0.655172 |
8bf3f50631e252fb8a9d0546f9e7a57eb253fa9d | 411 | package com.mxpio.mxpioboot.jpa.initiator;
import org.springframework.context.ApplicationContext;
/**
* JpaUtil可用接口
* JpaUtil在启动时候会进行初始化动作,初始化之前用JpaUtil<br>
* 会报错,如果需要在项目启动的时候用JpaUtil,可以通过实现JpaUtilAble接口,<br>
* 从而确保JpaUtil已经被初始化
* @author Kevin Yang (mailto:[email protected])
* @since 2017年11月16日
*/
public interface JpaUtilAble {
void afterPropertiesSet(ApplicationContext applicationContext);
}
| 25.6875 | 64 | 0.805353 |
972a392a6aa9bdd082aa69c0fcd76692a9879b6f | 952 | package com.sensiblemetrics.api.alpenidos.pattern.service_layer.spell;
import com.sensiblemetrics.api.alpenidos.pattern.service_layer.common.BaseEntity;
import com.sensiblemetrics.api.alpenidos.pattern.service_layer.spellbook.Spellbook;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
/**
* Spell entity.
*/
@Data
@Entity
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
@Table(name = "SPELL")
public class Spell extends BaseEntity {
private String name;
@Id
@GeneratedValue
@Column(name = "SPELL_ID")
private Long id;
@ManyToOne
@JoinColumn(name = "SPELLBOOK_ID_FK", referencedColumnName = "SPELLBOOK_ID")
private Spellbook spellbook;
public Spell(final String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
| 22.139535 | 83 | 0.734244 |
3d0e1ae0abba8e377decf30721f327d22af41c17 | 37,864 | /*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.web.security;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.web.security.MembershipUser;
import system.web.security.MembershipUserCollection;
import system.web.security.MembershipProvider;
import system.web.security.MembershipProviderCollection;
/**
* The base .NET class managing System.Web.Security.Membership, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Web.Security.Membership" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Web.Security.Membership</a>
*/
public class Membership extends NetObject {
/**
* Fully assembly qualified name: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: System.Web
*/
public static final String assemblyShortName = "System.Web";
/**
* Qualified class name: System.Web.Security.Membership
*/
public static final String className = "System.Web.Security.Membership";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Membership(Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link Membership}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link Membership} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static Membership cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new Membership(from.getJCOInstance());
}
// Constructors section
public Membership() throws Throwable {
}
// Methods section
public static boolean DeleteUser(java.lang.String username) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Invoke("DeleteUser", username);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static boolean DeleteUser(java.lang.String username, boolean deleteAllRelatedData) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Invoke("DeleteUser", username, deleteAllRelatedData);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static boolean ValidateUser(java.lang.String username, java.lang.String password) throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.TypeLoadException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Invoke("ValidateUser", username, password);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int GetNumberOfUsersOnline() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.TypeLoadException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Invoke("GetNumberOfUsersOnline");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String GeneratePassword(int length, int numberOfNonAlphanumericCharacters) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.FormatException, system.OverflowException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Invoke("GeneratePassword", length, numberOfNonAlphanumericCharacters);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String GetUserNameByEmail(java.lang.String emailToMatch) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Invoke("GetUserNameByEmail", emailToMatch);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser CreateUser(java.lang.String username, java.lang.String password) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.ArgumentException, system.resources.MissingManifestResourceException, system.InvalidOperationException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.NotSupportedException, system.MissingMethodException, system.reflection.TargetInvocationException, system.configuration.provider.ProviderException, system.web.security.MembershipCreateUserException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objCreateUser = (JCObject)classType.Invoke("CreateUser", username, password);
return new MembershipUser(objCreateUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser CreateUser(java.lang.String username, java.lang.String password, java.lang.String email) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.NotSupportedException, system.configuration.ConfigurationException, system.TypeLoadException, system.configuration.provider.ProviderException, system.web.security.MembershipCreateUserException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objCreateUser = (JCObject)classType.Invoke("CreateUser", username, password, email);
return new MembershipUser(objCreateUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser() throws Throwable, system.ArgumentException, system.InvalidOperationException, system.ArgumentNullException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.security.SecurityException, system.NullReferenceException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser");
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser(boolean userIsOnline) throws Throwable, system.ArgumentException, system.InvalidOperationException, system.ArgumentNullException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.security.SecurityException, system.NullReferenceException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser", userIsOnline);
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser(NetObject providerUserKey) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.NotImplementedException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.ConfigurationErrorsException, system.NotSupportedException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser", providerUserKey == null ? null : providerUserKey.getJCOInstance());
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser(NetObject providerUserKey, boolean userIsOnline) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.TypeLoadException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser", providerUserKey == null ? null : providerUserKey.getJCOInstance(), userIsOnline);
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser(java.lang.String username) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.NotSupportedException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser", username);
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUser GetUser(java.lang.String username, boolean userIsOnline) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetUser = (JCObject)classType.Invoke("GetUser", username, userIsOnline);
return new MembershipUser(objGetUser);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUserCollection FindUsersByEmail(java.lang.String emailToMatch) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.NotSupportedException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objFindUsersByEmail = (JCObject)classType.Invoke("FindUsersByEmail", emailToMatch);
return new MembershipUserCollection(objFindUsersByEmail);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUserCollection FindUsersByName(java.lang.String usernameToMatch) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.IndexOutOfRangeException, system.security.SecurityException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objFindUsersByName = (JCObject)classType.Invoke("FindUsersByName", usernameToMatch);
return new MembershipUserCollection(objFindUsersByName);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipUserCollection GetAllUsers() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.ConfigurationErrorsException, system.NotSupportedException, system.configuration.ConfigurationException, system.configuration.provider.ProviderException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject objGetAllUsers = (JCObject)classType.Invoke("GetAllUsers");
return new MembershipUserCollection(objGetAllUsers);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static void UpdateUser(MembershipUser user) throws Throwable, system.ArgumentNullException, system.ObjectDisposedException, system.threading.AbandonedMutexException, system.ArgumentOutOfRangeException, system.OverflowException, system.ArgumentException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
classType.Invoke("UpdateUser", user == null ? null : user.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
public static boolean getEnablePasswordReset() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Get("EnablePasswordReset");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static boolean getEnablePasswordRetrieval() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Get("EnablePasswordRetrieval");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static boolean getRequiresQuestionAndAnswer() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (boolean)classType.Get("RequiresQuestionAndAnswer");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int getMaxInvalidPasswordAttempts() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Get("MaxInvalidPasswordAttempts");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int getMinRequiredNonAlphanumericCharacters() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Get("MinRequiredNonAlphanumericCharacters");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int getMinRequiredPasswordLength() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Get("MinRequiredPasswordLength");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int getPasswordAttemptWindow() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Get("PasswordAttemptWindow");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static int getUserIsOnlineTimeWindow() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (int)classType.Get("UserIsOnlineTimeWindow");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String getApplicationName() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.TypeLoadException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Get("ApplicationName");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static void setApplicationName(java.lang.String ApplicationName) throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.reflection.TargetParameterCountException, system.NotSupportedException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException, system.configuration.ConfigurationException, system.TypeLoadException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
classType.Set("ApplicationName", ApplicationName);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String getHashAlgorithmType() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Get("HashAlgorithmType");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String getPasswordStrengthRegularExpression() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Get("PasswordStrengthRegularExpression");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipProvider getProvider() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject val = (JCObject)classType.Get("Provider");
return new MembershipProvider(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static MembershipProviderCollection getProviders() throws Throwable, system.ArgumentException, system.security.SecurityException, system.ArgumentNullException, system.InvalidOperationException, system.NotSupportedException, system.MemberAccessException, system.reflection.TargetException, system.reflection.TargetParameterCountException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.web.HttpException, system.configuration.provider.ProviderException, system.configuration.ConfigurationErrorsException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
JCObject val = (JCObject)classType.Get("Providers");
return new MembershipProviderCollection(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
} | 76.95935 | 794 | 0.774165 |
dbdb4117bd443ec7f1afbda1310708cdbfbd4c43 | 2,787 | package ru.otus.spring01;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import ru.otus.spring01.domain.Answer;
import ru.otus.spring01.domain.User;
import ru.otus.spring01.services.AliceServiceImpl;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Locale;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class AliceServiceImplTest {
private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Autowired
private AliceServiceImpl aliceService;
@Autowired
private MessageSource messageSource;
@BeforeEach
public void setAlice() {
aliceService.setInputStream(System.in);
aliceService.setOutputStream(outContent);
aliceService.setLocale(Locale.forLanguageTag("ru"));
}
@Test
public void sayRawTest() {
String testText = "Test this text";
aliceService.sayRaw(testText);
Assertions.assertTrue(outContent.toString().endsWith(testText + "\n"));
}
@Test
public void sayTest() {
String testText = "enter.name";
String expectedMessage = messageSource.getMessage(testText, null, Locale.forLanguageTag("ru"));
aliceService.say(testText, null);
Assertions.assertTrue(outContent.toString().endsWith(expectedMessage + "\n"));
}
@Test
public void sayTestWithObj() {
String testText = "enter.name";
String argText = "dabadi-dabaday";
String expectedMessage = messageSource.getMessage(testText, new String[]{argText}, Locale.forLanguageTag("ru"));
aliceService.say(testText, new String[]{argText});
Assertions.assertTrue(outContent.toString().endsWith(expectedMessage + "\n"));
}
@Test
public void sayToUserTest() {
String testText = "enter.name";
User user = new User("My name is test");
String expectedMessage = messageSource.getMessage(testText, new String[]{user.getUserName()}, Locale.forLanguageTag("ru"));
aliceService.sayToUser(testText, user);
Assertions.assertTrue(outContent.toString().endsWith(expectedMessage + "\n"));
}
@Test
public void waitAnswerTest() {
String test = "Test";
PrintStream printOut = new PrintStream(outContent);
printOut.println(test);
Answer answer = aliceService.waitAnswer();
Assertions.assertEquals(test, answer.asString());
}
}
| 34.8375 | 131 | 0.714029 |
b57621b57be56e845e8bb6d9964069240d01a365 | 1,139 | package de.uni.bielefeld.sc.hterhors.psink.scio.semanticmr.slot_filling.result.goldmodrules;
import de.hterhors.semanticmr.crf.structure.annotations.AbstractAnnotation;
import de.hterhors.semanticmr.crf.variables.Instance.GoldModificationRule;
import de.uni.bielefeld.sc.hterhors.psink.scio.semanticmr.SCIOEntityTypes;
import de.uni.bielefeld.sc.hterhors.psink.scio.semanticmr.SCIOSlotTypes;
public class OnlyDefinedExpGroupResults implements GoldModificationRule {
@Override
public AbstractAnnotation modify(AbstractAnnotation result) {
AbstractAnnotation target = result.asInstanceOfEntityTemplate()
.getSingleFillerSlot(SCIOSlotTypes.hasTargetGroup).getSlotFiller();
AbstractAnnotation reference = result.asInstanceOfEntityTemplate()
.getSingleFillerSlot(SCIOSlotTypes.hasReferenceGroup).getSlotFiller();
if (target != null
&& target.asInstanceOfEntityTemplate().getEntityType() != SCIOEntityTypes.definedExperimentalGroup)
return null;
if (reference != null
&& reference.asInstanceOfEntityTemplate().getEntityType() != SCIOEntityTypes.definedExperimentalGroup)
return null;
return result;
}
}
| 39.275862 | 106 | 0.820018 |
105d899746a5fb76c8a69557acfd63f4577d145c | 1,011 | package com.alicloud.openservices.tablestore.timestream.model.expression;
import com.alicloud.openservices.tablestore.model.search.query.GeoBoundingBoxQuery;
import com.alicloud.openservices.tablestore.model.search.query.Query;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by yanglian on 2019/4/10.
*/
public class GeoBoundingBoxExpressionUnittest {
@Test
public void testBasic() {
String left = "123,345";
String right = "234,456";
GeoBoundingBoxExpression expression = new GeoBoundingBoxExpression(left, right);
String colName = "loc123";
Query query = expression.getQuery(colName);
Assert.assertTrue(query instanceof GeoBoundingBoxQuery);
GeoBoundingBoxQuery boundingBoxQuery = (GeoBoundingBoxQuery)query;
Assert.assertEquals(boundingBoxQuery.getFieldName(), colName);
Assert.assertEquals(boundingBoxQuery.getTopLeft(), left);
Assert.assertEquals(boundingBoxQuery.getBottomRight(), right);
}
}
| 37.444444 | 88 | 0.740851 |
cf51a3e8db8b8226f42a81ec1388c94daf6745f2 | 4,340 | package database;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.function.Predicate;
import java.util.Comparator;
import java.time.LocalDate;
import java.io.*;
import structures.Person;
import structures.Location;
import database.Server;
import protocol.*;
/**
* @brief This class holds datastructure and the metadata for the database.
*/
public class Database {
/**
* @brief Constructs database with associated database file.
* @param filepath Path to a database file.
*/
public Database(Server server) {
this.server = server;
}
/**
* @return Size of the underlying datastructure.
*/
public int size() {
Response ret = server.sendMessage(new RequestSize());
if (ret != null && ret instanceof ResponseSize)
return ((ResponseSize)ret).getSize();
return 0;
}
/**
* @return Date when underlying datastructure was constructed.
*/
public LocalDate constructionDate() {
Response ret = server.sendMessage(new RequestConstructionDate());
if (ret != null && ret instanceof ResponseConstructionDate)
return ((ResponseConstructionDate)ret).getConstructionDate();
return null;
}
/**
* @brief Clear the underlying datastructure.
*/
public void clear() {
server.sendMessage(new RequestClear());
}
/**
* @brief Shuffle the elements in the underlying datastructure.
*/
public void shuffle() {
server.sendMessage(new RequestShuffle());
}
/**
* @brief Add new element to the database.
* @param val Element to add.
*/
public boolean add(Person val) {
return server.sendMessage(new RequestAdd(val)) != null;
}
/**
* @brief Find an element with the same id.
* @param id Id to test against.
* @return Either index of the element or -1.
*/
public int findById(long id) {
Response ret = server.sendMessage(new RequestFind(id));
if (ret != null && ret instanceof ResponseFind)
return ((ResponseFind)ret).getIndex();
return -1;
}
/**
* @brief Replace element at index with a given.
* @param index Index at wich new element should be placed.
* @param person New element to insert.
* @return Success bool.
*/
public boolean replace(Person person) {
Response ret = server.sendMessage(new RequestReplace(person));
return ret != null && ret.isSuccessful();
}
/**
* @brief Retrieve all of the elements that are passing the test.
* @param test Test function.
* @return List of passed elements.
*/
public List<Person> retrieveWithSameLocation(Location location) {
Response ret = server.sendMessage(new RequestRetrieve(location));
if (ret != null && ret instanceof ResponseRetrieve)
return ((ResponseRetrieve)ret).getValues();
return new ArrayList<Person>();
}
/**
* @brief Remove all of the elements that pass the test.
* @param test Test function.
*/
public boolean removeIf(RequestRemove.Key key, Long value) {
Response ret = server.sendMessage(new RequestRemove(key, value));
return ret != null && ret.isSuccessful();
}
/**
* @brief Retrieve all of the elements in the sorted order.
* @param compare Comparison function.
* @return List of sorted elements.
*/
public List<Person> sortedBy(RequestSorted.Key key) {
Response ret = server.sendMessage(new RequestSorted(key));
if (ret != null && ret instanceof ResponseSorted)
return ((ResponseSorted)ret).getValues();
return new ArrayList<Person>();
}
public List<Person> retrieve() {
Response ret = server.sendMessage(new RequestRetrieve(null));
if (ret != null && ret instanceof ResponseRetrieve)
return ((ResponseRetrieve)ret).getValues();
return null;
}
public boolean isUpdateRequested() { return server.isUpdateRequested(); }
public boolean isAccessible() {
Response ret = server.sendMessage(new RequestAccess());
return ret != null && ret.isSuccessful();
}
public boolean register() {
Response ret = server.sendMessage(new RequestRegister());
return ret != null && ret.isSuccessful();
}
@Override
public String toString() {
Response ret = server.sendMessage(new RequestRetrieve(null));
if (ret != null && ret instanceof ResponseRetrieve) {
List<Person> values = ((ResponseRetrieve)ret).getValues();
String str = "";
for (Person person : values)
str += person.toString();
return str;
}
return "\n";
}
Server server;
}
| 26.625767 | 74 | 0.70553 |
f4257efa1f0765733429073aa737780114c8f434 | 10,845 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.interestrate;
import com.opengamma.financial.interestrate.annuity.definition.AnnuityCouponFixed;
import com.opengamma.financial.interestrate.annuity.definition.AnnuityCouponIbor;
import com.opengamma.financial.interestrate.annuity.definition.AnnuityCouponIborRatchet;
import com.opengamma.financial.interestrate.annuity.definition.GenericAnnuity;
import com.opengamma.financial.interestrate.bond.definition.Bond;
import com.opengamma.financial.interestrate.bond.definition.BondCapitalIndexedSecurity;
import com.opengamma.financial.interestrate.bond.definition.BondCapitalIndexedTransaction;
import com.opengamma.financial.interestrate.bond.definition.BondFixedSecurity;
import com.opengamma.financial.interestrate.bond.definition.BondFixedTransaction;
import com.opengamma.financial.interestrate.bond.definition.BondForward;
import com.opengamma.financial.interestrate.bond.definition.BondIborSecurity;
import com.opengamma.financial.interestrate.bond.definition.BondIborTransaction;
import com.opengamma.financial.interestrate.cash.definition.Cash;
import com.opengamma.financial.interestrate.fra.ForwardRateAgreement;
import com.opengamma.financial.interestrate.future.definition.BondFuture;
import com.opengamma.financial.interestrate.future.definition.BondFutureSecurity;
import com.opengamma.financial.interestrate.future.definition.BondFutureTransaction;
import com.opengamma.financial.interestrate.future.definition.InterestRateFuture;
import com.opengamma.financial.interestrate.future.definition.InterestRateFutureOptionMarginSecurity;
import com.opengamma.financial.interestrate.future.definition.InterestRateFutureOptionMarginTransaction;
import com.opengamma.financial.interestrate.future.definition.InterestRateFutureOptionPremiumSecurity;
import com.opengamma.financial.interestrate.future.definition.InterestRateFutureOptionPremiumTransaction;
import com.opengamma.financial.interestrate.inflation.derivatives.CouponInflationZeroCouponInterpolation;
import com.opengamma.financial.interestrate.inflation.derivatives.CouponInflationZeroCouponInterpolationGearing;
import com.opengamma.financial.interestrate.inflation.derivatives.CouponInflationZeroCouponMonthly;
import com.opengamma.financial.interestrate.inflation.derivatives.CouponInflationZeroCouponMonthlyGearing;
import com.opengamma.financial.interestrate.payments.CapFloorCMS;
import com.opengamma.financial.interestrate.payments.CapFloorCMSSpread;
import com.opengamma.financial.interestrate.payments.CapFloorIbor;
import com.opengamma.financial.interestrate.payments.CouponCMS;
import com.opengamma.financial.interestrate.payments.CouponFixed;
import com.opengamma.financial.interestrate.payments.CouponIbor;
import com.opengamma.financial.interestrate.payments.CouponIborFixed;
import com.opengamma.financial.interestrate.payments.CouponIborGearing;
import com.opengamma.financial.interestrate.payments.Payment;
import com.opengamma.financial.interestrate.payments.PaymentFixed;
import com.opengamma.financial.interestrate.payments.ZZZCouponOIS;
import com.opengamma.financial.interestrate.payments.derivative.CouponOIS;
import com.opengamma.financial.interestrate.swap.definition.CrossCurrencySwap;
import com.opengamma.financial.interestrate.swap.definition.FixedCouponSwap;
import com.opengamma.financial.interestrate.swap.definition.FixedFloatSwap;
import com.opengamma.financial.interestrate.swap.definition.FloatingRateNote;
import com.opengamma.financial.interestrate.swap.definition.ForexForward;
import com.opengamma.financial.interestrate.swap.definition.OISSwap;
import com.opengamma.financial.interestrate.swap.definition.Swap;
import com.opengamma.financial.interestrate.swap.definition.TenorSwap;
import com.opengamma.financial.interestrate.swaption.derivative.SwaptionBermudaFixedIbor;
import com.opengamma.financial.interestrate.swaption.derivative.SwaptionCashFixedIbor;
import com.opengamma.financial.interestrate.swaption.derivative.SwaptionPhysicalFixedIbor;
/**
*
* @param <S> The type of the data
* @param <T> The return type of the calculation
*/
public interface InterestRateDerivativeVisitor<S, T> {
// Two arguments
T visit(InterestRateDerivative derivative, S data);
T[] visit(InterestRateDerivative[] derivative, S data);
T visitBond(Bond bond, S data);
T visitBondForward(BondForward bondForward, S data);
T visitBondFuture(BondFuture bondFuture, S data);
T visitBondFutureSecurity(BondFutureSecurity bondFuture, S data);
T visitBondFutureTransaction(BondFutureTransaction bondFuture, S data);
T visitBondFixedSecurity(BondFixedSecurity bond, S data);
T visitBondFixedTransaction(BondFixedTransaction bond, S data);
T visitBondIborSecurity(BondIborSecurity bond, S data);
T visitBondIborTransaction(BondIborTransaction bond, S data);
T visitGenericAnnuity(GenericAnnuity<? extends Payment> genericAnnuity, S data);
T visitFixedCouponAnnuity(AnnuityCouponFixed fixedCouponAnnuity, S data);
T visitForwardLiborAnnuity(AnnuityCouponIbor forwardLiborAnnuity, S data);
T visitAnnuityCouponIborRatchet(AnnuityCouponIborRatchet annuity, S data);
T visitSwap(Swap<?, ?> swap, S data);
T visitFixedCouponSwap(FixedCouponSwap<?> swap, S data);
T visitFixedFloatSwap(FixedFloatSwap swap, S data);
T visitOISSwap(OISSwap swap, S data);
T visitSwaptionCashFixedIbor(SwaptionCashFixedIbor swaption, S data);
T visitSwaptionPhysicalFixedIbor(SwaptionPhysicalFixedIbor swaption, S data);
T visitSwaptionBermudaFixedIbor(SwaptionBermudaFixedIbor swaption, S data);
T visitTenorSwap(TenorSwap<? extends Payment> tenorSwap, S data);
T visitFloatingRateNote(FloatingRateNote frn, S data);
T visitCrossCurrencySwap(CrossCurrencySwap ccs, S data);
T visitForexForward(ForexForward fx, S data);
T visitCash(Cash cash, S data);
T visitInterestRateFuture(InterestRateFuture future, S data);
T visitInterestRateFutureOptionPremiumSecurity(InterestRateFutureOptionPremiumSecurity option, S data);
T visitInterestRateFutureOptionPremiumTransaction(InterestRateFutureOptionPremiumTransaction option, S data);
T visitInterestRateFutureOptionMarginSecurity(InterestRateFutureOptionMarginSecurity option, S data);
T visitInterestRateFutureOptionMarginTransaction(InterestRateFutureOptionMarginTransaction option, S data);
T visitZZZCouponOIS(ZZZCouponOIS payment, S data);
T visitFixedPayment(PaymentFixed payment, S data);
T visitFixedCouponPayment(CouponFixed payment, S data);
T visitCouponIbor(CouponIbor payment, S data);
T visitCouponIborFixed(CouponIborFixed payment, S data);
T visitCouponIborGearing(CouponIborGearing payment, S data);
T visitCouponOIS(CouponOIS payment, S data);
T visitCouponCMS(CouponCMS payment, S data);
T visitCapFloorIbor(CapFloorIbor payment, S data);
T visitCapFloorCMS(CapFloorCMS payment, S data);
T visitCapFloorCMSSpread(CapFloorCMSSpread payment, S data);
T visitForwardRateAgreement(ForwardRateAgreement fra, S data);
T visitCouponInflationZeroCouponMonthly(CouponInflationZeroCouponMonthly coupon, S data);
T visitCouponInflationZeroCouponMonthlyGearing(CouponInflationZeroCouponMonthlyGearing coupon, S data);
T visitCouponInflationZeroCouponInterpolation(CouponInflationZeroCouponInterpolation coupon, S data);
T visitCouponInflationZeroCouponInterpolationGearing(CouponInflationZeroCouponInterpolationGearing coupon, S data);
T visitBondCapitalIndexedSecurity(BondCapitalIndexedSecurity<?> bond, S data);
T visitBondCapitalIndexedTransaction(BondCapitalIndexedTransaction<?> bond, S data);
// One argument
T visit(InterestRateDerivative derivative);
T[] visit(InterestRateDerivative[] derivative);
T visitBond(Bond bond);
T visitBondForward(BondForward bondForward);
T visitBondFuture(BondFuture bondFuture);
T visitBondFutureSecurity(BondFutureSecurity bondFuture);
T visitBondFutureTransaction(BondFutureTransaction bondFuture);
T visitBondFixedSecurity(BondFixedSecurity bond);
T visitBondFixedTransaction(BondFixedTransaction bond);
T visitBondIborSecurity(BondIborSecurity bond);
T visitBondIborTransaction(BondIborTransaction bond);
T visitGenericAnnuity(GenericAnnuity<? extends Payment> genericAnnuity);
T visitFixedCouponAnnuity(AnnuityCouponFixed fixedCouponAnnuity);
T visitForwardLiborAnnuity(AnnuityCouponIbor forwardLiborAnnuity);
T visitAnnuityCouponIborRatchet(AnnuityCouponIborRatchet annuity);
T visitSwap(Swap<?, ?> swap);
T visitFixedCouponSwap(FixedCouponSwap<?> swap);
T visitFixedFloatSwap(FixedFloatSwap swap);
T visitOISSwap(OISSwap swap);
T visitSwaptionCashFixedIbor(SwaptionCashFixedIbor swaption);
T visitSwaptionPhysicalFixedIbor(SwaptionPhysicalFixedIbor swaption);
T visitSwaptionBermudaFixedIbor(SwaptionBermudaFixedIbor swaption);
T visitFloatingRateNote(FloatingRateNote frn);
T visitCrossCurrencySwap(CrossCurrencySwap ccs);
T visitForexForward(ForexForward fx);
T visitTenorSwap(TenorSwap<? extends Payment> tenorSwap);
T visitCash(Cash cash);
T visitInterestRateFutureSecurity(InterestRateFuture future);
T visitInterestRateFutureOptionPremiumSecurity(InterestRateFutureOptionPremiumSecurity option);
T visitInterestRateFutureOptionPremiumTransaction(InterestRateFutureOptionPremiumTransaction option);
T visitInterestRateFutureOptionMarginSecurity(InterestRateFutureOptionMarginSecurity option);
T visitInterestRateFutureOptionMarginTransaction(InterestRateFutureOptionMarginTransaction option);
T visitZZZCouponOIS(ZZZCouponOIS payment);
T visitFixedPayment(PaymentFixed payment);
T visitFixedCouponPayment(CouponFixed payment);
T visitCouponIborFixed(CouponIborFixed payment);
T visitCouponIbor(CouponIbor payment);
T visitCouponIborGearing(CouponIborGearing payment);
T visitCouponOIS(CouponOIS payment);
T visitCouponCMS(CouponCMS payment);
T visitCapFloorIbor(CapFloorIbor payment);
T visitCapFloorCMS(CapFloorCMS payment);
T visitCapFloorCMSSpread(CapFloorCMSSpread payment);
T visitForwardRateAgreement(ForwardRateAgreement fra);
T visitCouponInflationZeroCouponMonthly(CouponInflationZeroCouponMonthly coupon);
T visitCouponInflationZeroCouponMonthlyGearing(CouponInflationZeroCouponMonthlyGearing coupon);
T visitCouponInflationZeroCouponInterpolation(CouponInflationZeroCouponInterpolation coupon);
T visitCouponInflationZeroCouponInterpolationGearing(CouponInflationZeroCouponInterpolationGearing coupon);
T visitBondCapitalIndexedSecurity(BondCapitalIndexedSecurity<?> bond);
T visitBondCapitalIndexedTransaction(BondCapitalIndexedTransaction<?> bond);
//TODO cap / floor CMS spread
}
| 40.01845 | 117 | 0.846289 |
1d93b40e61310c5b8b83f90ef17b78e73c2f91c8 | 2,105 | /*
*@Author Shubham Maurya
*@Date April 20, 2019
*@Company pnstech Inc.*/
package com.pnstech.finalactivity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class WinnerDetail extends DarkMode {
private DatabaseReference reference ;
private RecyclerView recyclerView;
private ArrayList<WinnerProfile>list;
private WinnerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_winner_detail);
recyclerView= findViewById(R.id.pmyrecycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list=new ArrayList<>();
reference=FirebaseDatabase.getInstance().getReference().child("Winners");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
WinnerProfile p = dataSnapshot1.getValue(WinnerProfile.class);
list.add(p);
}
adapter= new WinnerAdapter(WinnerDetail.this,list);
recyclerView.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Opps! Please check your internet connection!", Toast.LENGTH_SHORT).show();
}
});
}
}
| 33.951613 | 131 | 0.704988 |
d2172c8b6596740778f4f93d9b92a8d6c5a638ef | 10,645 | package com.datastax.mcac.insights.events;
/**
* Copyright DataStax, Inc.
*
* Please see the included license file for details.
*/
import java.io.IOError;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import com.datastax.mcac.insights.Insight;
import com.datastax.mcac.insights.InsightMetadata;
import com.datastax.mcac.utils.JacksonUtil;
import com.datastax.mcac.utils.ShellUtils;
import org.apache.cassandra.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonFilter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonRawValue;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonStreamContext;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.PropertyWriter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.std.MapProperty;
/**
* Represents static configuration like jvm / yaml
*
* intended to be sent on startup
*/
public class NodeConfiguration extends Insight
{
private static final Logger logger = LoggerFactory.getLogger(NodeConfiguration.class);
public static final String NAME = "oss.insights.event.node_configuration";
private static final String MAPPING_VERSION = "oss-node-config-v1";
private static final ObjectWriter SECURE_WRITER =new ObjectMapper().addMixIn(Object.class, SecureFilterMixIn.class)
.writer(new SimpleFilterProvider().addFilter("secure filter", new SecurePropertyFilter()));
@JsonCreator
public NodeConfiguration(
@JsonProperty("metadata") InsightMetadata metadata,
@JsonProperty("data") Data data
)
{
super(
metadata,
data
);
}
public NodeConfiguration(Data data)
{
super(new InsightMetadata(
NAME,
System.currentTimeMillis(),
null,
InsightMetadata.InsightType.EVENT,
MAPPING_VERSION
), data);
}
public NodeConfiguration()
{
this(new Data());
}
public Data getData()
{
return (Data) this.data;
}
public static class Data
{
@JsonProperty("dse_config")
@JsonRawValue
public final String dseConfig;
@JsonProperty("cassandra_config")
@JsonRawValue
public final String cassandraConfig;
@JsonProperty("jvm_version")
public final String jvmVersion;
@JsonProperty("jvm_vendor")
public final String jvmVendor;
@JsonProperty("jvm_memory_max")
public final Long jvmMemoryMax;
@JsonProperty("jvm_final_flags")
public final List<String> jvmFlags;
@JsonProperty("jvm_classpath")
public final String jvmClasspath;
@JsonProperty("jvm_properties")
public final Map<String, String> jvmProperties;
@JsonProperty("jvm_startup_time")
public final Long jvmStartupTime;
@JsonProperty("os")
public final String os;
@JsonProperty("hostname")
public final String hostname;
@JsonProperty("cpu_layout")
public final List<Map<String, String>> cpuInfo;
@JsonCreator
public Data(
@JsonProperty("dse_config") final Object dseConfig,
@JsonProperty("cassandra_config") final Object cassandraConfig,
@JsonProperty("jvm_version") final String jvmVersion,
@JsonProperty("jvm_vendor") final String jvmVendor,
@JsonProperty("jvm_memory_max") final Long jvmMemoryMax,
@JsonProperty("jvm_final_flags") final List<String> jvmFlags,
@JsonProperty("jvm_classpath") final String jvmClasspath,
@JsonProperty("jvm_properties") final Map<String, String> jvmProperties,
@JsonProperty("jvm_startup_time") final Long jvmStartupTime,
@JsonProperty("os") final String os,
@JsonProperty("hostname") final String hostname,
@JsonProperty("cpu_layout") final List<Map<String, String>> cpuInfo)
{
this.dseConfig = null;
String cassandraConf = null;
try
{
cassandraConf = JacksonUtil.writeValueAsString(cassandraConfig);
}
catch (JacksonUtil.JacksonUtilException e)
{
throw new IllegalArgumentException("Error creating cassandraConfig json", e);
}
this.cassandraConfig = cassandraConf;
this.os = os;
this.hostname = hostname;
this.jvmStartupTime = jvmStartupTime;
this.cpuInfo = cpuInfo;
this.jvmProperties = jvmProperties;
this.jvmMemoryMax = jvmMemoryMax;
this.jvmVersion = jvmVersion;
this.jvmFlags = jvmFlags;
this.jvmClasspath = jvmClasspath;
this.jvmVendor = jvmVendor;
}
private Data()
{
String cassandraConf = null;
try {
Field field = null;
field = DatabaseDescriptor.class.getDeclaredField("conf");
field.setAccessible(true); // Suppress Java language access checking
Config config = (Config) field.get(null);
cassandraConf = SECURE_WRITER.writeValueAsString(config);
}
catch (NoSuchFieldException e) {
logger.error("DatabaseDescriptor has no config, this should never happen.");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.cassandraConfig = cassandraConf;
this.dseConfig = null;
String hostname = "n/a";
try
{
hostname = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e1)
{
logger.info("Could not resolve hostname");
}
this.hostname = hostname;
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
this.jvmVendor = runtime.getVmVendor();
this.jvmVersion = runtime.getVmVersion();
this.jvmClasspath = runtime.getClassPath();
this.jvmFlags = runtime.getInputArguments();
this.jvmMemoryMax = Runtime.getRuntime().maxMemory();
this.jvmProperties = runtime.getSystemProperties();
this.jvmStartupTime = runtime.getStartTime();
this.os = System.getProperty("os.name").toLowerCase();
List<Map<String, String>> tmp = Collections.EMPTY_LIST;
try
{
tmp = ShellUtils.loadCpuMap();
}
catch (IOError e)
{
if (this.os.contains("linux"))
logger.warn("Error reading cpuInfo", e);
}
this.cpuInfo = tmp;
}
}
@JsonFilter("secure filter")
static class SecureFilterMixIn {}
static class SecurePropertyFilter extends SimpleBeanPropertyFilter
{
private static final Pattern pattern = Pattern.compile("(secret|user|pass)", Pattern.CASE_INSENSITIVE);
private String createPath(PropertyWriter writer, JsonGenerator jgen)
{
StringBuilder path = new StringBuilder();
path.append(writer.getName());
JsonStreamContext sc = jgen.getOutputContext();
if (sc != null)
{
sc = sc.getParent();
}
while (sc != null)
{
if (sc.getCurrentName() != null)
{
if (path.length() > 0)
{
path.insert(0, ".");
}
path.insert(0, sc.getCurrentName());
}
sc = sc.getParent();
}
return path.toString();
}
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception
{
String path = createPath(writer, jgen);
try
{
if (!pattern.matcher(path).find())
{
if (writer instanceof MapProperty &&
writer.getType().getContentType().getRawClass() == String.class &&
((MapProperty) writer).getValue() != null &&
((MapProperty) writer).getValue().getClass() != String.class
)
{
((MapProperty) writer).setValue(((MapProperty) writer).getValue().toString());
writer.serializeAsField(pojo, jgen, provider);
}
else
{
writer.serializeAsField(pojo, jgen, provider);
}
}
else if (!jgen.canOmitFields())
{
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
catch (Throwable t)
{
//Handle errors by just omitting the field
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
}
}
| 35.016447 | 138 | 0.601221 |
b396879371d2ece635ba9e5ecfafa0381d1e8c09 | 2,121 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.internal.test;
import org.elasticsearch.gradle.internal.BuildPlugin;
import org.elasticsearch.gradle.internal.InternalTestClustersPlugin;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaBasePlugin;
import java.util.Arrays;
import java.util.List;
/**
* Adds support for starting an Elasticsearch cluster before running integration
* tests. Used in conjunction with {@link StandaloneRestTestPlugin} for qa
* projects and in conjunction with {@link BuildPlugin} for testing the rest
* client.
*/
public class RestTestPlugin implements Plugin<Project> {
private final List<String> REQUIRED_PLUGINS = Arrays.asList("elasticsearch.build", "elasticsearch.standalone-rest-test");
@Override
public void apply(final Project project) {
if (REQUIRED_PLUGINS.stream().noneMatch(requiredPlugin -> project.getPluginManager().hasPlugin(requiredPlugin))) {
throw new InvalidUserDataException(
"elasticsearch.rest-test " + "requires either elasticsearch.build or " + "elasticsearch.standalone-rest-test"
);
}
project.getPlugins().apply(RestTestBasePlugin.class);
project.getPluginManager().apply(InternalTestClustersPlugin.class);
final var integTest = project.getTasks().register("integTest", RestIntegTestTask.class, task -> {
task.setDescription("Runs rest tests against an elasticsearch cluster.");
task.setGroup(JavaBasePlugin.VERIFICATION_GROUP);
task.mustRunAfter(project.getTasks().named("precommit"));
});
project.getTasks().named("check").configure(task -> task.dependsOn(integTest));
}
}
| 45.12766 | 125 | 0.736917 |
ab13e0868024104c1235e1ad7de4c543abc2c9cd | 1,507 | package com.tangkuo.cn.rpc.mina;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @ClassName: MiNaServerHelloWorld
* @Description: (服务器端编程MiNaServer)
* @author tangkuo
* @date 2017年11月4日 下午5:33:59
*
*/
public class MiNaServer {
private static Logger logger = LoggerFactory.getLogger(MiNaServer.class);
static int PORT = 7080;
static IoAcceptor accept = null;
public static void main(String[] args) {
accept = new NioSocketAcceptor();
// 设置编码过滤器
accept.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())));
accept.getSessionConfig().setReadBufferSize(1024);
accept.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
accept.setHandler(new MyServerHandler());
try {
accept.bind(new InetSocketAddress(PORT));
} catch (IOException e) {
logger.error("server is IOException:" + e);
}
logger.info("server ->>>>" + PORT);
}
}
| 31.395833 | 79 | 0.737226 |
65a814dbbb495e6cc6e21c58c7231d6576c7302d | 786 | package com.skw359.diamond;
import org.bukkit.plugin.java.JavaPlugin;
public final class Diamond extends JavaPlugin {
@Override
public void onEnable() {
// Plugin startup logic
System.out.println("\033[36;1mDIAMOND >> \033[32;1;2mAuthenticating Java environment (build 1.8.0+) \033[0m");
System.out.println("\033[36;1mDIAMOND >> \033[32;1;2mLoading configuration...\033[0m");
System.out.println("\033[36;1mDIAMOND >> \033[32;1;2mWelcome to Diamond, \033[34;1;2mby Sky_Wizard360\033[0m");
getServer().getPluginManager().registerEvents(new BreakBlock(), this);
}
@Override
public void onDisable() {
// Plugin shutdown logic
System.out.println("\033[36;1mDIAMOND >> \033[32;1;2mDisabling...\033[0m");
}
} | 35.727273 | 119 | 0.66285 |
1e06978ff8324e2350d993ecd0b02328fb32f368 | 3,027 | package automation.testing.test.cucumber.test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.github.mkolisnyk.cucumber.runner.*;
import cucumber.api.CucumberOptions;
import org.junit.runner.RunWith;
import automation.testing.util.cucumber.CustomCucumberListener;
import java.io.IOException;
@RunWith(ExtendedCucumber.class)
@ExtendedCucumberOptions(outputFolder = "cucumber-parallel-execution-results/", jsonReport = "cucumber-parallel-execution-results/cucumber-json-report.json", retryCount = 0
, detailedReport = true, detailedAggregatedReport = true, overviewReport = true, overviewChartsReport = true, featureOverviewChart = true, coverageReport = true,
consolidatedReport = true, consolidatedReportConfig = "src/test/resources/conf/consolidated_batch.json", usageReport = true, jsonUsageReport = "cucumber-parallel-execution-results/cucumber-json-usage-report.json")
@CucumberOptions(features = "src/test/resources/features", glue = "automation.testing.test.cucumber.stepdefs", plugin =
{"automation.testing.util.cucumber.CustomCucumberListener:cucumber-parallel-execution-results/extent-report-cucumber-report-based.html"
, "html:cucumber-parallel-execution-results/cucumber-html-report"
, "json:cucumber-parallel-execution-results/cucumber-json-report.json"
, "usage:cucumber-parallel-execution-results/cucumber-json-usage-report.json"}, tags = {"@cucumber-report"})
public class ExtendedCucumberRunnerTest {
@BeforeSuite
public static void setUp() throws IOException {
Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");
Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe");
Runtime.getRuntime().exec("taskkill /F /IM phantomjs.exe");
CustomCucumberListener.isReporterStarted = true;
CustomCucumberListener.extentReports = new ExtentReports();
ExtentHtmlReporter extentHtmlReporter = new ExtentHtmlReporter("cucumber-parallel-execution-results/extent-report-cucumber-report-based.html");
extentHtmlReporter.config().setChartVisibilityOnOpen(true);
extentHtmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
extentHtmlReporter.config().setDocumentTitle("Parallel Execution Report from Cucumber Report Library");
extentHtmlReporter.config().setReportName("Cucumber Parallel Execution Report");
CustomCucumberListener.extentReports.attachReporter(extentHtmlReporter);
}
@AfterSuite
public static void tearDown() throws IOException {
Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");
Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe");
Runtime.getRuntime().exec("taskkill /F /IM phantomjs.exe");
synchronized (CustomCucumberListener.class) {
CustomCucumberListener.extentReports.flush();
}
}
} | 61.77551 | 221 | 0.765114 |
97b86309bb99c655795c332e611d4d54b77f2de7 | 2,345 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.api.common.domain.impl;
import com.jaspersoft.jasperserver.api.common.domain.Id;
import com.jaspersoft.jasperserver.api.common.domain.ValidationDetail;
/**
* @author Lucian Chirita ([email protected])
* @version $Id: ValidationDetailImpl.java 47331 2014-07-18 09:13:06Z kklein $
*/
public class ValidationDetailImpl implements ValidationDetail {
private Class validationClass;
private String name;
private String label;
private String state;
private String message;
private Exception exception;
public ValidationDetailImpl() {
}
public Id getId() {
// TODO Auto-generated method stub
return null;
}
public void setValidationClass(Class validationClass) {
this.validationClass = validationClass;
}
public Class getValidationClass() {
return validationClass;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setResult(String state) {
this.state = state;
}
public String getResult() {
return state;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setException(Exception exception) {
this.exception = exception;
}
public Exception getException() {
return exception;
}
}
| 24.175258 | 78 | 0.73774 |
b0991daa7635f03a4f1bf8344cfdd0493ab2267d | 15,594 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* 02/25/2009-2.0 Guy Pelletier
* - 265359: JPA 2.0 Element Collections - Metadata processing portions
* 06/16/2010-2.2 Guy Pelletier
* - 247078: eclipselink-orm.xml schema should allow lob and enumerated on version and id mappings
* 10/15/2010-2.2 Guy Pelletier
* - 322008: Improve usability of additional criteria applied to queries at the session/EM
* 10/27/2010-2.2 Guy Pelletier
* - 328114: @AttributeOverride does not work with nested embeddables having attributes of the same name
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3;
import org.eclipse.persistence.testing.framework.TogglingFastTableCreator;
import org.eclipse.persistence.tools.schemaframework.*;
public class AdvancedTableCreator_3 extends TogglingFastTableCreator {
public AdvancedTableCreator_3() {
setName("EJB3EmployeeProject");
this.ignoreDatabaseException = true;
/* addTableDefinition(buildADDRESSTable());
addTableDefinition(buildBUYERTable());
addTableDefinition(buildCREDITCARDSTable());
addTableDefinition(buildCREDITLINESTable());
addTableDefinition(buildCUSTOMERTable());*/
addTableDefinition(buildDEALERTable());
/* addTableDefinition(buildDEPTTable());
addTableDefinition(buildDEPT_EMPTable());
addTableDefinition(buildEMPLOYEETable());*/
addTableDefinition(buildEQUIPMENTTable());
/* addTableDefinition(buildEQUIPMENTCODETable());
addTableDefinition(buildGOLFERTable());*/
addTableDefinition(buildHUGEPROJECTTable());
addTableDefinition(buildLARGEPROJECTTable());
/* addTableDefinition(buildMANTable());
addTableDefinition(buildPARTNERLINKTable());*/
addTableDefinition(buildPHONENUMBERTable());
/* addTableDefinition(buildPHONENUMBERSTATUSTable());
addTableDefinition(buildPLATINUMBUYERTable());*/
addTableDefinition(buildPROJECT_EMPTable());
/* addTableDefinition(buildPROJECT_PROPSTable());*/
addTableDefinition(buildPROJECTTable());
/* addTableDefinition(buildRESPONSTable());
addTableDefinition(buildSALARYTable());
addTableDefinition(buildVEGETABLETable());
addTableDefinition(buildWOMANTable());
addTableDefinition(buildWORKWEEKTable());
addTableDefinition(buildWORLDRANKTable());
addTableDefinition(buildCONCURRENCYATable());
addTableDefinition(buildCONCURRENCYBTable());
addTableDefinition(buildCONCURRENCYCTable());
addTableDefinition(buildREADONLYISOLATED());
addTableDefinition(buildENTITYBTable());
addTableDefinition(buildENTITYCTable());
addTableDefinition(buildENTITYATable());
addTableDefinition(buildENTITYDTable());
addTableDefinition(buildADVENTITYAENTITYDTable());
addTableDefinition(buildENTITYETable());
addTableDefinition(buildADVENTITYAENTITYETable());
addTableDefinition(buildVIOLATIONTable());
addTableDefinition(buildVIOLATIONCODETable());
addTableDefinition(buildVIOLATIONCODESTable());
addTableDefinition(buildSTUDENTTable());
addTableDefinition(buildSCHOOLTable());
addTableDefinition(buildBOLTTable());
addTableDefinition(buildNUTTable());
addTableDefinition(buildLOOTTable())*/;
}
public TableDefinition buildDEALERTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_DEALER");
FieldDefinition field = new FieldDefinition();
field.setName("DEALER_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false);
field.setIsPrimaryKey(true);
field.setUnique(false);
field.setIsIdentity(true);
table.addField(field);
FieldDefinition field0 = new FieldDefinition();
field0.setName("FK_EMP_ID");
field0.setTypeName("NUMERIC");
field0.setSize(15);
field0.setShouldAllowNull(true);
field0.setIsPrimaryKey(false);
field0.setUnique(false);
field0.setIsIdentity(false);
// field0.setForeignKeyFieldName("MBR2_EMPLOYEE.EMP_ID");
table.addField(field0);
FieldDefinition field1 = new FieldDefinition();
field1.setName("F_NAME");
field1.setTypeName("VARCHAR");
field1.setSize(40);
field1.setShouldAllowNull(true);
field1.setIsPrimaryKey(false);
field1.setUnique(false);
field1.setIsIdentity(false);
table.addField(field1);
FieldDefinition field2 = new FieldDefinition();
field2.setName("L_NAME");
field2.setTypeName("VARCHAR");
field2.setSize(40);
field2.setShouldAllowNull(true);
field2.setIsPrimaryKey(false);
field2.setUnique(false);
field2.setIsIdentity(false);
table.addField(field2);
FieldDefinition field3 = new FieldDefinition();
field3.setName("STATUS");
field3.setTypeName("VARCHAR");
field3.setSize(40);
field3.setShouldAllowNull(true);
field3.setIsPrimaryKey(false);
field3.setUnique(false);
field3.setIsIdentity(false);
table.addField(field3);
FieldDefinition field4 = new FieldDefinition();
field4.setName("VERSION");
field4.setTypeName("NUMERIC");
field4.setSize(15);
field4.setShouldAllowNull(true);
field4.setIsPrimaryKey(false);
field4.setUnique(false);
field4.setIsIdentity(false);
table.addField(field4);
return table;
}
public TableDefinition buildEQUIPMENTTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_ADV_EQUIP");
FieldDefinition fieldID = new FieldDefinition();
fieldID.setName("ID");
fieldID.setTypeName("NUMERIC");
fieldID.setSize(15);
fieldID.setSubSize(0);
fieldID.setIsPrimaryKey(true);
fieldID.setIsIdentity(true);
fieldID.setUnique(false);
fieldID.setShouldAllowNull(false);
table.addField(fieldID);
FieldDefinition fieldNAME = new FieldDefinition();
fieldNAME.setName("DESCRIP");
fieldNAME.setTypeName("VARCHAR2");
fieldNAME.setSize(100);
fieldNAME.setSubSize(0);
fieldNAME.setIsPrimaryKey(false);
fieldNAME.setIsIdentity(false);
fieldNAME.setUnique(false);
fieldNAME.setShouldAllowNull(true);
table.addField(fieldNAME);
FieldDefinition fieldDEPTID = new FieldDefinition();
fieldDEPTID.setName("DEPT_ID");
fieldDEPTID.setTypeName("NUMERIC");
fieldDEPTID.setSize(15);
fieldDEPTID.setShouldAllowNull(true);
fieldDEPTID.setIsPrimaryKey(false);
fieldDEPTID.setUnique(false);
fieldDEPTID.setIsIdentity(false);
// fieldDEPTID.setForeignKeyFieldName("MBR1_DEPT.ID");
table.addField(fieldDEPTID);
FieldDefinition fieldCODEID = new FieldDefinition();
fieldCODEID.setName("CODE_ID");
fieldCODEID.setTypeName("NUMERIC");
fieldCODEID.setSize(15);
fieldCODEID.setShouldAllowNull(true);
fieldCODEID.setIsPrimaryKey(false);
fieldCODEID.setUnique(false);
fieldCODEID.setIsIdentity(false);
// fieldCODEID.setForeignKeyFieldName("MBR1_ADV_EQUIP_CODE.ID");
table.addField(fieldCODEID);
return table;
}
public TableDefinition buildHUGEPROJECTTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_HPROJECT");
// SECTION: FIELD
FieldDefinition field = new FieldDefinition();
field.setName("PROJ_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false );
field.setIsPrimaryKey(true );
field.setUnique(false );
field.setIsIdentity(false );
field.setForeignKeyFieldName("MBR3_PROJECT.PROJ_ID");
table.addField(field);
// SECTION: FIELD
FieldDefinition field1 = new FieldDefinition();
field1.setName("EVANGELIST_ID");
field1.setTypeName("NUMERIC");
field1.setSize(15);
field1.setShouldAllowNull(true);
field1.setIsPrimaryKey(false);
field1.setUnique(false);
field1.setIsIdentity(false);
// field1.setForeignKeyFieldName("MBR2_EMPLOYEE.EMP_ID");
table.addField(field1);
return table;
}
public TableDefinition buildLARGEPROJECTTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_LPROJECT");
// SECTION: FIELD
FieldDefinition field = new FieldDefinition();
field.setName("PROJ_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false );
field.setIsPrimaryKey(true );
field.setUnique(false );
field.setIsIdentity(false );
field.setForeignKeyFieldName("MBR3_PROJECT.PROJ_ID");
table.addField(field);
// SECTION: FIELD
FieldDefinition field1 = new FieldDefinition();
field1.setName("BUDGET");
field1.setTypeName("DOUBLE PRECIS");
field1.setSize(18);
field1.setShouldAllowNull(true );
field1.setIsPrimaryKey(false );
field1.setUnique(false );
field1.setIsIdentity(false );
table.addField(field1);
return table;
}
public TableDefinition buildPHONENUMBERTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_PHONENUMBER");
// SECTION: FIELD
FieldDefinition field = new FieldDefinition();
field.setName("OWNER_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false );
field.setIsPrimaryKey(true );
field.setUnique(false );
field.setIsIdentity(false );
// field.setForeignKeyFieldName("MBR2_EMPLOYEE.EMP_ID");
table.addField(field);
// SECTION: FIELD
FieldDefinition field1 = new FieldDefinition();
field1.setName("TYPE");
field1.setTypeName("VARCHAR");
field1.setSize(15);
field1.setShouldAllowNull(false );
field1.setIsPrimaryKey(true );
field1.setUnique(false );
field1.setIsIdentity(false );
table.addField(field1);
// SECTION: FIELD
FieldDefinition field2 = new FieldDefinition();
field2.setName("AREA_CODE");
field2.setTypeName("VARCHAR");
field2.setSize(3);
field2.setShouldAllowNull(true );
field2.setIsPrimaryKey(false );
field2.setUnique(false );
field2.setIsIdentity(false );
table.addField(field2);
// SECTION: FIELD
FieldDefinition field3 = new FieldDefinition();
field3.setName("NUMB");
field3.setTypeName("VARCHAR");
field3.setSize(8);
field3.setShouldAllowNull(true );
field3.setIsPrimaryKey(false );
field3.setUnique(false );
field3.setIsIdentity(false );
table.addField(field3);
return table;
}
public TableDefinition buildPROJECT_EMPTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_EMP_PROJ");
// SECTION: FIELD
FieldDefinition field = new FieldDefinition();
field.setName("EMPLOYEES_EMP_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false );
field.setIsPrimaryKey(true );
field.setUnique(false );
field.setIsIdentity(false );
// field.setForeignKeyFieldName("MBR2_EMPLOYEE.EMP_ID");
table.addField(field);
// SECTION: FIELD
FieldDefinition field1 = new FieldDefinition();
field1.setName("projects_PROJ_ID");
field1.setTypeName("NUMERIC");
field1.setSize(15);
field1.setShouldAllowNull(false );
field1.setIsPrimaryKey(true );
field1.setUnique(false );
field1.setIsIdentity(false );
field1.setForeignKeyFieldName("MBR3_PROJECT.PROJ_ID");
table.addField(field1);
return table;
}
public TableDefinition buildPROJECTTable() {
TableDefinition table = new TableDefinition();
table.setName("MBR3_PROJECT");
// SECTION: FIELD
FieldDefinition field = new FieldDefinition();
field.setName("PROJ_ID");
field.setTypeName("NUMERIC");
field.setSize(15);
field.setShouldAllowNull(false );
field.setIsPrimaryKey(true );
field.setUnique(false );
field.setIsIdentity(true );
table.addField(field);
// SECTION: FIELD
FieldDefinition field1 = new FieldDefinition();
field1.setName("PROJ_TYPE");
field1.setTypeName("VARCHAR");
field1.setSize(1);
field1.setShouldAllowNull(true );
field1.setIsPrimaryKey(false );
field1.setUnique(false );
field1.setIsIdentity(false );
table.addField(field1);
// SECTION: FIELD
FieldDefinition field2 = new FieldDefinition();
field2.setName("PROJ_NAME");
field2.setTypeName("VARCHAR");
field2.setSize(30);
field2.setShouldAllowNull(true );
field2.setIsPrimaryKey(false );
field2.setUnique(false );
field2.setIsIdentity(false );
table.addField(field2);
// SECTION: FIELD
FieldDefinition field3 = new FieldDefinition();
field3.setName("DESCRIP");
field3.setTypeName("VARCHAR");
field3.setSize(200);
field3.setShouldAllowNull(true );
field3.setIsPrimaryKey(false );
field3.setUnique(false );
field3.setIsIdentity(false );
table.addField(field3);
// SECTION: FIELD
FieldDefinition field4 = new FieldDefinition();
field4.setName("LEADER_ID");
field4.setTypeName("NUMERIC");
field4.setSize(15);
field4.setShouldAllowNull(true );
field4.setIsPrimaryKey(false );
field4.setUnique(false );
field4.setIsIdentity(false );
// field4.setForeignKeyFieldName("MBR2_EMPLOYEE.EMP_ID");
table.addField(field4);
// SECTION: FIELD
FieldDefinition field5 = new FieldDefinition();
field5.setName("VERSION");
field5.setTypeName("NUMERIC");
field5.setSize(15);
field5.setShouldAllowNull(true );
field5.setIsPrimaryKey(false );
field5.setUnique(false );
field5.setIsIdentity(false );
table.addField(field5);
return table;
}
}
| 37.217184 | 110 | 0.645761 |
5b87030a8f07a1019740b0624c3df7454662d533 | 4,072 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Graph{
private static class Edge{
int node;
int next;
Edge(int node, int next){
this.node = node;
this.next = next;
}
}
final static int NIL = -1;
private int[] head;
private int[] degree;
private ArrayList<Edge> graph;
private int N;
private int counter;
Graph(int N){
initialize(N);
}
public int getN() {
return N;
}
private void initialize(final int N){
head = new int[N];
degree = new int[N];
graph = new ArrayList<>();
this.N = N;
this.counter = 0;
Arrays.fill(head, NIL);
Arrays.fill(degree, 0);
}
void addEdge(int x, int y){
if (!(1 <= x && x <= N)) throw new AssertionError();
x--; y--;
graph.add(new Edge(y, head[x]));
head[x] = counter++;
degree[x]++;
}
int getHead(int node){
if (!(1 <= node && node <= N)) throw new AssertionError();
node--;
return head[node];
}
int getNext(int p){
if (!(0 <= p && p < counter)) throw new AssertionError();
return graph.get(p).next;
}
int getNeighbour(int p){
if (!(0 <= p && p < counter)) throw new AssertionError();
return graph.get(p).node + 1;
}
boolean isEmpty(int node){
if (!(1 <= node && node <= N)) throw new AssertionError();
node--;
return head[node] == NIL;
}
int size(int node){
assert 1 <= node && node <= N;
node--;
return degree[node];
}
Graph transpose(){
Graph GT = new Graph(N);
for (int i = 1; i <= N; i++) {
for (int son : getNeighbours(i))
GT.addEdge(son, i);
}
return GT;
}
List<Integer> getNeighbours(int node){
if (!(1 <= node && node <= N)) throw new AssertionError();
List<Integer> list = new ArrayList<>();
for (int p = head[node - 1]; p != NIL; p = graph.get(p).next) {
list.add(graph.get(p).node + 1);
}
return list;
}
}
class StronglyConnectedComponents {
private Graph G;
private Graph GT;
private int N;
StronglyConnectedComponents(Graph graph){
G = graph;
GT = graph.transpose();
N = graph.getN();
}
private void dfs(int node, boolean[] visited, List<Integer> list){
visited[node] = true;
for (int son : G.getNeighbours(node + 1)){
if (!visited[son - 1])
dfs(son - 1, visited, list);
}
list.add(node);
}
private void dfsT(int node, boolean[] visited, int[] color, int currentColor){
color[node] = currentColor;
visited[node] = false;
for (int son : GT.getNeighbours(node + 1)){
if (visited[son - 1])
dfsT(son - 1, visited, color, currentColor);
}
}
int[] topologicalSorting(){
boolean[] visited = new boolean[N];
Arrays.fill(visited, false);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
if (!visited[i])
dfs(i, visited, list);
}
int[] array = new int[list.size()];
for (int i = 0; i < N; i++) {
array[i] = list.get(i);
}
return array;
}
int[] computeSCCs(){
boolean[] visited = new boolean[N];
Arrays.fill(visited, false);
int[] color = new int[N];
Arrays.fill(color, -1);
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
if (!visited[i])
dfs(i, visited, list);
}
int numberOfSCCs = 0;
for (int i = N - 1; i >= 0; i--) {
int v = list.get(i);
if (visited[v]){
dfsT(v, visited, color, numberOfSCCs++);
}
}
return color;
}
}
| 22.251366 | 82 | 0.485265 |
f8be8d62ba63caed88b648f4f58e1ef411317660 | 3,891 | package breadth_first_search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 14052번 : 연구소
*
* @see https://www.acmicpc.net/problem/14052/
*
*/
public class Boj14502 {
private static final String SPACE = " ";
private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
private static final int ROW = 0;
private static final int COL = 1;
private static final int VIRUS = 2;
private static final int BLOCK = 1;
private static final int SAFETY = 0;
private static Point[] vlist = null;
private static int[][] map = null;
private static int[][] tmp = null;
private static int N = 0;
private static int M = 0;
private static int loop = 0;
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), SPACE);
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
tmp = new int[N][M];
map = new int[N][M];
vlist = new Point[11];
for(int i = 0; i < N; i++){
st = new StringTokenizer(br.readLine(), SPACE);
for(int j = 0; j < M; j++){
map[i][j] = Integer.parseInt(st.nextToken());
tmp[i][j] = map[i][j];
if(map[i][j] == VIRUS){ // 바이러스 위치를 포인트 배열에 담아줌
vlist[loop] = new Point(i, j);
loop++;
}
}
}
int max = 0;
for(int row1 = 0; row1 < N; row1++){
for(int col1 = 0; col1 < M; col1++){
if(map[row1][col1] != SAFETY) continue; // 안전지역아닌경우 넘어감
for(int row2 = 0; row2 < N; row2++){
for(int col2 = 0; col2 < M; col2++){
if(map[row2][col2] != SAFETY) continue; // 안전지역아닌경우 넘어감
for(int row3 = 0; row3 < N; row3++){
for(int col3 = 0; col3 < M; col3++){
if(map[row3][col3] != SAFETY) continue; // 안전지역아닌경우 넘어감
if(row1 == row2 && col1 == col2) continue; // 벽이 겹친경우 넘어감
if(row2 == row3 && col2 == col3) continue;
if(row3 == row1 && col3 == col1) continue;
map[row1][col1] = BLOCK; // 모든 경우의 수의 벽을 세움
map[row2][col2] = BLOCK;
map[row3][col3] = BLOCK;
int res = bfs(); // 벽을 세운 후 너비 우선 탐색을 통해 바이러스를 전파시킴
if(res > max){ // 안전지역의 최대 크기를 구함
max = res;
}
reset(); // 배열을 초기화시키고 반복
}
}
}
}
}
}
System.out.println(max); // 안전지역 최댓값 출력
}
/**
* 정점 이너 클래스
* @author minchoba
*
*/
private static class Point{
int row;
int col;
public Point(int row, int col){
this.row = row;
this.col = col;
}
}
/**
* 너비 우선 탐색 알고리즘
* @return : 안전지역의 최대 크기 반환
*/
private static int bfs(){
int space = 0;
for(int i = 0; i < loop; i++){
Queue<Point> q = new LinkedList<>();
q.offer(new Point(vlist[i].row, vlist[i].col)); // 바이러스 위치만 찾아내서
while(!q.isEmpty()){
Point current = q.poll();
for(final int[] DIRECTION : DIRECTIONS){
int nextRow = current.row + DIRECTION[ROW];
int nextCol = current.col + DIRECTION[COL];
if(nextRow >= 0 && nextRow < N && nextCol >= 0 && nextCol < M){
if(map[nextRow][nextCol] == SAFETY){ // 다음 인접한 곳이 안전지역이면
map[nextRow][nextCol] = VIRUS; // 바이러스를 퍼트리고
q.offer(new Point(nextRow, nextCol)); // 퍼진 지역으로부터 다시 탐색
}
}
}
}
}
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(map[i][j] == SAFETY){ // 안전지역의 갯수를 구함
space++;
}
}
}
return space; // 안전지역 크기 반환
}
/**
* 배열 초기화 메소드
*/
private static void reset(){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
map[i][j] = tmp[i][j];
}
}
}
}
| 23.871166 | 78 | 0.536366 |
4864f9e4679e5612e76e5720b53e09d09d205e59 | 2,113 | package gunging.ootilities.gunging_ootilities_plugin.misc.mmmechanics;
import gunging.ootilities.gunging_ootilities_plugin.OotilityCeption;
import gunging.ootilities.gunging_ootilities_plugin.containers.GOOPCManager;
import io.lumine.mythic.api.adapters.AbstractEntity;
import io.lumine.mythic.api.adapters.AbstractLocation;
import io.lumine.mythic.api.config.MythicLineConfig;
import io.lumine.mythic.api.skills.SkillMetadata;
import io.lumine.mythic.api.skills.placeholders.PlaceholderFloat;
import io.lumine.mythic.core.skills.SkillExecutor;
import io.lumine.mythic.core.skills.targeters.ILocationSelector;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class LocationsInSlash extends ILocationSelector {
@NotNull final SlashLocations<AbstractLocation> particleEffect;
public LocationsInSlash(SkillExecutor manager, MythicLineConfig mlc) {
super(manager, mlc);
particleEffect = new SlashLocations<>(mlc, (data, slashedLocation, funnies) -> {
// Exactly what the doctor ordered
return slashedLocation;
});
// Time delay not supported
particleEffect.slashDelay = PlaceholderFloat.of("0");
}
@Override
public Collection<AbstractLocation> getLocations(SkillMetadata skillMetadata) {
// Only include each entity once
HashSet<AbstractLocation> v = new HashSet<>();
// For each location targets
if (skillMetadata.getLocationTargets() != null && GOOPCManager.isLocationsInSlash()) {
for (AbstractLocation w : skillMetadata.getLocationTargets()) {
v.addAll(particleEffect.playParticleSlashEffect(skillMetadata, w)); }
}
// For each location targets
if (skillMetadata.getEntityTargets() != null && GOOPCManager.isLocationsInSlash()) {
for (AbstractEntity w : skillMetadata.getEntityTargets()) {
if (w == null) { continue; }
v.addAll(particleEffect.playParticleSlashEffect(skillMetadata, w.getLocation())); }
}
// That's the result
return v;
}
}
| 37.732143 | 99 | 0.715097 |
afa9dd3d0eb1f76f532d91c784ef96b0f0721adf | 296 | package io.github.bigbio.pgatk.io.common.psms;
import io.github.bigbio.pgatk.io.common.modification.IModification;
import java.util.List;
/**
* Created by jg on 24.09.14.
*/
public interface IPeptideSpectrumMatch {
String getSequence();
List<IModification> getModifications();
}
| 16.444444 | 67 | 0.739865 |
37ad3797f0c2953623cdd8c5fc0646605ca9df6f | 1,255 | package net.azagwen.accessible_dev_blocks;
import net.azagwen.accessible_dev_blocks.option.AdbGameOptions;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.LiteralText;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.util.shape.VoxelShapes;
import static net.azagwen.accessible_dev_blocks.AdbClient.structureVoidCycleKey;
public class StructureVoidToggleVisible {
private static AdbGameOptions settings = AdbClient.settings;
@Environment(EnvType.CLIENT)
public static void toggle() {
if (structureVoidCycleKey.isPressed()) {
settings.structVoidVisibility = !settings.structVoidVisibility;
settings.write();
if (settings.structVoidVisibility) {
MinecraftClient.getInstance().player.sendMessage(new LiteralText("Structure Void is now §aVisible."), true);
} else {
MinecraftClient.getInstance().player.sendMessage(new LiteralText("Structure Void is now §cHidden."), true);
}
}
}
public static VoxelShape shape() {
return settings.structVoidVisibility ? VoxelShapes.fullCube() : VoxelShapes.empty();
}
}
| 36.911765 | 124 | 0.726693 |
b0d6711e4d819778d1687b3ec167ca48f3c33ba2 | 782 | package dojo.extract_subclass;
/*
* A labor mezőtől függően az osztály máshogyan számol. Emeljük ki ezt a viselkedést egy LaborItem osztályba!
*/
public class JobItem {
private final double unitPrice;
private final int quantity;
private final Employee employee;
private final boolean labor;
public JobItem(double unitPrice, int quantity, Employee employee, boolean labor) {
super();
this.unitPrice = unitPrice;
this.quantity = quantity;
this.employee = employee;
this.labor = labor;
}
public double getTotalPrice() {
return getUnitPrice() * quantity;
}
public double getUnitPrice() {
return (labor ? employee.getRate() : unitPrice);
}
public int getQuantity() {
return quantity;
}
public Employee getEmployee() {
return employee;
}
}
| 20.578947 | 109 | 0.725064 |
5323fee47bdeb2741e47d03632f9f81e8c21a64e | 935 | package com.mvmlabs.springboot.dao;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.mvmlabs.springboot.domain.User;
/**
* Spring Data repository for interacting with user details data store.
*
* @author Mark Meany
*/
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
/**
* Find a users record given their name.
*
* @param name the name to identify
* @return
*/
User findByName(String name);
/**
* Find a users record given their name.
*
* @param username the name to identify
* @return
*/
User findByUsername(String username);
@Modifying
@Query("update User u set u.numberOfVisits = u.numberOfVisits + 1 where id = ?1")
void updateNumberOfVisits(Long id);
}
| 25.27027 | 85 | 0.695187 |
f36e82d20d7449f500aa3d8a87f34129abcf3ec8 | 1,355 | package io.blushine.utils;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
/**
* Various time methods
*/
public class Time {
/** ISO Date */
public static final String ISO_DATE = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
/**
* Create a simple date format from the ISO date
* @return simple date format with ISO date
*/
public static SimpleDateFormat createIsoDateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_DATE, Locale.ENGLISH);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat;
}
/**
* Create a simple date format from the ISO date in local format
* @return simple date format with ISO date
*/
public static SimpleDateFormat createIsoDateFormatLocal() {
return new SimpleDateFormat(ISO_DATE, Locale.ENGLISH);
}
/**
* Causes the currently executing thread to sleep (temporarily cease execution) for the specified
* number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
* The thread does not lose ownership of any monitors.
* @param millis the length of time to sleep in milliseconds
* @throws IllegalArgumentException if the value of {@code millis} is negative
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 28.829787 | 97 | 0.758672 |
517d2af3fd81ff3a8bfef2208931af337bf56489 | 470 | package com.force.formula.impl;
import com.force.formula.FormulaException;
import com.force.formula.util.FormulaI18nUtils;
public class NestedFormulaException extends FormulaException {
private static final long serialVersionUID = 1L;
public NestedFormulaException(Throwable t, String fieldName) {
super(FormulaI18nUtils.getLocalizer().getLabel("FormulaFieldExceptionMessages", "NestedFormulaException", fieldName, t
.getMessage()));
}
}
| 33.571429 | 126 | 0.776596 |
b75449e561c44ebe02325784c77704f014d8db22 | 1,757 | package com.weique.overhaul.v2.mvp.model.entity;
import java.util.List;
public class DataReportInfoBean {
/**
* typeName : 网格员
* departmentName : 徐州市鼓楼区
* departments : [{"Id":"bb25830d-f8fe-4b33-ab31-1cc08a5bc106","Name":"丰财街道办事处","FullPath":"徐州市鼓楼区/丰财街道办事处/","Level":2,"Count":62},{"Id":"839901b2-b245-494d-b2f4-9a45ee6c36c6","Name":"环城街道办事处","FullPath":"徐州市鼓楼区/环城街道办事处/","Level":2,"Count":60},{"Id":"d79d00a1-030a-412f-b80a-610f7acc018d","Name":"黄楼街道办事处","FullPath":"徐州市鼓楼区/黄楼街道办事处/","Level":2,"Count":24},{"Id":"5b42fd23-d110-45a0-91cb-652739c95f2c","Name":"九里街道办事处","FullPath":"徐州市鼓楼区/九里街道办事处/","Level":2,"Count":39},{"Id":"aa760fad-fb89-402c-beeb-84a5be7bfc55","Name":"牌楼街道办事处","FullPath":"徐州市鼓楼区/牌楼街道办事处/","Level":2,"Count":38},{"Id":"2f830ce5-5266-4cb6-91ee-4a5873762af7","Name":"琵琶街道办事处","FullPath":"徐州市鼓楼区/琵琶街道办事处/","Level":2,"Count":0},{"Id":"d14ff50d-6423-48c8-88b9-0d1172e70849","Name":"铜沛街道办事处","FullPath":"徐州市鼓楼区/铜沛街道办事处/","Level":2,"Count":20},{"Id":"470a733b-2d00-41cc-b2e6-020ddadd3851","Name":"武装部专属网格","FullPath":"徐州市鼓楼区/武装部专属网格/","Level":2,"Count":0}]
*/
private String typeName;
private String departmentName;
private List<GridDataBean> departments;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public List<GridDataBean> getDepartments() {
return departments;
}
public void setDepartments(List<GridDataBean> departments) {
this.departments = departments;
}
}
| 39.931818 | 924 | 0.67786 |
2a5c519822ebcee943e683eacec00d37a3b527d9 | 3,696 | // Copyright 2013 Viewfinder. All rights reserved.
// Author: Mike Purtell
package co.viewfinder;
import co.viewfinder.Time;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
import java.util.Date;
/**
* This is the fragment which holds the "single photo" image.
* It is the paging element of the ViewPager in SinglePhotoPagerFragment.
* It is created by the SinglePhotoAdapter as the SinglePhotoPagerFragment's ViewPager gets items from it.
*/
public class SinglePhotoFragment extends BaseFragment {
private final static String TAG = "Viewfinder.SinglePhotoFragment";
private final static String ARG_CONV_VIEW_DATA_ID = "co.viewfinder.conv_view_data_id";
private final static String ARG_PHOTO_POSITION = "co.viewfinder.photo_position";
private final static String ARG_HEADER_VISIBILITY = "co.viewfinder.header_visibility";
private OnSinglePhotoListener mCallback;
public interface OnSinglePhotoListener {
public void onToggleHeaderFooter();
}
public static SinglePhotoFragment newInstance(long convViewDataId, int photoPosition, int headerVisibility) {
SinglePhotoFragment singlePhotoFragment = new SinglePhotoFragment();
Bundle args = new Bundle();
args.putLong(ARG_CONV_VIEW_DATA_ID, convViewDataId);
args.putInt(ARG_PHOTO_POSITION, photoPosition);
args.putInt(ARG_HEADER_VISIBILITY, headerVisibility);
singlePhotoFragment.setArguments(args);
return singlePhotoFragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (OnSinglePhotoListener)getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
long convViewDataId = getArguments().getLong(ARG_CONV_VIEW_DATA_ID);
int photoPosition = getArguments().getInt(ARG_PHOTO_POSITION);
int headerVisibility = getArguments().getInt(ARG_HEADER_VISIBILITY);
View view = inflater.inflate(R.layout.single_photo_page, container, false);
ViewData.PhotoViewData.PhotoItemViewData photoItem =
getViewData().getConvViewDataFromId(convViewDataId).getAllPhotos().getItem(photoPosition);
PhotoView imageViewSinglePhoto = (PhotoView)view.findViewById(R.id.imageView_singlePhoto);
imageViewSinglePhoto.setScaleType(ImageView.ScaleType.FIT_CENTER);
Bitmap bitmap = getAppState().bitmapFetcher().fetch(getDisplayWidth(),
getDisplayHeight(),
BitmapFetcher.DIMENSIONS_AT_MOST,
photoItem);
imageViewSinglePhoto.setImageBitmap(bitmap);
TextView textViewTimeDate = (TextView)view.findViewById(R.id.textView_timeDate);
textViewTimeDate.setText(Time.formatExactTime(photoItem.getTimestamp()));
TextView textViewLocation = (TextView)view.findViewById(R.id.textView_location);
textViewLocation.setText(photoItem.getLocation());
RelativeLayout header = (RelativeLayout)view.findViewById(R.id.relativeLayout_singlePhotoPageHeader);
header.setVisibility(headerVisibility);
imageViewSinglePhoto.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
@Override
public void onViewTap(View v, float x, float y) {
mCallback.onToggleHeaderFooter();
}
});
return view;
}
}
| 39.741935 | 111 | 0.752706 |
7c01eff7da48a6bdf5d4c66d2b0f41d8008196a8 | 2,316 | package MulanBaseline;
import experiment.BResult_delete4;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author 郭朝彤
* @date 2017/7/13.
*/
public class PreprocessData {
public static void main(String[] args) {
CreateXML();
CreateArff();
System.out.println("done");
}
public static void CreateXML() {
List<String> facetList = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\experiment\\facet_order.txt");
StringBuffer cont = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<labels xmlns=\"http://mulan.sourceforge.net/labels\">\n");
for (String s : facetList) {
cont.append("<label name=\"" + s.replaceAll(" ", "_") + "\"></label>\n");
}
cont.append("</labels>\n");
try {
FileUtils.write(new File("C:\\Users\\tong\\Desktop\\dataset\\facet\\facet.xml"), cont.toString(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void CreateArff() {
List<String> facetList = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\experiment\\facet_order.txt");
StringBuffer cont = new StringBuffer("@relation FacetData\n\n");
for (String s : facetList) {
cont.append("@attribute " + s.replaceAll(" ", "_") + " {0, 1}\n");
}
cont.append("\n@data\n");
List<String> fileName = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\otherFiles\\Data_structure_topics.txt");
for (String name : fileName) {
cont.append("{");
List<String> topicFacet = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\good ground truth\\" + name + ".txt");
for (int i = 0; i < facetList.size(); i++) {
if (topicFacet.contains(facetList.get(i))) {
cont.append(i + " 1,");
}
}
cont.deleteCharAt(cont.length() - 1);
cont.append("}\n");
}
try {
FileUtils.write(new File("C:\\Users\\tong\\Desktop\\dataset\\facet\\facet.arff"), cont.toString(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 37.354839 | 149 | 0.568653 |
32fa2faa4bc95dffa35c5e69ca23b8aac28a3434 | 41,661 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.inventario.presentation.web.jsf.sessionbean;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Date;
import java.io.Serializable;
import com.bydan.framework.erp.util.Constantes;
import com.bydan.erp.inventario.business.entity.*;
@SuppressWarnings("unused")
public class ParametroInventarioDefectoSessionBean extends ParametroInventarioDefectoSessionBeanAdditional {
private static final long serialVersionUID = 1L;
protected Boolean isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
protected Boolean isPermiteRecargarInformacion;
protected String sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto;
protected Long lIdParametroInventarioDefectoActualForeignKey;
protected Long lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras;
protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras;
protected String sUltimaBusquedaParametroInventarioDefecto;
protected String sServletGenerarHtmlReporte;
protected Integer iNumeroPaginacion;
protected Integer iNumeroPaginacionPagina;
protected String sPathNavegacionActual="";
protected Boolean isPaginaPopup=false;
protected String sStyleDivArbol="";
protected String sStyleDivContent="";
protected String sStyleDivOpcionesBanner="";
protected String sStyleDivExpandirColapsar="";
protected String sFuncionBusquedaRapida="";
Boolean isBusquedaDesdeForeignKeySesionEmpresa;
Long lidEmpresaActual;
Boolean isBusquedaDesdeForeignKeySesionSucursal;
Long lidSucursalActual;
Boolean isBusquedaDesdeForeignKeySesionGrupoBodega;
Long lidGrupoBodegaActual;
Boolean isBusquedaDesdeForeignKeySesionCalidadProducto;
Long lidCalidadProductoActual;
Boolean isBusquedaDesdeForeignKeySesionTipoServicio;
Long lidTipoServicioActual;
Boolean isBusquedaDesdeForeignKeySesionTipoProductoServicioInven;
Long lidTipoProductoServicioInvenActual;
Boolean isBusquedaDesdeForeignKeySesionTipoProductoServicio;
Long lidTipoProductoServicioActual;
Boolean isBusquedaDesdeForeignKeySesionTipoCosteo;
Long lidTipoCosteoActual;
Boolean isBusquedaDesdeForeignKeySesionTipoProducto;
Long lidTipoProductoActual;
Boolean isBusquedaDesdeForeignKeySesionTipoViaTransporte;
Long lidTipoViaTransporteActual;
Boolean isBusquedaDesdeForeignKeySesionRangoUnidadVenta;
Long lidRangoUnidadVentaActual;
Boolean isBusquedaDesdeForeignKeySesionPais;
Long lidPaisActual;
Boolean isBusquedaDesdeForeignKeySesionCiudad;
Long lidCiudadActual;
Boolean isBusquedaDesdeForeignKeySesionColorProducto;
Long lidColorProductoActual;
Boolean isBusquedaDesdeForeignKeySesionClaseProducto;
Long lidClaseProductoActual;
Boolean isBusquedaDesdeForeignKeySesionEfectoProducto;
Long lidEfectoProductoActual;
Boolean isBusquedaDesdeForeignKeySesionMarcaProducto;
Long lidMarcaProductoActual;
Boolean isBusquedaDesdeForeignKeySesionModeloProducto;
Long lidModeloProductoActual;
Boolean isBusquedaDesdeForeignKeySesionMaterialProducto;
Long lidMaterialProductoActual;
Boolean isBusquedaDesdeForeignKeySesionSegmentoProducto;
Long lidSegmentoProductoActual;
Boolean isBusquedaDesdeForeignKeySesionTallaProducto;
Long lidTallaProductoActual;
private Long id;
private Long id_empresa;
private Long id_sucursal;
private Long id_grupo_bodega;
private Long id_calidad_producto;
private Long id_tipo_servicio;
private Long id_tipo_producto_servicio_inven;
private Long id_tipo_producto_servicio;
private Long id_tipo_costeo;
private Long id_tipo_producto;
private Long id_tipo_via_transporte;
private Long id_rango_unidad_venta;
private Long id_pais;
private Long id_ciudad;
private Long id_color_producto;
private Long id_clase_producto;
private Long id_efecto_producto;
private Long id_marca_producto;
private Long id_modelo_producto;
private Long id_material_producto;
private Long id_segmento_producto;
private Long id_talla_producto;
protected Boolean conGuardarRelaciones=false;
protected Boolean estaModoGuardarRelaciones=false;
protected Boolean esGuardarRelacionado=false;
protected Boolean estaModoBusqueda=false;
protected Boolean noMantenimiento=false;
protected ParametroInventarioDefectoSessionBeanAdditional parametroinventariodefectoSessionBeanAdditional=null;
public ParametroInventarioDefectoSessionBeanAdditional getParametroInventarioDefectoSessionBeanAdditional() {
return this.parametroinventariodefectoSessionBeanAdditional;
}
public void setParametroInventarioDefectoSessionBeanAdditional(ParametroInventarioDefectoSessionBeanAdditional parametroinventariodefectoSessionBeanAdditional) {
try {
this.parametroinventariodefectoSessionBeanAdditional=parametroinventariodefectoSessionBeanAdditional;
} catch(Exception e) {
;
}
}
public ParametroInventarioDefectoSessionBean () {
this.inicializarParametroInventarioDefectoSessionBean();
}
public void inicializarParametroInventarioDefectoSessionBean () {
this.isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto=false;
this.isPermiteRecargarInformacion=false;
this.sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto="";
this.isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto=false;
this.lIdParametroInventarioDefectoActualForeignKey=0L;
this.lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras=0L;
this.isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras=false;
this.sUltimaBusquedaParametroInventarioDefecto ="";
this.sServletGenerarHtmlReporte="";
this.iNumeroPaginacion=10;
this.iNumeroPaginacionPagina=0;
this.sPathNavegacionActual="";
this.sFuncionBusquedaRapida="";
this.sStyleDivArbol="display:table-row;width:20%;height:800px;visibility:visible";
this.sStyleDivContent="height:600px;width:80%";
this.sStyleDivOpcionesBanner="display:table-row";
this.sStyleDivExpandirColapsar="display:table-row";
this.isPaginaPopup=false;
this.estaModoGuardarRelaciones=true;
this.conGuardarRelaciones=false;
this.esGuardarRelacionado=false;
this.estaModoBusqueda=false;
this.noMantenimiento=false;
isBusquedaDesdeForeignKeySesionEmpresa=false;
lidEmpresaActual=0L;
isBusquedaDesdeForeignKeySesionSucursal=false;
lidSucursalActual=0L;
isBusquedaDesdeForeignKeySesionGrupoBodega=false;
lidGrupoBodegaActual=0L;
isBusquedaDesdeForeignKeySesionCalidadProducto=false;
lidCalidadProductoActual=0L;
isBusquedaDesdeForeignKeySesionTipoServicio=false;
lidTipoServicioActual=0L;
isBusquedaDesdeForeignKeySesionTipoProductoServicioInven=false;
lidTipoProductoServicioInvenActual=0L;
isBusquedaDesdeForeignKeySesionTipoProductoServicio=false;
lidTipoProductoServicioActual=0L;
isBusquedaDesdeForeignKeySesionTipoCosteo=false;
lidTipoCosteoActual=0L;
isBusquedaDesdeForeignKeySesionTipoProducto=false;
lidTipoProductoActual=0L;
isBusquedaDesdeForeignKeySesionTipoViaTransporte=false;
lidTipoViaTransporteActual=0L;
isBusquedaDesdeForeignKeySesionRangoUnidadVenta=false;
lidRangoUnidadVentaActual=0L;
isBusquedaDesdeForeignKeySesionPais=false;
lidPaisActual=0L;
isBusquedaDesdeForeignKeySesionCiudad=false;
lidCiudadActual=0L;
isBusquedaDesdeForeignKeySesionColorProducto=false;
lidColorProductoActual=0L;
isBusquedaDesdeForeignKeySesionClaseProducto=false;
lidClaseProductoActual=0L;
isBusquedaDesdeForeignKeySesionEfectoProducto=false;
lidEfectoProductoActual=0L;
isBusquedaDesdeForeignKeySesionMarcaProducto=false;
lidMarcaProductoActual=0L;
isBusquedaDesdeForeignKeySesionModeloProducto=false;
lidModeloProductoActual=0L;
isBusquedaDesdeForeignKeySesionMaterialProducto=false;
lidMaterialProductoActual=0L;
isBusquedaDesdeForeignKeySesionSegmentoProducto=false;
lidSegmentoProductoActual=0L;
isBusquedaDesdeForeignKeySesionTallaProducto=false;
lidTallaProductoActual=0L;
this.id_empresa=-1L;
this.id_sucursal=-1L;
this.id_grupo_bodega=-1L;
this.id_calidad_producto=-1L;
this.id_tipo_servicio=-1L;
this.id_tipo_producto_servicio_inven=-1L;
this.id_tipo_producto_servicio=-1L;
this.id_tipo_costeo=-1L;
this.id_tipo_producto=-1L;
this.id_tipo_via_transporte=-1L;
this.id_rango_unidad_venta=-1L;
this.id_pais=-1L;
this.id_ciudad=-1L;
this.id_color_producto=-1L;
this.id_clase_producto=-1L;
this.id_efecto_producto=-1L;
this.id_marca_producto=-1L;
this.id_modelo_producto=-1L;
this.id_material_producto=-1L;
this.id_segmento_producto=-1L;
this.id_talla_producto=-1L;
}
public void setPaginaPopupVariables(Boolean isPopupVariables) {
if(isPopupVariables) {
if(!this.isPaginaPopup) {
this.sStyleDivArbol="display:none;width:0px;height:0px;visibility:hidden";
this.sStyleDivContent="height:800px;width:100%";;
this.sStyleDivOpcionesBanner="display:none";
this.sStyleDivExpandirColapsar="display:none";
this.isPaginaPopup=true;
}
} else {
if(this.isPaginaPopup) {
this.sStyleDivArbol="display:table-row;width:15%;height:600px;visibility:visible;overflow:auto;";
this.sStyleDivContent="height:600px;width:80%";
this.sStyleDivOpcionesBanner="display:table-row";
this.sStyleDivExpandirColapsar="display:table-row";
this.isPaginaPopup=false;
}
}
}
public Boolean getisPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto() {
return this.isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
}
public void setisPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto(
Boolean isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto) {
this.isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto= isPermiteNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
}
public Boolean getisPermiteRecargarInformacion() {
return this.isPermiteRecargarInformacion;
}
public void setisPermiteRecargarInformacion(
Boolean isPermiteRecargarInformacion) {
this.isPermiteRecargarInformacion=isPermiteRecargarInformacion;
}
public String getsNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto() {
return this.sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
}
public void setsNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto(String sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto) {
this.sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto = sNombrePaginaNavegacionHaciaForeignKeyDesdeParametroInventarioDefecto;
}
public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto() {
return isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto;
}
public void setisBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto(
Boolean isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto) {
this.isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto= isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefecto;
}
public Long getlIdParametroInventarioDefectoActualForeignKey() {
return lIdParametroInventarioDefectoActualForeignKey;
}
public void setlIdParametroInventarioDefectoActualForeignKey(
Long lIdParametroInventarioDefectoActualForeignKey) {
this.lIdParametroInventarioDefectoActualForeignKey = lIdParametroInventarioDefectoActualForeignKey;
}
public Long getlIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras() {
return lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras;
}
public void setlIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras(
Long lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras) {
this.lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras = lIdParametroInventarioDefectoActualForeignKeyParaPosibleAtras;
}
public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras() {
return isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras;
}
public void setisBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras(
Boolean isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras) {
this.isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras = isBusquedaDesdeForeignKeySesionForeignKeyParametroInventarioDefectoParaPosibleAtras;
}
public String getsUltimaBusquedaParametroInventarioDefecto() {
return sUltimaBusquedaParametroInventarioDefecto;
}
public void setsUltimaBusquedaParametroInventarioDefecto(String sUltimaBusquedaParametroInventarioDefecto) {
this.sUltimaBusquedaParametroInventarioDefecto = sUltimaBusquedaParametroInventarioDefecto;
}
public String getsServletGenerarHtmlReporte() {
return sServletGenerarHtmlReporte;
}
public void setsServletGenerarHtmlReporte(String sServletGenerarHtmlReporte) {
this.sServletGenerarHtmlReporte = sServletGenerarHtmlReporte;
}
public Integer getiNumeroPaginacion() {
return iNumeroPaginacion;
}
public void setiNumeroPaginacion(Integer iNumeroPaginacion) {
this.iNumeroPaginacion= iNumeroPaginacion;
}
public Integer getiNumeroPaginacionPagina() {
return iNumeroPaginacionPagina;
}
public void setiNumeroPaginacionPagina(Integer iNumeroPaginacionPagina) {
this.iNumeroPaginacionPagina= iNumeroPaginacionPagina;
}
public String getsPathNavegacionActual() {
return this.sPathNavegacionActual;
}
public void setsPathNavegacionActual(String sPathNavegacionActual) {
this.sPathNavegacionActual = sPathNavegacionActual;
}
public Boolean getisPaginaPopup() {
return this.isPaginaPopup;
}
public void setisPaginaPopup(Boolean isPaginaPopup) {
this.isPaginaPopup = isPaginaPopup;
}
public String getsStyleDivArbol() {
return this.sStyleDivArbol;
}
public void setsStyleDivArbol(String sStyleDivArbol) {
this.sStyleDivArbol = sStyleDivArbol;
}
public String getsStyleDivContent() {
return this.sStyleDivContent;
}
public void setsStyleDivContent(String sStyleDivContent) {
this.sStyleDivContent = sStyleDivContent;
}
public String getsStyleDivOpcionesBanner() {
return this.sStyleDivOpcionesBanner;
}
public void setsStyleDivOpcionesBanner(String sStyleDivOpcionesBanner) {
this.sStyleDivOpcionesBanner = sStyleDivOpcionesBanner;
}
public String getsStyleDivExpandirColapsar() {
return this.sStyleDivExpandirColapsar;
}
public void setsStyleDivExpandirColapsar(String sStyleDivExpandirColapsar) {
this.sStyleDivExpandirColapsar = sStyleDivExpandirColapsar;
}
public String getsFuncionBusquedaRapida() {
return this.sFuncionBusquedaRapida;
}
public void setsFuncionBusquedaRapida(String sFuncionBusquedaRapida) {
this.sFuncionBusquedaRapida = sFuncionBusquedaRapida;
}
public Boolean getConGuardarRelaciones() {
return this.conGuardarRelaciones;
}
public void setConGuardarRelaciones(Boolean conGuardarRelaciones) {
this.conGuardarRelaciones = conGuardarRelaciones;
}
public Boolean getEstaModoGuardarRelaciones() {
return this.estaModoGuardarRelaciones;
}
public void setEstaModoGuardarRelaciones(Boolean estaModoGuardarRelaciones) {
this.estaModoGuardarRelaciones = estaModoGuardarRelaciones;
}
public Boolean getEsGuardarRelacionado() {
return this.esGuardarRelacionado;
}
public void setEsGuardarRelacionado(Boolean esGuardarRelacionado) {
this.esGuardarRelacionado = esGuardarRelacionado;
}
public Boolean getEstaModoBusqueda() {
return this.estaModoBusqueda;
}
public void setEstaModoBusqueda(Boolean estaModoBusqueda) {
this.estaModoBusqueda = estaModoBusqueda;
}
public Boolean getNoMantenimiento() {
return this.noMantenimiento;
}
public void setNoMantenimiento(Boolean noMantenimiento) {
this.noMantenimiento = noMantenimiento;
}
public Long getid() {
return this.id;
}
public Long getid_empresa() {
return this.id_empresa;
}
public Long getid_sucursal() {
return this.id_sucursal;
}
public Long getid_grupo_bodega() {
return this.id_grupo_bodega;
}
public Long getid_calidad_producto() {
return this.id_calidad_producto;
}
public Long getid_tipo_servicio() {
return this.id_tipo_servicio;
}
public Long getid_tipo_producto_servicio_inven() {
return this.id_tipo_producto_servicio_inven;
}
public Long getid_tipo_producto_servicio() {
return this.id_tipo_producto_servicio;
}
public Long getid_tipo_costeo() {
return this.id_tipo_costeo;
}
public Long getid_tipo_producto() {
return this.id_tipo_producto;
}
public Long getid_tipo_via_transporte() {
return this.id_tipo_via_transporte;
}
public Long getid_rango_unidad_venta() {
return this.id_rango_unidad_venta;
}
public Long getid_pais() {
return this.id_pais;
}
public Long getid_ciudad() {
return this.id_ciudad;
}
public Long getid_color_producto() {
return this.id_color_producto;
}
public Long getid_clase_producto() {
return this.id_clase_producto;
}
public Long getid_efecto_producto() {
return this.id_efecto_producto;
}
public Long getid_marca_producto() {
return this.id_marca_producto;
}
public Long getid_modelo_producto() {
return this.id_modelo_producto;
}
public Long getid_material_producto() {
return this.id_material_producto;
}
public Long getid_segmento_producto() {
return this.id_segmento_producto;
}
public Long getid_talla_producto() {
return this.id_talla_producto;
}
public void setid(Long newid)throws Exception
{
try {
if(this.id!=newid) {
if(newid==null) {
//newid=0L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id");
}
}
this.id=newid;
}
} catch(Exception e) {
throw e;
}
}
public void setid_empresa(Long newid_empresa)throws Exception
{
try {
if(this.id_empresa!=newid_empresa) {
if(newid_empresa==null) {
//newid_empresa=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_empresa");
}
}
this.id_empresa=newid_empresa;
}
} catch(Exception e) {
throw e;
}
}
public void setid_sucursal(Long newid_sucursal)throws Exception
{
try {
if(this.id_sucursal!=newid_sucursal) {
if(newid_sucursal==null) {
//newid_sucursal=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_sucursal");
}
}
this.id_sucursal=newid_sucursal;
}
} catch(Exception e) {
throw e;
}
}
public void setid_grupo_bodega(Long newid_grupo_bodega)throws Exception
{
try {
if(this.id_grupo_bodega!=newid_grupo_bodega) {
if(newid_grupo_bodega==null) {
//newid_grupo_bodega=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_grupo_bodega");
}
}
this.id_grupo_bodega=newid_grupo_bodega;
}
} catch(Exception e) {
throw e;
}
}
public void setid_calidad_producto(Long newid_calidad_producto)throws Exception
{
try {
if(this.id_calidad_producto!=newid_calidad_producto) {
if(newid_calidad_producto==null) {
//newid_calidad_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_calidad_producto");
}
}
this.id_calidad_producto=newid_calidad_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_servicio(Long newid_tipo_servicio)throws Exception
{
try {
if(this.id_tipo_servicio!=newid_tipo_servicio) {
if(newid_tipo_servicio==null) {
//newid_tipo_servicio=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_servicio");
}
}
this.id_tipo_servicio=newid_tipo_servicio;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_producto_servicio_inven(Long newid_tipo_producto_servicio_inven)throws Exception
{
try {
if(this.id_tipo_producto_servicio_inven!=newid_tipo_producto_servicio_inven) {
if(newid_tipo_producto_servicio_inven==null) {
//newid_tipo_producto_servicio_inven=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_producto_servicio_inven");
}
}
this.id_tipo_producto_servicio_inven=newid_tipo_producto_servicio_inven;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_producto_servicio(Long newid_tipo_producto_servicio)throws Exception
{
try {
if(this.id_tipo_producto_servicio!=newid_tipo_producto_servicio) {
if(newid_tipo_producto_servicio==null) {
//newid_tipo_producto_servicio=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_producto_servicio");
}
}
this.id_tipo_producto_servicio=newid_tipo_producto_servicio;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_costeo(Long newid_tipo_costeo)throws Exception
{
try {
if(this.id_tipo_costeo!=newid_tipo_costeo) {
if(newid_tipo_costeo==null) {
//newid_tipo_costeo=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_costeo");
}
}
this.id_tipo_costeo=newid_tipo_costeo;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_producto(Long newid_tipo_producto)throws Exception
{
try {
if(this.id_tipo_producto!=newid_tipo_producto) {
if(newid_tipo_producto==null) {
//newid_tipo_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_producto");
}
}
this.id_tipo_producto=newid_tipo_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_tipo_via_transporte(Long newid_tipo_via_transporte)throws Exception
{
try {
if(this.id_tipo_via_transporte!=newid_tipo_via_transporte) {
if(newid_tipo_via_transporte==null) {
//newid_tipo_via_transporte=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_tipo_via_transporte");
}
}
this.id_tipo_via_transporte=newid_tipo_via_transporte;
}
} catch(Exception e) {
throw e;
}
}
public void setid_rango_unidad_venta(Long newid_rango_unidad_venta)throws Exception
{
try {
if(this.id_rango_unidad_venta!=newid_rango_unidad_venta) {
if(newid_rango_unidad_venta==null) {
//newid_rango_unidad_venta=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_rango_unidad_venta");
}
}
this.id_rango_unidad_venta=newid_rango_unidad_venta;
}
} catch(Exception e) {
throw e;
}
}
public void setid_pais(Long newid_pais)throws Exception
{
try {
if(this.id_pais!=newid_pais) {
if(newid_pais==null) {
//newid_pais=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_pais");
}
}
this.id_pais=newid_pais;
}
} catch(Exception e) {
throw e;
}
}
public void setid_ciudad(Long newid_ciudad)throws Exception
{
try {
if(this.id_ciudad!=newid_ciudad) {
if(newid_ciudad==null) {
//newid_ciudad=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_ciudad");
}
}
this.id_ciudad=newid_ciudad;
}
} catch(Exception e) {
throw e;
}
}
public void setid_color_producto(Long newid_color_producto)throws Exception
{
try {
if(this.id_color_producto!=newid_color_producto) {
if(newid_color_producto==null) {
//newid_color_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_color_producto");
}
}
this.id_color_producto=newid_color_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_clase_producto(Long newid_clase_producto)throws Exception
{
try {
if(this.id_clase_producto!=newid_clase_producto) {
if(newid_clase_producto==null) {
//newid_clase_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_clase_producto");
}
}
this.id_clase_producto=newid_clase_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_efecto_producto(Long newid_efecto_producto)throws Exception
{
try {
if(this.id_efecto_producto!=newid_efecto_producto) {
if(newid_efecto_producto==null) {
//newid_efecto_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_efecto_producto");
}
}
this.id_efecto_producto=newid_efecto_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_marca_producto(Long newid_marca_producto)throws Exception
{
try {
if(this.id_marca_producto!=newid_marca_producto) {
if(newid_marca_producto==null) {
//newid_marca_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_marca_producto");
}
}
this.id_marca_producto=newid_marca_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_modelo_producto(Long newid_modelo_producto)throws Exception
{
try {
if(this.id_modelo_producto!=newid_modelo_producto) {
if(newid_modelo_producto==null) {
//newid_modelo_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_modelo_producto");
}
}
this.id_modelo_producto=newid_modelo_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_material_producto(Long newid_material_producto)throws Exception
{
try {
if(this.id_material_producto!=newid_material_producto) {
if(newid_material_producto==null) {
//newid_material_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_material_producto");
}
}
this.id_material_producto=newid_material_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_segmento_producto(Long newid_segmento_producto)throws Exception
{
try {
if(this.id_segmento_producto!=newid_segmento_producto) {
if(newid_segmento_producto==null) {
//newid_segmento_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_segmento_producto");
}
}
this.id_segmento_producto=newid_segmento_producto;
}
} catch(Exception e) {
throw e;
}
}
public void setid_talla_producto(Long newid_talla_producto)throws Exception
{
try {
if(this.id_talla_producto!=newid_talla_producto) {
if(newid_talla_producto==null) {
//newid_talla_producto=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("ParametroInventarioDefecto:Valor nulo no permitido en columna id_talla_producto");
}
}
this.id_talla_producto=newid_talla_producto;
}
} catch(Exception e) {
throw e;
}
}
public Boolean getisBusquedaDesdeForeignKeySesionEmpresa() {
return isBusquedaDesdeForeignKeySesionEmpresa;
}
public void setisBusquedaDesdeForeignKeySesionEmpresa(
Boolean isBusquedaDesdeForeignKeySesionEmpresa) {
this.isBusquedaDesdeForeignKeySesionEmpresa = isBusquedaDesdeForeignKeySesionEmpresa;
}
public Long getlidEmpresaActual() {
return lidEmpresaActual;
}
public void setlidEmpresaActual(Long lidEmpresaActual) {
this.lidEmpresaActual = lidEmpresaActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionSucursal() {
return isBusquedaDesdeForeignKeySesionSucursal;
}
public void setisBusquedaDesdeForeignKeySesionSucursal(
Boolean isBusquedaDesdeForeignKeySesionSucursal) {
this.isBusquedaDesdeForeignKeySesionSucursal = isBusquedaDesdeForeignKeySesionSucursal;
}
public Long getlidSucursalActual() {
return lidSucursalActual;
}
public void setlidSucursalActual(Long lidSucursalActual) {
this.lidSucursalActual = lidSucursalActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionGrupoBodega() {
return isBusquedaDesdeForeignKeySesionGrupoBodega;
}
public void setisBusquedaDesdeForeignKeySesionGrupoBodega(
Boolean isBusquedaDesdeForeignKeySesionGrupoBodega) {
this.isBusquedaDesdeForeignKeySesionGrupoBodega = isBusquedaDesdeForeignKeySesionGrupoBodega;
}
public Long getlidGrupoBodegaActual() {
return lidGrupoBodegaActual;
}
public void setlidGrupoBodegaActual(Long lidGrupoBodegaActual) {
this.lidGrupoBodegaActual = lidGrupoBodegaActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionCalidadProducto() {
return isBusquedaDesdeForeignKeySesionCalidadProducto;
}
public void setisBusquedaDesdeForeignKeySesionCalidadProducto(
Boolean isBusquedaDesdeForeignKeySesionCalidadProducto) {
this.isBusquedaDesdeForeignKeySesionCalidadProducto = isBusquedaDesdeForeignKeySesionCalidadProducto;
}
public Long getlidCalidadProductoActual() {
return lidCalidadProductoActual;
}
public void setlidCalidadProductoActual(Long lidCalidadProductoActual) {
this.lidCalidadProductoActual = lidCalidadProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoServicio() {
return isBusquedaDesdeForeignKeySesionTipoServicio;
}
public void setisBusquedaDesdeForeignKeySesionTipoServicio(
Boolean isBusquedaDesdeForeignKeySesionTipoServicio) {
this.isBusquedaDesdeForeignKeySesionTipoServicio = isBusquedaDesdeForeignKeySesionTipoServicio;
}
public Long getlidTipoServicioActual() {
return lidTipoServicioActual;
}
public void setlidTipoServicioActual(Long lidTipoServicioActual) {
this.lidTipoServicioActual = lidTipoServicioActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoProductoServicioInven() {
return isBusquedaDesdeForeignKeySesionTipoProductoServicioInven;
}
public void setisBusquedaDesdeForeignKeySesionTipoProductoServicioInven(
Boolean isBusquedaDesdeForeignKeySesionTipoProductoServicioInven) {
this.isBusquedaDesdeForeignKeySesionTipoProductoServicioInven = isBusquedaDesdeForeignKeySesionTipoProductoServicioInven;
}
public Long getlidTipoProductoServicioInvenActual() {
return lidTipoProductoServicioInvenActual;
}
public void setlidTipoProductoServicioInvenActual(Long lidTipoProductoServicioInvenActual) {
this.lidTipoProductoServicioInvenActual = lidTipoProductoServicioInvenActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoProductoServicio() {
return isBusquedaDesdeForeignKeySesionTipoProductoServicio;
}
public void setisBusquedaDesdeForeignKeySesionTipoProductoServicio(
Boolean isBusquedaDesdeForeignKeySesionTipoProductoServicio) {
this.isBusquedaDesdeForeignKeySesionTipoProductoServicio = isBusquedaDesdeForeignKeySesionTipoProductoServicio;
}
public Long getlidTipoProductoServicioActual() {
return lidTipoProductoServicioActual;
}
public void setlidTipoProductoServicioActual(Long lidTipoProductoServicioActual) {
this.lidTipoProductoServicioActual = lidTipoProductoServicioActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoCosteo() {
return isBusquedaDesdeForeignKeySesionTipoCosteo;
}
public void setisBusquedaDesdeForeignKeySesionTipoCosteo(
Boolean isBusquedaDesdeForeignKeySesionTipoCosteo) {
this.isBusquedaDesdeForeignKeySesionTipoCosteo = isBusquedaDesdeForeignKeySesionTipoCosteo;
}
public Long getlidTipoCosteoActual() {
return lidTipoCosteoActual;
}
public void setlidTipoCosteoActual(Long lidTipoCosteoActual) {
this.lidTipoCosteoActual = lidTipoCosteoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoProducto() {
return isBusquedaDesdeForeignKeySesionTipoProducto;
}
public void setisBusquedaDesdeForeignKeySesionTipoProducto(
Boolean isBusquedaDesdeForeignKeySesionTipoProducto) {
this.isBusquedaDesdeForeignKeySesionTipoProducto = isBusquedaDesdeForeignKeySesionTipoProducto;
}
public Long getlidTipoProductoActual() {
return lidTipoProductoActual;
}
public void setlidTipoProductoActual(Long lidTipoProductoActual) {
this.lidTipoProductoActual = lidTipoProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTipoViaTransporte() {
return isBusquedaDesdeForeignKeySesionTipoViaTransporte;
}
public void setisBusquedaDesdeForeignKeySesionTipoViaTransporte(
Boolean isBusquedaDesdeForeignKeySesionTipoViaTransporte) {
this.isBusquedaDesdeForeignKeySesionTipoViaTransporte = isBusquedaDesdeForeignKeySesionTipoViaTransporte;
}
public Long getlidTipoViaTransporteActual() {
return lidTipoViaTransporteActual;
}
public void setlidTipoViaTransporteActual(Long lidTipoViaTransporteActual) {
this.lidTipoViaTransporteActual = lidTipoViaTransporteActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionRangoUnidadVenta() {
return isBusquedaDesdeForeignKeySesionRangoUnidadVenta;
}
public void setisBusquedaDesdeForeignKeySesionRangoUnidadVenta(
Boolean isBusquedaDesdeForeignKeySesionRangoUnidadVenta) {
this.isBusquedaDesdeForeignKeySesionRangoUnidadVenta = isBusquedaDesdeForeignKeySesionRangoUnidadVenta;
}
public Long getlidRangoUnidadVentaActual() {
return lidRangoUnidadVentaActual;
}
public void setlidRangoUnidadVentaActual(Long lidRangoUnidadVentaActual) {
this.lidRangoUnidadVentaActual = lidRangoUnidadVentaActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionPais() {
return isBusquedaDesdeForeignKeySesionPais;
}
public void setisBusquedaDesdeForeignKeySesionPais(
Boolean isBusquedaDesdeForeignKeySesionPais) {
this.isBusquedaDesdeForeignKeySesionPais = isBusquedaDesdeForeignKeySesionPais;
}
public Long getlidPaisActual() {
return lidPaisActual;
}
public void setlidPaisActual(Long lidPaisActual) {
this.lidPaisActual = lidPaisActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionCiudad() {
return isBusquedaDesdeForeignKeySesionCiudad;
}
public void setisBusquedaDesdeForeignKeySesionCiudad(
Boolean isBusquedaDesdeForeignKeySesionCiudad) {
this.isBusquedaDesdeForeignKeySesionCiudad = isBusquedaDesdeForeignKeySesionCiudad;
}
public Long getlidCiudadActual() {
return lidCiudadActual;
}
public void setlidCiudadActual(Long lidCiudadActual) {
this.lidCiudadActual = lidCiudadActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionColorProducto() {
return isBusquedaDesdeForeignKeySesionColorProducto;
}
public void setisBusquedaDesdeForeignKeySesionColorProducto(
Boolean isBusquedaDesdeForeignKeySesionColorProducto) {
this.isBusquedaDesdeForeignKeySesionColorProducto = isBusquedaDesdeForeignKeySesionColorProducto;
}
public Long getlidColorProductoActual() {
return lidColorProductoActual;
}
public void setlidColorProductoActual(Long lidColorProductoActual) {
this.lidColorProductoActual = lidColorProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionClaseProducto() {
return isBusquedaDesdeForeignKeySesionClaseProducto;
}
public void setisBusquedaDesdeForeignKeySesionClaseProducto(
Boolean isBusquedaDesdeForeignKeySesionClaseProducto) {
this.isBusquedaDesdeForeignKeySesionClaseProducto = isBusquedaDesdeForeignKeySesionClaseProducto;
}
public Long getlidClaseProductoActual() {
return lidClaseProductoActual;
}
public void setlidClaseProductoActual(Long lidClaseProductoActual) {
this.lidClaseProductoActual = lidClaseProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionEfectoProducto() {
return isBusquedaDesdeForeignKeySesionEfectoProducto;
}
public void setisBusquedaDesdeForeignKeySesionEfectoProducto(
Boolean isBusquedaDesdeForeignKeySesionEfectoProducto) {
this.isBusquedaDesdeForeignKeySesionEfectoProducto = isBusquedaDesdeForeignKeySesionEfectoProducto;
}
public Long getlidEfectoProductoActual() {
return lidEfectoProductoActual;
}
public void setlidEfectoProductoActual(Long lidEfectoProductoActual) {
this.lidEfectoProductoActual = lidEfectoProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionMarcaProducto() {
return isBusquedaDesdeForeignKeySesionMarcaProducto;
}
public void setisBusquedaDesdeForeignKeySesionMarcaProducto(
Boolean isBusquedaDesdeForeignKeySesionMarcaProducto) {
this.isBusquedaDesdeForeignKeySesionMarcaProducto = isBusquedaDesdeForeignKeySesionMarcaProducto;
}
public Long getlidMarcaProductoActual() {
return lidMarcaProductoActual;
}
public void setlidMarcaProductoActual(Long lidMarcaProductoActual) {
this.lidMarcaProductoActual = lidMarcaProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionModeloProducto() {
return isBusquedaDesdeForeignKeySesionModeloProducto;
}
public void setisBusquedaDesdeForeignKeySesionModeloProducto(
Boolean isBusquedaDesdeForeignKeySesionModeloProducto) {
this.isBusquedaDesdeForeignKeySesionModeloProducto = isBusquedaDesdeForeignKeySesionModeloProducto;
}
public Long getlidModeloProductoActual() {
return lidModeloProductoActual;
}
public void setlidModeloProductoActual(Long lidModeloProductoActual) {
this.lidModeloProductoActual = lidModeloProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionMaterialProducto() {
return isBusquedaDesdeForeignKeySesionMaterialProducto;
}
public void setisBusquedaDesdeForeignKeySesionMaterialProducto(
Boolean isBusquedaDesdeForeignKeySesionMaterialProducto) {
this.isBusquedaDesdeForeignKeySesionMaterialProducto = isBusquedaDesdeForeignKeySesionMaterialProducto;
}
public Long getlidMaterialProductoActual() {
return lidMaterialProductoActual;
}
public void setlidMaterialProductoActual(Long lidMaterialProductoActual) {
this.lidMaterialProductoActual = lidMaterialProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionSegmentoProducto() {
return isBusquedaDesdeForeignKeySesionSegmentoProducto;
}
public void setisBusquedaDesdeForeignKeySesionSegmentoProducto(
Boolean isBusquedaDesdeForeignKeySesionSegmentoProducto) {
this.isBusquedaDesdeForeignKeySesionSegmentoProducto = isBusquedaDesdeForeignKeySesionSegmentoProducto;
}
public Long getlidSegmentoProductoActual() {
return lidSegmentoProductoActual;
}
public void setlidSegmentoProductoActual(Long lidSegmentoProductoActual) {
this.lidSegmentoProductoActual = lidSegmentoProductoActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionTallaProducto() {
return isBusquedaDesdeForeignKeySesionTallaProducto;
}
public void setisBusquedaDesdeForeignKeySesionTallaProducto(
Boolean isBusquedaDesdeForeignKeySesionTallaProducto) {
this.isBusquedaDesdeForeignKeySesionTallaProducto = isBusquedaDesdeForeignKeySesionTallaProducto;
}
public Long getlidTallaProductoActual() {
return lidTallaProductoActual;
}
public void setlidTallaProductoActual(Long lidTallaProductoActual) {
this.lidTallaProductoActual = lidTallaProductoActual;
}
}
| 32.220418 | 178 | 0.785675 |
7d95269dbf01a98e882671f2c8ee099dfa6c4fcc | 2,650 | // Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.jtx.meta;
import org.junit.Test;
import java.lang.reflect.Method;
import static jodd.jtx.JtxIsolationLevel.*;
import static jodd.jtx.JtxPropagationBehavior.*;
import static org.junit.Assert.assertEquals;
public class TransactionAnnotationTest {
@Transaction
public void hello() {
}
@Transaction(readOnly = false, isolation = ISOLATION_SERIALIZABLE, propagation = PROPAGATION_REQUIRES_NEW, timeout = 1000)
public void hello2() {
}
@CustomTransaction
public void hello3() {
}
@CustomTransaction(propagation = PROPAGATION_MANDATORY)
public void hello4() {
}
@Test
public void testTransactionAnnotationOnly() throws NoSuchMethodException {
TransactionAnnotation<Transaction> txAnnotation = new TransactionAnnotation<Transaction>(Transaction.class);
assertEquals(Transaction.class, txAnnotation.getAnnotationClass());
Method method = this.getClass().getMethod("hello");
TransactionAnnotationData<Transaction> annotationData = txAnnotation.readAnnotationData(method);
assertEquals(ISOLATION_DEFAULT, annotationData.isolation);
assertEquals(PROPAGATION_SUPPORTS, annotationData.propagation);
assertEquals(true, annotationData.readOnly);
assertEquals(-1, annotationData.timeout);
method = this.getClass().getMethod("hello2");
annotationData = txAnnotation.readAnnotationData(method);
assertEquals(ISOLATION_SERIALIZABLE, annotationData.isolation);
assertEquals(PROPAGATION_REQUIRES_NEW, annotationData.propagation);
assertEquals(false, annotationData.readOnly);
assertEquals(1000, annotationData.timeout);
}
@Test
public void testCustomTransactionAnnotation() throws NoSuchMethodException {
TransactionAnnotation<CustomTransaction> txAnnotation = new TransactionAnnotation<CustomTransaction>(CustomTransaction.class);
assertEquals(CustomTransaction.class, txAnnotation.getAnnotationClass());
Method method = this.getClass().getMethod("hello3");
TransactionAnnotationData<CustomTransaction> annotationData = txAnnotation.readAnnotationData(method);
assertEquals(ISOLATION_DEFAULT, annotationData.isolation);
assertEquals(PROPAGATION_REQUIRED, annotationData.propagation);
assertEquals(false, annotationData.readOnly);
assertEquals(-1, annotationData.timeout);
method = this.getClass().getMethod("hello4");
annotationData = txAnnotation.readAnnotationData(method);
assertEquals(ISOLATION_DEFAULT, annotationData.isolation);
assertEquals(PROPAGATION_MANDATORY, annotationData.propagation);
assertEquals(false, annotationData.readOnly);
assertEquals(-1, annotationData.timeout);
}
} | 34.415584 | 128 | 0.806792 |
200acd5829e4688b4a779859cc99f56260aee4f5 | 2,146 | package homework.gamestore.commands.game;
import homework.gamestore.commands.Command;
import homework.gamestore.domain.dtos.GameEditDto;
import homework.gamestore.services.GameService;
import homework.gamestore.services.UserService;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class EditGame extends Command {
private static final int COMMAND_INDEX = 0;
private static final int VALUE_INDEX = 1;
public EditGame(UserService userService, GameService gameService) {
super(userService, gameService);
}
@Override
public String execute(String... args) {
Long id = Long.parseLong(args[0]);
GameEditDto gameEditDto = getGameService().getEditGameDtoById(id);
if (gameEditDto == null) {
return String.format("Is not found game with ID %s", id);
}
for (int i = 1; i < args.length; i++) {
String[] tokens = args[i].split("=");
switch (tokens[COMMAND_INDEX]) {
case "title":
gameEditDto.setTitle(tokens[VALUE_INDEX]);
break;
case "price":
gameEditDto.setPrice(new BigDecimal(tokens[VALUE_INDEX]));
break;
case "size":
gameEditDto.setSize(Double.parseDouble(tokens[VALUE_INDEX]));
break;
case "thumbnail":
gameEditDto.setImageThumbnail(tokens[VALUE_INDEX]);
break;
case "trailer":
gameEditDto.setTrailer(tokens[VALUE_INDEX]);
break;
case "description":
gameEditDto.setDescription(tokens[VALUE_INDEX]);
break;
case "date":
gameEditDto.setReleaseDate(LocalDate.parse(tokens[VALUE_INDEX], DateTimeFormatter.ofPattern("dd-MM-yyyy")));
break;
default:
break;
}
}
return this.getGameService().editGame(gameEditDto, id);
}
}
| 34.063492 | 128 | 0.573625 |
b7c4d6ed93f146714aba6dc891319b6a18ed206f | 311 | package controllers;
import play.mvc.Controller;
import play.mvc.Result;
//TODO: This should generate individual describing the configuration, instead of constraints
public class Main extends Controller {
public static Result index() {
return ok( views.html.tan.startView.render("Welcome - TAN"));
}
} | 23.923077 | 92 | 0.765273 |
32c20068571c6aab3879242beebb0932c506ca28 | 2,102 | package com.github.nmorel.gwtjackson.objectify.shared;
import com.github.nmorel.gwtjackson.shared.ObjectReaderTester;
import com.github.nmorel.gwtjackson.shared.ObjectWriterTester;
import com.googlecode.objectify.Ref;
public final class BeanRefTester extends ObjectifyAbstractTester {
public static final BeanRefTester INSTANCE = new BeanRefTester();
private static final String BEAN_REF_JSON = "" +
"{" +
"\"key\":" +
"{\"raw\":" +
"{\"parent\":null," +
"\"kind\":\"Bean\"," +
"\"id\":1," +
"\"name\":null" +
"}" +
"}," +
"\"value\":" +
"{" +
"\"id\":1," +
"\"string\":\"string1\"," +
"\"set\":[1]" +
"}" +
"}";
private static final String BEAN_REF_NON_NULL_JSON = "" +
"{" +
"\"key\":" +
"{" +
"\"raw\":" +
"{" +
"\"kind\":\"Bean\"," +
"\"id\":1" +
"}" +
"}," +
"\"value\":" +
"{" +
"\"id\":1," +
"\"string\":\"string1\"," +
"\"set\":[1]" +
"}" +
"}";
private BeanRefTester() {
}
public void testSerialize( ObjectWriterTester<Ref<Bean>> writer ) {
assertEquals( BEAN_REF_JSON, writer.write( BEAN_REF ) );
}
public void testDeserialize( ObjectReaderTester<Ref<Bean>> reader ) {
Ref<Bean> result = reader.read( BEAN_REF_JSON );
assertEquals( BEAN_REF, result );
assertEquals( BEAN_REF.getValue(), result.getValue() );
}
public void testSerializeNonNull( ObjectWriterTester<Ref<Bean>> writer ) {
assertEquals( BEAN_REF_NON_NULL_JSON, writer.write( BEAN_REF ) );
}
public void testDeserializeNonNull( ObjectReaderTester<Ref<Bean>> reader ) {
Ref<Bean> result = reader.read( BEAN_REF_NON_NULL_JSON );
assertEquals( BEAN_REF, result );
assertEquals( BEAN_REF.getValue(), result.getValue() );
}
}
| 30.028571 | 80 | 0.501427 |
fa1d4b31f661e8c2c76cf4f6db253ca99a6dcdd2 | 699 | package com.huajiao.comm.monitor;
import java.util.Locale;
class MissInfo {
private int max_id;
private int least_timeout;
private String _roomid;
/**
* @param max_id
* @param least_timeout
*/
public MissInfo(int max_id, int least_timeout, String roomid) {
super();
this.max_id = max_id;
this.least_timeout = least_timeout;
_roomid = roomid;
}
public int getMax_id() {
return max_id;
}
/***
* 最小超时的消息的超时时间, 如果0表示没有
* */
public int getLeast_timeout() {
return least_timeout;
}
public String getRoomId(){
return _roomid;
}
@Override
public String toString() {
return String.format(Locale.US, "max_id %d, least_timeout %d", max_id, least_timeout);
}
} | 17.04878 | 88 | 0.693848 |
c7410112671672225b4127bcc7d4e23b88611a74 | 1,822 | package no.nav.arbeidsgiver.kandidat.kandidatsok.es.domene;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Date;
import java.util.Objects;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EsAnnenErfaring {
private Date fraDato;
private Date tilDato;
private String beskrivelse;
private String rolle;
public EsAnnenErfaring() {
}
public EsAnnenErfaring(Date fraDato, Date tilDato, String beskrivelse) {
this.fraDato = fraDato;
this.tilDato = tilDato;
this.beskrivelse = beskrivelse;
}
public EsAnnenErfaring(Date fraDato, Date tilDato, String beskrivelse, String rolle) {
this(fraDato, tilDato, beskrivelse);
this.rolle = rolle;
}
public Date getFraDato() {
return fraDato;
}
public Date getTilDato() {
return tilDato;
}
public String getBeskrivelse() {
return beskrivelse;
}
public String getRolle() {
return rolle;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EsAnnenErfaring that = (EsAnnenErfaring) o;
return Objects.equals(fraDato, that.fraDato) && Objects.equals(tilDato, that.tilDato)
&& Objects.equals(beskrivelse, that.beskrivelse) && Objects.equals(rolle, that.rolle);
}
@Override
public int hashCode() {
return Objects.hash(fraDato, tilDato, beskrivelse, rolle);
}
@Override
public String toString() {
return "EsAnnenErfaring{" + "fraDato=" + fraDato + ", tilDato=" + tilDato + ", beskrivelse='"
+ beskrivelse + '\'' + ", rolle='" + rolle + '\'' + '}';
}
}
| 24.293333 | 102 | 0.61416 |
2ed40a23cdf94de780211651d7ad1d058718744b | 884 | import java.util.*;
public class CCC_2009_J4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
Stack<String> words = new Stack();
words.add("TODAY");
words.add("LUCK");
words.add("GOOD");
words.add("CCC");
words.add("TO");
words.add("WELCOME");
while (!words.empty()) {
int wordletters = 0;
ArrayList<String> line = new ArrayList();
while (words.peek().length() + wordletters + line.size() <= w) {
wordletters += words.peek().length();
line.add(words.pop());
if (words.empty())
break;
}
int spaces = w - wordletters;
while (spaces > 0) {
for (int i = 0; i < Math.max(1, line.size() - 1) && spaces > 0; i++) {
line.set(i, line.get(i) + ".");
spaces--;
}
}
for (String i : line) {
System.out.print(i);
}
System.out.println();
}
}
} | 19.644444 | 74 | 0.561086 |
da6324d9fae514031db47035167eea177fdf6a31 | 13,562 | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/8.0.15
* Generated at: 2015-01-07 00:05:49 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.Enumeration;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;
import org.apache.catalina.manager.JspHelper;
import org.apache.catalina.util.ContextName;
public final class sessionDetail_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, false, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
out = pageContext.getOut();
_jspx_out = out;
out.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html\n");
out.write(" PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
out.write(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("\n");
out.write("\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n");
String path = (String) request.getAttribute("path");
String version = (String) request.getAttribute("version");
ContextName cn = new ContextName(path, version);
Session currentSession = (Session)request.getAttribute("currentSession");
String currentSessionId = null;
HttpSession currentHttpSession = null;
if (currentSession != null) {
currentHttpSession = currentSession.getSession();
currentSessionId = JspHelper.escapeXml(currentSession.getId());
} else {
currentSessionId = "Session invalidated";
}
String submitUrl = JspHelper.escapeXml(response.encodeURL(
((HttpServletRequest) pageContext.getRequest()).getRequestURI() +
"?path=" + path + "&version=" + version));
out.write("\n");
out.write("<head>\n");
out.write(" <meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\"/>\n");
out.write(" <meta http-equiv=\"pragma\" content=\"no-cache\"/><!-- HTTP 1.0 -->\n");
out.write(" <meta http-equiv=\"cache-control\" content=\"no-cache,must-revalidate\"/><!-- HTTP 1.1 -->\n");
out.write(" <meta http-equiv=\"expires\" content=\"0\"/><!-- 0 is an invalid value and should be treated as 'now' -->\n");
out.write(" <meta http-equiv=\"content-language\" content=\"en\"/>\n");
out.write(" <meta name=\"author\" content=\"Cedrik LIME\"/>\n");
out.write(" <meta name=\"copyright\" content=\"copyright 2005-2014 the Apache Software Foundation\"/>\n");
out.write(" <meta name=\"robots\" content=\"noindex,nofollow,noarchive\"/>\n");
out.write(" <title>Sessions Administration: details for ");
out.print( currentSessionId );
out.write("</title>\n");
out.write("</head>\n");
out.write("<body>\n");
if (currentHttpSession == null) {
out.write("\n");
out.write(" <h1>");
out.print(currentSessionId);
out.write("</h1>\n");
} else {
out.write("\n");
out.write(" <h1>Details for Session ");
out.print( currentSessionId );
out.write("</h1>\n");
out.write("\n");
out.write(" <table style=\"text-align: left;\" border=\"0\">\n");
out.write(" <tr>\n");
out.write(" <th>Session Id</th>\n");
out.write(" <td>");
out.print( currentSessionId );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Guessed Locale</th>\n");
out.write(" <td>");
out.print( JspHelper.guessDisplayLocaleFromSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Guessed User</th>\n");
out.write(" <td>");
out.print( JspHelper.guessDisplayUserFromSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Creation Time</th>\n");
out.write(" <td>");
out.print( JspHelper.getDisplayCreationTimeForSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Last Accessed Time</th>\n");
out.write(" <td>");
out.print( JspHelper.getDisplayLastAccessedTimeForSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Session Max Inactive Interval</th>\n");
out.write(" <td>");
out.print( JspHelper.secondsToTimeString(currentSession.getMaxInactiveInterval()) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Used Time</th>\n");
out.write(" <td>");
out.print( JspHelper.getDisplayUsedTimeForSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>Inactive Time</th>\n");
out.write(" <td>");
out.print( JspHelper.getDisplayInactiveTimeForSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <th>TTL</th>\n");
out.write(" <td>");
out.print( JspHelper.getDisplayTTLForSession(currentSession) );
out.write("</td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write("\n");
out.write(" <form method=\"post\" action=\"");
out.print( submitUrl );
out.write("\">\n");
out.write(" <div>\n");
out.write(" <input type=\"hidden\" name=\"sessionId\" value=\"");
out.print( currentSessionId );
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"action\" value=\"sessionDetail\" />\n");
out.write(" ");
if ("Primary".equals(request.getParameter("sessionType"))) {
out.write("\n");
out.write(" <input type=\"hidden\" name=\"sessionType\" value=\"Primary\" />\n");
out.write(" ");
}
out.write(" <input type=\"submit\" value=\"Refresh\" />\n");
out.write(" </div>\n");
out.write(" </form>\n");
out.write("\n");
out.write(" <div class=\"error\">");
out.print( JspHelper.escapeXml(request.getAttribute("error")) );
out.write("</div>\n");
out.write(" <div class=\"message\">");
out.print( JspHelper.escapeXml(request.getAttribute("message")) );
out.write("</div>\n");
out.write("\n");
out.write(" <table style=\"text-align: left;\" border=\"1\" cellpadding=\"2\" cellspacing=\"2\">\n");
out.write(" ");
int nAttributes = 0;
Enumeration attributeNamesEnumeration = currentHttpSession.getAttributeNames();
while (attributeNamesEnumeration.hasMoreElements()) {
attributeNamesEnumeration.nextElement();
++nAttributes;
}
out.write("\n");
out.write(" <caption style=\"font-variant: small-caps;\">");
out.print( JspHelper.formatNumber(nAttributes) );
out.write(" attributes</caption>\n");
out.write(" <thead>\n");
out.write(" <tr>\n");
out.write(" <th>Remove Attribute</th>\n");
out.write(" <th>Attribute name</th>\n");
out.write(" <th>Attribute value</th>\n");
out.write(" </tr>\n");
out.write(" </thead>\n");
out.write(" ");
out.write("\n");
out.write(" <tbody>\n");
out.write(" ");
attributeNamesEnumeration = currentHttpSession.getAttributeNames();
while (attributeNamesEnumeration.hasMoreElements()) {
String attributeName = (String) attributeNamesEnumeration.nextElement();
out.write("\n");
out.write(" <tr>\n");
out.write(" <td align=\"center\">\n");
out.write(" <form method=\"post\" action=\"");
out.print( submitUrl );
out.write("\">\n");
out.write(" <div>\n");
out.write(" <input type=\"hidden\" name=\"action\" value=\"removeSessionAttribute\" />\n");
out.write(" <input type=\"hidden\" name=\"sessionId\" value=\"");
out.print( currentSessionId );
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"attributeName\" value=\"");
out.print( JspHelper.escapeXml(attributeName) );
out.write("\" />\n");
out.write(" ");
if ("Primary".equals(request.getParameter("sessionType"))) {
out.write("\n");
out.write(" <input type=\"submit\" value=\"Remove\" />\n");
out.write(" <input type=\"hidden\" name=\"sessionType\" value=\"Primary\" />\n");
out.write(" ");
} else {
out.print("Primary sessions only");
}
out.write("\n");
out.write(" </div>\n");
out.write(" </form>\n");
out.write(" </td>\n");
out.write(" <td>");
out.print( JspHelper.escapeXml(attributeName) );
out.write("</td>\n");
out.write(" <td>");
Object attributeValue = currentHttpSession.getAttribute(attributeName);
out.write("<span title=\"");
out.print( attributeValue == null ? "" : attributeValue.getClass().toString() );
out.write('"');
out.write('>');
out.print( JspHelper.escapeXml(attributeValue) );
out.write("</span></td>\n");
out.write(" </tr>\n");
out.write(" ");
} // end while
out.write("\n");
out.write(" </tbody>\n");
out.write(" </table>\n");
} // endif
out.write("\n");
out.write("\n");
out.write("<form method=\"post\" action=\"");
out.print(submitUrl);
out.write("\">\n");
out.write(" <p style=\"text-align: center;\">\n");
out.write(" <input type=\"submit\" value=\"Return to session list\" />\n");
out.write(" </p>\n");
out.write("</form>\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 41.987616 | 173 | 0.561864 |
ff066a2b06b8e4f4146842593aa68ec920daeb93 | 342 | package com.innoq.mploed.ddd.creditAgency;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CreditAgencyApplication {
public static void main(String[] args) {
SpringApplication.run(CreditAgencyApplication.class);
}
}
| 28.5 | 68 | 0.807018 |
1771039c6b135f5cffb3d167f518a1f825bdef34 | 2,101 | /**
* This class is the teacher's solution
* for the Nested loop exercises from lab7
* originally from 360-420 Prog for Sci
* there are other ways to do this, you
* are seeing the solution that came to
* mind today.
*
* @author PMCampbell
* @version today
**/
import java.util.Scanner;
public class NestedLoops {
public static void main(String[] args) {
System.out.println("drawTopTriangle(5, '*')");
drawTopTriangle(5, '*');
System.out.println("drawBottomTriangle(4, '+')");
drawBottomTriangle(4, '+');
System.out.println("drawStairs(7, '@')");
drawStairs(7, '@');
} // end main()
/**
* draws a triangle on the screen with the top
* max width equal to count
*
* @param int count maximum base of inverted triangle
* @param char disp the char to display on screen
*/
public static void drawTopTriangle(int count, char disp) {
int charStart =-1;
for (int row=0;row < count;row++) { // row
for (int col=0; col < count;col++) { // cols
if (col<=charStart) {
System.out.print(' ');
}else {
System.out.print(disp);
}
}
System.out.println();
charStart++;
}
} // drawTopTriangle()
/**
* draws a triangle on the screen with the bottom
* max width equal to count
*
* @param int count maximum base of inverted triangle
* @param char disp the char to display on screen
*/
public static void drawBottomTriangle(int count, char disp) {
for (int row=0;row < count;row++) { // row
for (int col=0; col <=row ;col++) { // cols
System.out.print(disp);
}
System.out.println();
}
} // drawBottomTriangle()
/**
* draws a diagonal on the screen the
* bottom point at count
*
* @param int count maximum base of inverted triangle
* @param char disp the char to display on screen
*/
public static void drawStairs(int count, char disp) {
for (int row=0;row < count;row++) { // row
for (int col=0; col <row ;col++) { // cols
System.out.print(' ');
}
System.out.println(disp);
}
} // drawStairs()
} // end class
| 26.2625 | 61 | 0.615421 |
f4b2317fc5df143628787bb96623fa9f0d5da295 | 5,644 | package byow.lab13;
import byow.Core.RandomUtils;
import edu.princeton.cs.introcs.StdDraw;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
public class MemoryGame {
/** The width of the window of this game. */
private int width;
/** The height of the window of this game. */
private int height;
/** The current round the user is on. */
private int round;
/** The Random object used to randomly generate Strings. */
private Random rand;
/** Whether or not the game is over. */
private boolean gameOver;
/** Whether or not it is the player's turn. Used in the last section of the
* spec, 'Helpful UI'. */
private boolean playerTurn;
/** Current encouragement string, changes on every round */
private String encouragement;
/** The characters we generate random Strings from. */
private static final char[] CHARACTERS = "abcdefghijklmnopqrstuvwxyz".toCharArray();
/** Encouraging phrases. Used in the last section of the spec, 'Helpful UI'. */
private static final String[] ENCOURAGEMENT = {"You can do this!", "I believe in you!",
"You got this!", "You're a star!", "Go Bears!",
"Too easy for you!", "Wow, so impressive!"};
public MemoryGame(int width, int height, long seed) {
/* Sets up StdDraw so that it has a width by height grid of 16 by 16 squares as its canvas
* Also sets up the scale so the top left is (0,0) and the bottom right is (width, height)
*/
this.width = width;
this.height = height;
StdDraw.setCanvasSize(this.width * 16, this.height * 16);
Font font = new Font("Monaco", Font.BOLD, 30);
StdDraw.setFont(font);
StdDraw.setXscale(0, this.width);
StdDraw.setYscale(0, this.height);
StdDraw.clear(Color.BLACK);
StdDraw.enableDoubleBuffering();
//TODO: Initialize random number generator
this.rand = new Random(seed);
}
public String generateRandomString(int n) {
//TODO: Generate random string of letters of length n
String result = "";
while (result.length() < n) {
result += CHARACTERS[RandomUtils.uniform(this.rand, CHARACTERS.length)];
}
return result;
}
// public String generateRandomEncouragement() {
// return ENCOURAGEMENT[RandomUtils.uniform(rand, ENCOURAGEMENT.length)];
// }
public void drawFrame(String s) {
//TODO: Take the string and display it in the center of the screen
StdDraw.clear(Color.BLACK);
StdDraw.setPenColor(Color.WHITE);
Font font = new Font("Monaco", Font.BOLD, 30);
StdDraw.setFont(font);
StdDraw.text(this.width / 2, this.height / 2, s);
//TODO: If game is not over, display relevant game information at the top of the screen
if (!gameOver) {
Font smallFont = new Font("Monaco", Font.BOLD, 20);
StdDraw.setFont(smallFont);
StdDraw.line(0, this.height - 2, this.width, this.height - 2);
StdDraw.textLeft(0, this.height - 1, "Round: " + this.round);
if (this.playerTurn) {
StdDraw.text(this.width/2, this.height - 1, "Type!");
} else {
StdDraw.text(this.width/2, this.height - 1, "Watch!");
}
int randomEncouragement = RandomUtils.uniform(this.rand, ENCOURAGEMENT.length);
StdDraw.textRight(this.width, this.height - 1, ENCOURAGEMENT[randomEncouragement]);
}
StdDraw.show();
}
public void flashSequence(String letters) {
//TODO: Display each character in letters, making sure to blank the screen between letters
for (int i = 0; i < letters.length(); i++) {
Character current = letters.charAt(i);
this.drawFrame(current.toString());
StdDraw.pause(500);
this.drawFrame("");
StdDraw.pause(500);
}
}
public String solicitNCharsInput(int n) {
//TODO: Read n letters of player input
String userInput = "";
while(userInput.length() < n) {
if (StdDraw.hasNextKeyTyped()) {
char current = StdDraw.nextKeyTyped();
userInput += current;
this.drawFrame(userInput);
}
}
return userInput;
}
public void startGame() {
//TODO: Set any relevant variables before the game starts
this.round = 1;
String randomString = "";
String userInput = "";
//TODO: Establish Engine loop
while(randomString.equals(userInput)) {
this.playerTurn = false;
StdDraw.pause(1000);
this.drawFrame("Round: " + this.round);
StdDraw.pause(1000);
randomString = this.generateRandomString(this.round);
this.flashSequence(randomString);
this.playerTurn = true;
userInput = this.solicitNCharsInput(this.round);
this.round += 1;
}
this.round -= 1;
this.gameOver = true;
this.drawFrame("Game Over: You made it to round: " + round);
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please enter a seed");
return;
}
long seed = Long.parseLong(args[0]);
MemoryGame game = new MemoryGame(40, 40, seed);
game.startGame();
}
}
| 38.135135 | 99 | 0.581148 |
064c39893ff1ddc4b5e87c6f5200f2fa321deecd | 422 | package gaarason.database.contracts.builder;
import gaarason.database.query.Builder;
public interface Lock<T> {
/**
* lock in share mode 不会阻塞其它事务读取被锁定行记录的值
* 相对适用于,两张以及多张表存在业务关系时的一致性要求,性能稍好,但易发生死锁
* @return 查询构造器
*/
Builder<T> sharedLock();
/**
* for update 会阻塞其他锁定性读对锁定行的读取
* 相对适用于,适用于操作同一张表时的一致性要求,性能稍弱,但不会发生死锁
* @return 查询构造器
*/
Builder<T> lockForUpdate();
}
| 20.095238 | 45 | 0.661137 |
b55c22e6779c12d1fe629618472e1adeb5a92f81 | 141 | package com.diter.motiondetection;
public interface MotionDetectorCallback {
void onMotionDetected(byte[] img);
void onTooDark();
}
| 20.142857 | 41 | 0.758865 |
f9d5674c3b4c52a59830f3ddea636c7a405455ba | 944 | package com.ruoyi.system.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.ruoyi.system.domain.SysNotice;
/**
* 公告 数据层
*
* @author ruoyi
*/
@Mapper
public interface SysNoticeMapper
{
/**
* 查询公告信息
*
* @param noticeId 公告ID
* @return 公告信息
*/
SysNotice selectNoticeById(Long noticeId);
/**
* 查询公告列表
*
* @param notice 公告信息
* @return 公告集合
*/
List<SysNotice> selectNoticeList(SysNotice notice);
/**
* 新增公告
*
* @param notice 公告信息
* @return 结果
*/
int insertNotice(SysNotice notice);
/**
* 修改公告
*
* @param notice 公告信息
* @return 结果
*/
int updateNotice(SysNotice notice);
/**
* 批量删除公告
*
* @param noticeIds 需要删除的数据ID
* @return 结果
*/
int deleteNoticeByIds(String[] noticeIds);
} | 16.857143 | 57 | 0.53072 |
89db340d7d5dcb8f6df14f44ea39b14084b48690 | 1,302 | package Logica;
import Logica.Risorse.Risorsa;
import java.util.ArrayList;
/**
* classe per le componenti attualmente mostrate all'utente
* @author Francesco Rocchetti
*/
public class ComponentiMostrati {
private ArrayList<Componente> alc;
public ComponentiMostrati(){
alc = new ArrayList<>();
}
public void add(Componente c){
alc.add(c);
}
public void change(ArrayList<Componente> alc){
this.alc = alc;
}
public Componente getCompbyId(int id){
for(Componente c: alc){
if(c.getId() == id)
return c;
}
return null;
}
public ArrayList<String> getDetails(int id){
ArrayList<Risorsa> tempR = new ArrayList<>();
for(Componente c: alc){
if(c.getId() == id)
tempR = c.getRisorse();
}
ArrayList<String> tempS = new ArrayList<>();
for(Risorsa r: tempR){
tempS.add(r.getName()+" "+r.getValue());
}
return tempS;
}
public ArrayList<ArrayList<String>> getLista(){
ArrayList<ArrayList<String>> als = new ArrayList<>();
for(Componente c: alc){
if(c.getN()>0){
als.add(c.getString());
}
}
return als;
}
}
| 21.344262 | 61 | 0.545315 |
fa4ddd00aed82bf647e650e9c908bf78372e5c10 | 4,471 | /*
* Copyright (C) 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.cast.refplayer.utils;
import com.google.sample.cast.refplayer.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
/**
* A collection of utility methods, all static.
*/
public class Utils {
private static final String TAG = "Utils";
/*
* Making sure public utility methods remain static
*/
private Utils() {
}
@SuppressWarnings("deprecation")
/**
* Returns the screen/display size
*
*/
public static Point getDisplaySize(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
return new Point(width, height);
}
/**
* Returns {@code true} if and only if the screen orientation is portrait.
*/
public static boolean isOrientationPortrait(Context context) {
return context.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT;
}
/**
* Shows an error dialog with a given text message.
*/
public static void showErrorDialog(Context context, String errorString) {
new AlertDialog.Builder(context).setTitle(R.string.error)
.setMessage(errorString)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
/**
* Shows an "Oops" error dialog with a text provided by a resource ID
*/
public static void showOopsDialog(Context context, int resourceId) {
new AlertDialog.Builder(context).setTitle(R.string.oops)
.setMessage(context.getString(resourceId))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setIcon(R.drawable.ic_action_alerts_and_states_warning)
.create()
.show();
}
/**
* Gets the version of app.
*/
public static String getAppVersionName(Context context) {
String versionString = null;
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
0 /* basic info */);
versionString = info.versionName;
} catch (Exception e) {
// do nothing
}
return versionString;
}
/**
* Shows a (long) toast.
*/
public static void showToast(Context context, int resourceId) {
Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
}
/**
* Formats time from milliseconds to hh:mm:ss string format.
*/
public static String formatMillis(int millisec) {
int seconds = (int) (millisec / 1000);
int hours = seconds / (60 * 60);
seconds %= (60 * 60);
int minutes = seconds / 60;
seconds %= 60;
String time;
if (hours > 0) {
time = String.format("%d:%02d:%02d", hours, minutes, seconds);
} else {
time = String.format("%d:%02d", minutes, seconds);
}
return time;
}
}
| 32.165468 | 99 | 0.613062 |
72f1263b4968c674a2902f573d1810456935cc4c | 3,136 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.spreadsheet.engine;
import walkingkooka.spreadsheet.reference.SpreadsheetCellRange;
import walkingkooka.spreadsheet.reference.SpreadsheetCellReference;
import walkingkooka.spreadsheet.reference.SpreadsheetExpressionReferenceVisitor;
import walkingkooka.spreadsheet.reference.SpreadsheetLabelName;
import walkingkooka.spreadsheet.reference.store.TargetAndSpreadsheetCellReference;
/**
* A {@link SpreadsheetExpressionReferenceVisitor} that adds references to each reference present within cell formula.
*/
final class BasicSpreadsheetEngineChangesAddReferencesExpressionVisitorSpreadsheetExpressionReferenceVisitor extends SpreadsheetExpressionReferenceVisitor {
static BasicSpreadsheetEngineChangesAddReferencesExpressionVisitorSpreadsheetExpressionReferenceVisitor with(final SpreadsheetCellReference target,
final SpreadsheetEngineContext context) {
return new BasicSpreadsheetEngineChangesAddReferencesExpressionVisitorSpreadsheetExpressionReferenceVisitor(target, context);
}
// VisibleForTesting
BasicSpreadsheetEngineChangesAddReferencesExpressionVisitorSpreadsheetExpressionReferenceVisitor(final SpreadsheetCellReference target,
final SpreadsheetEngineContext context) {
super();
this.target = target;
this.context = context;
}
@Override
protected void visit(final SpreadsheetCellReference reference) {
this.context.storeRepository()
.cellReferences()
.addReference(TargetAndSpreadsheetCellReference.with(this.target, reference));
}
@Override
protected void visit(final SpreadsheetLabelName label) {
this.context.storeRepository()
.labelReferences()
.addReference(TargetAndSpreadsheetCellReference.with(label, this.target));
}
@Override
protected void visit(final SpreadsheetCellRange range) {
this.context.storeRepository()
.rangeToCells()
.addValue(range, this.target);
}
/**
* The target cell.
*/
private final SpreadsheetCellReference target;
/**
* Used to get stores.
*/
private final SpreadsheetEngineContext context;
@Override
public String toString() {
return this.target.toString();
}
}
| 39.2 | 156 | 0.702487 |
e4ac90835fceed1e26ef9939b36a668ff96a45be | 340 | package com.xinglefly.event;
public class NetWorkEvent {
private boolean isNetwork;
public boolean isNetwork() {
return isNetwork;
}
public void setIsNetwork(boolean isNetwork) {
this.isNetwork = isNetwork;
}
public NetWorkEvent(boolean isNetwork) {
this.isNetwork = isNetwork;
}
}
| 17 | 49 | 0.655882 |
96d7f2e3eebc5b91b26d97d7a28b043a3afcd618 | 1,956 | package com.staff.staffapp;
public class Constants {
public static final String BUSINESS_PRODUCTS_URL="https://fathomless-tor-95579.herokuapp.com/api/businesses";
public static final String PERSONAL_PRODUCTS_URL="https://fathomless-tor-95579.herokuapp.com/api/personals";
public static final String BUSINESS_SCHOOL_URL="https://e-class-portal.herokuapp.com/";
/* Azure AD Constants */
/* Authority is in the form of https://login.microsoftonline.com/yourtenant.onmicrosoft.com */
public static final String AUTHORITY = "https://login.microsoftonline.com/19a4db07-607d-475f-a518-0e3b699ac7d0";
/* The clientID of your application is a unique identifier which can be obtained from the app registration portal */
public static final String CLIENT_ID = "d86666b7-b3a0-46e9-aa57-4a161025d768";
/* Resource URI of the endpoint which will be accessed */
public static final String RESOURCE_ID = "https://graph.microsoft.com/";
/* The Redirect URI of the application (Optional) */
public static final String REDIRECT_URI = "https://login.microsoftonline.com/common/oauth2/nativeclient";
/* Microsoft Graph Constants */
public static final String MSGRAPH_URL = "https://graph.microsoft.com/v1.0/me";
/* Constant to send message to the mAcquireTokenHandler to do acquire token with Prompt.Auto*/
public static final int MSG_INTERACTIVE_SIGN_IN_PROMPT_AUTO = 1;
/* Constant to send message to the mAcquireTokenHandler to do acquire token with Prompt.Always */
public static final int MSG_INTERACTIVE_SIGN_IN_PROMPT_ALWAYS = 2;
/* Constant to store user id in shared preferences */
public static final String USER_ID = "user_id";
/* Telemetry variables */
// Flag to turn event aggregation on/off
public static final boolean sTelemetryAggregationIsRequired = true;
public static final String IMAGE_URL = "https://graph.microsoft.com/v1.0/me/photos/48x48/$value";
}
| 59.272727 | 120 | 0.752556 |
8bd71381132cb9b79fcc84c079c9157b28235c89 | 5,508 | package com.alimama.mdrill.index.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 确保tdate类型转换成正确的符合solr的格式
* @author peng.chen
*
*/
public class TdateFormat {
public static final String yyyymmdd_regex = "(\\d{4})(\\d{2})(\\d{2})";
public static final Pattern yyyymmdd_pattern = Pattern.compile(yyyymmdd_regex);
public static final Matcher yyyymmdd_matcher = yyyymmdd_pattern.matcher("");
public static final String yyyy_mm_dd_regex = "(\\d{4})-(\\d{2})-(\\d{2})";
public static final Pattern yyyy_mm_dd_pattern = Pattern.compile(yyyy_mm_dd_regex);
public static final Matcher yyyy_mm_dd_matcher = yyyy_mm_dd_pattern.matcher("");
public static final String yyyy_mm_dd_2_regex = "(\\d{4})/(\\d{2})/(\\d{2})";
public static final Pattern yyyy_mm_dd_2_pattern = Pattern.compile(yyyy_mm_dd_2_regex);
public static final Matcher yyyy_mm_dd_2_matcher = yyyy_mm_dd_2_pattern.matcher("");
public static final String yyyymmddhhsshh_regex = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
public static final Pattern yyyymmddhhsshh_pattern = Pattern.compile(yyyymmddhhsshh_regex);
public static final Matcher yyyymmddhhsshh_matcher = yyyymmddhhsshh_pattern.matcher("");
public static final String yyyy_mm_dd_hh_ss_hh_regex = "(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2})";
public static final Pattern yyyy_mm_dd_hh_ss_hh_pattern = Pattern.compile(yyyy_mm_dd_hh_ss_hh_regex);
public static final Matcher yyyy_mm_dd_hh_ss_hh_matcher = yyyy_mm_dd_hh_ss_hh_pattern.matcher("");
public static final String valid_regex = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z";
public static final Pattern valid_pattern = Pattern.compile(valid_regex);
public static final Matcher valid_matcher = valid_pattern.matcher("");
public static void main(String[] args) {
System.out.println(TdateFormat.ensureTdate("2013/01/02", ""));;
}
/**
*
* @param string
* @return
*/
public static String ensureTdate(String string, String fieldName) {
if(string==null)
{
return "2099-09-09T00:00:00Z";
}
try{
yyyymmdd_matcher.reset(string);
int len=string.length();
if(len==8&&yyyymmdd_matcher.find()){
return yyyymmdd_matcher.group(1)+"-"+yyyymmdd_matcher.group(2)+"-"+yyyymmdd_matcher.group(3)+"T00:00:00Z";
}
yyyy_mm_dd_matcher.reset(string);
if(len==10&&yyyy_mm_dd_matcher.find()){
return yyyy_mm_dd_matcher.group(1)+"-"+yyyy_mm_dd_matcher.group(2)+"-"+yyyy_mm_dd_matcher.group(3)+"T00:00:00Z";
}
yyyy_mm_dd_2_matcher.reset(string);
if(len==10&&yyyy_mm_dd_2_matcher.find()){
return yyyy_mm_dd_2_matcher.group(1)+"-"+yyyy_mm_dd_2_matcher.group(2)+"-"+yyyy_mm_dd_2_matcher.group(3)+"T00:00:00Z";
}
yyyymmddhhsshh_matcher.reset(string);
if(len==14&&yyyymmddhhsshh_matcher.find()){
return yyyymmddhhsshh_matcher.group(1)+"-"+yyyymmddhhsshh_matcher.group(2)+"-"+yyyymmddhhsshh_matcher.group(3)+"T"+yyyymmddhhsshh_matcher.group(4)+":"+yyyymmddhhsshh_matcher.group(5)+":"+yyyymmddhhsshh_matcher.group(6)+"Z";
}
yyyy_mm_dd_hh_ss_hh_matcher.reset(string);
if(len==19&&yyyy_mm_dd_hh_ss_hh_matcher.find()){
return yyyy_mm_dd_hh_ss_hh_matcher.group(1)+"T"+yyyy_mm_dd_hh_ss_hh_matcher.group(2)+"Z";
}
valid_matcher.reset(string);
if(valid_matcher.find()){
return valid_matcher.group();
}
return "2099-09-09T00:00:00Z";
}catch(Exception e){
}
return "2099-09-09T00:00:00Z";
}
//yyyy-mm-dd
//yyyy/mm/dd
//yyyy-mm-dd hh:mm:ss
public static String ensureTdateForSearch(String string) {
try{
int len=string.length();
yyyy_mm_dd_matcher.reset(string);
if(len==10&&yyyy_mm_dd_matcher.find()){
return yyyy_mm_dd_matcher.group(1)+"-"+yyyy_mm_dd_matcher.group(2)+"-"+yyyy_mm_dd_matcher.group(3)+"T00:00:00Z";
}
yyyy_mm_dd_2_matcher.reset(string);
if(len==10&&yyyy_mm_dd_2_matcher.find()){
return yyyy_mm_dd_2_matcher.group(1)+"-"+yyyy_mm_dd_2_matcher.group(2)+"-"+yyyy_mm_dd_2_matcher.group(3)+"T00:00:00Z";
}
yyyy_mm_dd_hh_ss_hh_matcher.reset(string);
if(len==19&&yyyy_mm_dd_hh_ss_hh_matcher.find()){
return yyyy_mm_dd_hh_ss_hh_matcher.group(1)+"T"+yyyy_mm_dd_hh_ss_hh_matcher.group(2)+"Z";
}
valid_matcher.reset(string);
if(valid_matcher.find()){
return valid_matcher.group();
}
return "2099-09-09T00:00:00Z";
}catch(Exception e){
}
return "2099-09-09T00:00:00Z";
}
public static String transformSolrMetacharactor(String input){
StringBuffer sb = new StringBuffer();
String regex = "[+\\-&|!(){}\\[\\]^\"~?:(\\)]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()){
matcher.appendReplacement(sb, "\\\\"+matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}
public static String transformSolrMetacharactorNoLike(String input){
StringBuffer sb = new StringBuffer();
String regex = "[+\\-&|!(){}\\[\\]^\"~?:(\\)*]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()){
matcher.appendReplacement(sb, "\\\\"+matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}
}
| 34.641509 | 231 | 0.661402 |
d04f4e42788cbf1b9461b7552ce6b4b666151bc2 | 2,466 | /*
* The MIT License
*
* Copyright 2013-2015 Florian Barras.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jeo.math.filters;
import jeo.common.io.IOManager;
import jeo.common.util.Strings;
import jeo.math.linearalgebra.Scalar;
public class Console
{
/**
* Starts the console.
* <p>
* @param args the command line arguments
*/
public static void main(final String[] args)
{
// Clear the console and the logs
IOManager.clear();
// Interactions with the user to get the measurements of the position to
// be searched and give the estimated position with the Kalman filter
interactions();
}
/**
* Interacts with the user.
*/
private static void interactions()
{
// Initialization
final KalmanFilter filter = new KalmanFilter();
// Initial guess
filter.x = new Scalar(1.);
// double[][] F =
// {
// {
// 1, 2
// },
// {
// 3, 4
// }
// };
// filter.F = new Matrix(F);
boolean running = true;
String expression;
// Process
do
{
// Predict the position (a priori)
filter.predict();
// Get the input
expression = IOManager.getInputLine().trim();
if (Strings.toLowerCase(expression).contains("exit"))
{
IOManager.printInfo("Good bye!");
running = false;
}
// Correct the position (a posteriori)
else
{
final Scalar y = new Scalar(Double.parseDouble(expression));
filter.correct(y);
}
}
while (running);
}
}
| 27.707865 | 80 | 0.694242 |
210535770e5f3aaa80213f7d7a9f6aa3bea07329 | 4,007 | /*
* Copyright (c) 2018 - 2020, Thales DIS CPL Canada, 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.thales.chaos.shellclient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(Parameterized.class)
public class ShellClientTest {
private static final String capability = UUID.randomUUID().toString();
private static final List<String> commandsInOrder = List.of("command -v", "which", "type");
private static final List<Integer> exitCodes = List.of(0, 1, 127);
private final SortedMap<String, Integer> commandAndExitCode;
private ShellClient shellClient;
private AtomicInteger expected;
private Map<String, Integer> expectedCalls = new HashMap<>();
public ShellClientTest (SortedMap<String, Integer> commandAndExitCode) {
this.commandAndExitCode = commandAndExitCode;
}
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> params () {
List<Object[]> params = new ArrayList<>();
/*
I would love to somehow do this in a recursive way, but I can't think of how
to right now. Enjoy the nested For loops!
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
params.add(new Object[]{ buildCommandAndExitCode(List.of(exitCodes.get(i), exitCodes.get(j), exitCodes
.get(k))) });
}
}
}
return params;
}
private static SortedMap<String, Integer> buildCommandAndExitCode (List<Integer> exitCodes) {
assertEquals(commandsInOrder.size(), exitCodes.size());
final SortedMap<String, Integer> map = new TreeMap<>(Comparator.comparingInt(commandsInOrder::indexOf));
for (int i = 0; i < commandsInOrder.size(); i++) {
map.put(commandsInOrder.get(i), exitCodes.get(i));
}
return map;
}
@Before
public void setUp () {
shellClient = mock(ShellClient.class);
doCallRealMethod().when(shellClient).checkDependency(any());
expected = new AtomicInteger(1);
commandAndExitCode.entrySet()
.stream()
.peek(stringIntegerEntry -> doReturn(ShellOutput.builder()
.withExitCode(stringIntegerEntry.getValue())
.build()).when(shellClient).runCommand(stringIntegerEntry.getKey() + " " + capability))
.forEach(stringIntegerEntry -> {
expectedCalls.put(stringIntegerEntry.getKey(), expected.get());
if (expected.get() == 1 && stringIntegerEntry.getValue() == 0) {
expected.set(0);
}
});
}
@Test
public void checkDependency () {
assertEquals(expected.get() == 0, shellClient.checkDependency(capability));
expectedCalls.forEach((s, i) -> verify(shellClient, times(i)).runCommand(s + " " + capability));
}
} | 41.739583 | 161 | 0.600948 |
93e58b4f2fce4fff40bd47dc72cd97ceed20735b | 486 | package netflix.adminresources;
@AdminPage
public class HealthCheckPlugin extends AbstractAdminPageInfo {
public static final String PAGE_ID = "karyon2_healthCheck";
public static final String NAME = "HealthCheck";
public HealthCheckPlugin() {
super(PAGE_ID, NAME);
}
@Override
public String getJerseyResourcePackageList() {
return "netflix.adminresources";
}
@Override
public boolean isVisible() {
return false;
}
}
| 21.130435 | 63 | 0.6893 |
03024bc18ed57bce3487def602f6f8ecc330d18f | 1,620 | package com.space.cornerstone.framework.core.redis;
import com.space.cornerstone.framework.core.util.RedisLockUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 锁的延长时间守护线程
*
* @author chen qi
* @date 2020-10-29 18:50
**/
@Slf4j
public class LockExpandDaemonRunnable implements Runnable {
private final RedisClient redisClient;
private final String key;
private final String value;
private final int lockTime;
public LockExpandDaemonRunnable(RedisClient redisClient, String key, String value, int lockTime) {
this.redisClient = redisClient;
this.key = key;
this.value = value;
this.lockTime = lockTime;
this.signal = Boolean.TRUE;
}
private volatile Boolean signal;
public void stop() {
this.signal = Boolean.FALSE;
}
@Override
public void run() {
// 先等待锁的过期时间的三分之二 如果还持有锁 进行一次续期 重复
int waitTime = lockTime * 1000 * 2 / 3;
while (signal) {
try {
Thread.sleep(waitTime);
if (RedisLockUtil.expandLockTime(redisClient, key, value, lockTime)) {
// 延长过期时间成功
log.debug("延长过期时间成功,本次等待{}ms,将重置key为{}的锁超时时间重置为{}s", waitTime, key, lockTime);
} else {
log.debug("延长过期时间失败, 此线程LockExpandDaemonRunnable中断");
this.stop();
}
} catch (InterruptedException e) {
log.debug("此线程LockExpandDaemonRunnable被强制中断", e);
} catch (Exception e) {
log.error("锁的延长时间守护线程发送异常", e);
}
}
}
}
| 27.931034 | 102 | 0.588272 |
b84f7dde2b7e8b2aec9d9f8e5606a34fbc8114b8 | 778 | package io.pivotal.db;
import org.springframework.data.gemfire.mapping.Region;
import org.springframework.data.gemfire.repository.Query;
import org.springframework.data.gemfire.repository.query.annotation.Import;
import org.springframework.data.repository.CrudRepository;
import io.pivotal.model.Property;
@Region("Property")
public interface PropertyRepository extends CrudRepository<Property, Long> {
@Query("SELECT * FROM /Property p WHERE p.address LIKE $1 LIMIT 5")
Iterable<Property> findAFewByAddressFuzzy(String address);
Iterable<Property> findByAddressIgnoreCaseContaining(String address);
@Query("SELECT count(*) FROM /Property p")
Integer getCountOfProperties();
@Query("SELECT p.address FROM /Property p LIMIT 5")
Iterable<String> getProperties();
}
| 32.416667 | 76 | 0.802057 |
8a2321ff68f2bac477a0cfc6810b9ea54acf5590 | 11,060 | /*
* Copyright (C) 2021 Gwinnett County Experimental Aircraft Association
*
* 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.eaa690.aerie.steps;
import io.cucumber.java.PendingException;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.http.ContentType;
import org.eaa690.aerie.TestContext;
import org.eaa690.aerie.TestDataFactory;
import org.eaa690.aerie.model.Member;
import org.eaa690.aerie.model.RFIDRequest;
import org.hamcrest.Matchers;
/**
* Roster test steps.
*/
public class RosterSteps extends BaseSteps {
/**
* Roster service.
*/
private final String ROSTER = "roster/";
/**
* Email service.
*/
private final String EMAIL = "email/";
/**
* Slack service.
*/
private final String SLACK = "slack/";
/**
* Constructor.
*
* @param testContext TestContext
*/
public RosterSteps(final TestContext testContext) {
super(testContext);
}
@Given("^I am not a chapter member$")
public void iAmNotAChapterMember() {
testContext.setRosterId(null);
}
@Given("^I am a new chapter member$")
public void iAmANewMember() {
final Member member = TestDataFactory.getMember();
throw new PendingException();
}
@Given("^I am a chapter member$")
public void iAmAnExistingMember() {
testContext.setRosterId("42648");
}
@Given("^I have a record in the roster management system$")
public void iHaveARecord() {
throw new PendingException();
}
@Given("^I do not have a record in the roster management system$")
public void iDoNotHaveARecord() {
throw new PendingException();
}
@Given("^email is (.*)$")
public void emailEnabled(final String flag) {
String enabled = "true";
if ("disabled".equalsIgnoreCase(flag)) {
enabled = "false";
}
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(EMAIL + "enabled/" + enabled)
.then().log().all());
}
@Given("^slack is (.*)$")
public void slackEnabled(final String flag) {
String enabled = "true";
if ("disabled".equalsIgnoreCase(flag)) {
enabled = "false";
}
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(SLACK + "enabled/" + enabled)
.then().log().all());
}
@When("^I request an update of the roster data$")
public void iRequestUpdateRosterData() {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(ROSTER + "update")
.then().log().all());
}
@When("^I update member (.*)'s RFID with (.*)$")
public void iUpdateMemberRFID(final String memberId, final String rfid) {
final RFIDRequest rfidRequest = new RFIDRequest();
rfidRequest.setRfid(rfid);
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.body(rfidRequest)
.put(ROSTER + memberId + "/rfid")
.then().log().all());
}
@When("^I find a member by their RFID (.*)$")
public void iFindMemberByRFID(final String rfid) {
final RFIDRequest rfidRequest = new RFIDRequest();
rfidRequest.setRfid(rfid);
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.body(rfidRequest)
.post(ROSTER + "find-by-rfid")
.then().log().all());
}
@When("^I request the expiration data for member with ID (.*)$")
public void iRequestExpirationData(final String memberId) {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.get(ROSTER + memberId + "/expiration")
.then().log().all());
}
@When("^I request RFID data for all members$")
public void iRequestAllRFIDData() {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.get(ROSTER)
.then().log().all());
}
@When("^I submit a new membership Jot Form$")
public void iSubmitANewMembershipJotForm() {
throw new PendingException();
}
@When("^I submit a renew membership Jot Form$")
public void iSubmitARenewMembershipJotForm() {
throw new PendingException();
}
@When("^I check membership information for (.*)")
public void iCheckMyMembershipInformation(final String rosterId) {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.get(ROSTER + rosterId)
.then().log().all());
}
@When("^I request an email be sent to new member (.*)$")
public void iRequestEmailToNewMember(final String rosterId) {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(ROSTER + rosterId + "/new-membership")
.then().log().all());
}
@When("^I request a message be sent to member (.*) to renew their membership$")
public void iRequestAMessageToRenewMember(final String rosterId) {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(ROSTER + rosterId + "/renew")
.then().log().all());
}
@When("^I find by name members with (.*) and (.*)$")
public void iFindByNameMembers(final String firstName, final String lastName) {
final StringBuilder sb = buildFirstAndLastNameQueryParamString(firstName, lastName);
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.get(ROSTER + "find-by-name" + sb)
.then().log().all());
}
@When("^I search for members with (.*) and (.*)$")
public void iSearchForMembers(final String firstName, final String lastName) {
final StringBuilder sb = buildFirstAndLastNameQueryParamString(firstName, lastName);
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.get("search" + sb)
.then().log().all());
}
@When("^I request membership renewal messages be sent$")
public void iRequestMembershipRenewalMessageBeSent() {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(ROSTER + "-1/renew")
.then().log().all());
}
@When("^Aerie checks for JotForm submissions$")
public void aerieChecksForJotFormSubmissions() {
testContext.setValidatableResponse(requestSpecification()
.contentType(ContentType.JSON)
.when()
.post(ROSTER + "jotform")
.then().log().all());
}
@Then("^I should have a record in the roster management system$")
public void iShouldHaveARecordInTheRosterManagementSystem() {
throw new PendingException();
}
@Then("^my membership expiration should be set to (.*) from now$")
public void myMembershipExpirationShouldBeSetToFromNow(final String duration) {
throw new PendingException();
}
@Then("^I should not receive a new member welcome email message$")
public void iShouldNotReceiveANewMemberWelcomeEmailMessage() {
throw new PendingException();
}
@Then("^I should receive a new member welcome email message$")
public void iShouldReceiveANewMemberWelcomeEmailMessage() {
throw new PendingException();
}
@Then("^my membership expiration should be set to (.*) from my previous expiration date$")
public void myMembershipExpirationShouldBeSetToFromPreviousExpiration(final String duration) {
throw new PendingException();
}
@Then("^I should receive a renew member welcome email message$")
public void iShouldReceiveARenewMemberWelcomeEmailMessage() {
throw new PendingException();
}
@Then("^I should receive my membership details$")
public void iShouldReceiveMyMembershipDetails() {
testContext.getValidatableResponse()
.assertThat()
.body("id", Matchers.notNullValue())
.body("firstName", Matchers.notNullValue())
.body("expiration", Matchers.notNullValue())
.body("rfid", Matchers.notNullValue());
}
@Then("^I should receive a list of membership details with (.*)$")
public void iShouldReceiveAListOfMembershipDetailsWith(final String name) {
if (name != null && !"null".equalsIgnoreCase(name)) {
testContext.getValidatableResponse()
.assertThat()
.body("name", Matchers.hasItem(name));
}
}
/**
* Builds a query param string with first and last name values.
*
* @param firstName First name
* @param lastName Last name
* @return query param string
*/
private StringBuilder buildFirstAndLastNameQueryParamString(String firstName, String lastName) {
final StringBuilder sb = new StringBuilder();
if (firstName != null && !firstName.equalsIgnoreCase("null")
|| lastName != null && !lastName.equalsIgnoreCase("null")) {
sb.append("?");
}
if (firstName != null && !firstName.equalsIgnoreCase("null")) {
sb.append("firstName=").append(firstName);
}
if (firstName != null && !firstName.equalsIgnoreCase("null")
&& lastName != null && !lastName.equalsIgnoreCase("null")) {
sb.append("&");
}
if (lastName != null && !lastName.equalsIgnoreCase("null")) {
sb.append("lastName=").append(lastName);
}
return sb;
}
}
| 35.335463 | 100 | 0.608951 |
2aced7fcd1671347e66fb291a5e9b8715e62b393 | 193 | package catv.product;
/**
* Created by Ray on 2016/2/14.
*/
public class CyberPctBusiness extends PctBusiness {
public CyberPctBusiness(String pcttype) {
super(pcttype);
}
}
| 17.545455 | 51 | 0.678756 |
ff4dbd788cdd51ace94c713996dbaecc7148c683 | 357 | package com.xiaoTools.util.ClassLoaderUtilTest;
import com.xiaoTools.util.classLoaderUtil.ClassLoaderUtil;
import org.junit.Test;
public class ClassLoaderUtilTest {
@Test
public void test_getClassLoader(){
// jdk.internal.loader.ClassLoaders$AppClassLoader@55054057
ClassLoader a = ClassLoaderUtil.getClassLoader();
System.out.println(a);
}
}
| 21 | 61 | 0.795518 |
256cd5401a82a3cb448189fe6183fc9368806ee3 | 589 | package org.openstreetmap.atlas.tags.filters.matcher.parsing.tree;
import java.util.List;
/**
* @author lcram
*/
public class BangOperator extends UnaryOperator
{
public BangOperator(final ASTNode child)
{
super(child);
}
@Override
public String getName()
{
return "BANG_" + getIdentifier();
}
@Override
public String getPrettyPrintText()
{
return "!";
}
@Override
public boolean match(final List<String> keys, final List<String> values)
{
return !getCenterChild().match(keys, values);
}
}
| 17.848485 | 76 | 0.628183 |
d4351b26c449f40fd8112a0b64d06803490a5b9a | 2,950 | /*
* This file was automatically generated by EvoSuite
* Fri Aug 24 09:33:05 GMT 2018
*/
package Newzgrabber;
import org.junit.Test;
import static org.junit.Assert.*;
import Newzgrabber.Base64Decoder;
import Newzgrabber.BufferedCustomInputStream;
import Newzgrabber.Newzgrabber;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.mock.java.io.MockFile;
import org.evosuite.runtime.mock.java.io.MockFileInputStream;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class Base64Decoder_ESTest extends Base64Decoder_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test0() throws Throwable {
BufferedCustomInputStream bufferedCustomInputStream0 = new BufferedCustomInputStream((InputStream) null, true);
BufferedCustomInputStream bufferedCustomInputStream1 = new BufferedCustomInputStream(bufferedCustomInputStream0);
DataOutputStream dataOutputStream0 = new DataOutputStream((OutputStream) null);
Base64Decoder base64Decoder0 = new Base64Decoder(bufferedCustomInputStream1, dataOutputStream0);
base64Decoder0.decodeStream();
base64Decoder0.decodeStream();
assertFalse(base64Decoder0.ProgressSet);
}
/**
//Test case number: 1
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test1() throws Throwable {
MockFile mockFile0 = new MockFile("aBsx]W5", "aBsx]W5");
File file0 = MockFile.createTempFile("aBsx]W5", (String) null, (File) mockFile0);
MockFileInputStream mockFileInputStream0 = new MockFileInputStream(file0);
byte[] byteArray0 = new byte[10];
byteArray0[0] = (byte)0;
byteArray0[1] = (byte)1;
mockFileInputStream0.read(byteArray0);
BufferedCustomInputStream bufferedCustomInputStream0 = new BufferedCustomInputStream(mockFileInputStream0);
ByteArrayOutputStream byteArrayOutputStream0 = new ByteArrayOutputStream();
Base64Decoder base64Decoder0 = new Base64Decoder(bufferedCustomInputStream0, byteArrayOutputStream0);
Newzgrabber.verbose = true;
String[] stringArray0 = new String[5];
stringArray0[0] = "0/*}KD*H%";
stringArray0[1] = "aBsx]W5";
FilterOutputStream filterOutputStream0 = new FilterOutputStream(byteArrayOutputStream0);
Base64Decoder base64Decoder1 = new Base64Decoder(bufferedCustomInputStream0, filterOutputStream0);
base64Decoder1.decodeStream();
base64Decoder1.decodeStream();
assertFalse(base64Decoder1.ABORT);
}
}
| 42.142857 | 176 | 0.767458 |
4da4fc1b173c87d4f2a933465c561938ff56abbe | 10,684 | /*
* Licensed to the Hipparchus project under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Hipparchus project 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.hipparchus.linear;
import org.hipparchus.complex.Complex;
import org.hipparchus.complex.ComplexField;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
public class ComplexEigenDecompositionTest {
@Test
public void testNonSquare() {
try {
new ComplexEigenDecomposition(MatrixUtils.createRealMatrix(2, 3), 1.0e-5, 1.0e-12, 1.0e-6);
Assert.fail("an axception should have been thrown");
} catch (MathIllegalArgumentException miae) {
Assert.assertEquals(LocalizedCoreFormats.NON_SQUARE_MATRIX, miae.getSpecifier());
}
}
@Test
public void testRealEigenValues() {
final RealMatrix m = MatrixUtils.createRealMatrix(new double[][] { { 2, 0 }, { 0, 3 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(m);
Assert.assertFalse(eigenDecomp.hasComplexEigenvalues());
}
@Test
public void testGetEigenValues() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
Complex ev1 = eigenDecomp.getEigenvalues()[0];
Complex ev2 = eigenDecomp.getEigenvalues()[1];
Assert.assertEquals(new Complex(1, +2), ev1);
Assert.assertEquals(new Complex(1, -2), ev2);
}
@Test
public void testHasComplexEigenValues() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
Assert.assertTrue(eigenDecomp.hasComplexEigenvalues());
}
@Test
public void testGetDeterminant() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
Assert.assertEquals(5, eigenDecomp.getDeterminant(), 1.0e-12);
}
@Test
public void testGetEigenVectors() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
checkScaledVector(eigenDecomp.getEigenvector(0), buildVector(new Complex(1), new Complex(1, -1)), 1.0e-15);
checkScaledVector(eigenDecomp.getEigenvector(1), buildVector(new Complex(1), new Complex(1, +1)), 1.0e-15);
}
@Test
public void testEigenValuesAndVectors() {
final RealMatrix aR = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
final ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(aR);
final FieldMatrix<Complex> aC = toComplex(aR);
for (int i = 0; i < aR.getRowDimension(); ++i) {
final Complex lambda = eigenDecomp.getEigenvalues()[i];
final FieldVector<Complex> u = eigenDecomp.getEigenvector(i);
final FieldVector<Complex> v = aC.operate(u);
checkScaledVector(v, u.mapMultiplyToSelf(lambda), 1.0e-12);
}
}
@Test
public void testGetV() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
FieldMatrix<Complex> V = eigenDecomp.getV();
Assert.assertEquals(0.0, new Complex(.5, .5).subtract(V.getEntry(0, 0)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(.5, -.5).subtract(V.getEntry(0, 1)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(1).subtract(V.getEntry(1, 0)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(1).subtract(V.getEntry(1, 1)).abs(), 1.0e-15);
}
@Test
public void testGetVT() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
FieldMatrix<Complex> V = eigenDecomp.getVT();
Assert.assertEquals(0.0, new Complex(.5, .5).subtract(V.getEntry(0, 0)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(.5, -.5).subtract(V.getEntry(1, 0)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(1).subtract(V.getEntry(0, 1)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(1).subtract(V.getEntry(1, 1)).abs(), 1.0e-15);
}
@Test
public void testGetD() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
FieldMatrix<Complex> D = eigenDecomp.getD();
Assert.assertEquals(0.0, new Complex(1, +2).subtract(D.getEntry(0, 0)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(0).subtract(D.getEntry(0, 1)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(0).subtract(D.getEntry(0, 1)).abs(), 1.0e-15);
Assert.assertEquals(0.0, new Complex(1, -2).subtract(D.getEntry(1, 1)).abs(), 1.0e-15);
}
@Test
public void testEqualEigenvalues() {
final RealMatrix A = MatrixUtils.createRealMatrix(new double[][] {
{ 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 }
});
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(A);
Assert.assertEquals(3, eigenDecomp.getEigenvalues().length);
for (Complex z : eigenDecomp.getEigenvalues()) {
Assert.assertEquals(Complex.ONE, z);
}
checkScaledVector(buildVector(Complex.ONE, Complex.ZERO, Complex.ZERO), eigenDecomp.getEigenvector(0), 1.0e-12);
checkScaledVector(buildVector(Complex.ZERO, Complex.ONE, Complex.ZERO), eigenDecomp.getEigenvector(1), 1.0e-12);
checkScaledVector(buildVector(Complex.ZERO, Complex.ZERO, Complex.ONE), eigenDecomp.getEigenvector(2), 1.0e-12);
}
@Test
public void testDefinition() {
final RealMatrix aR = MatrixUtils.createRealMatrix(new double[][] { { 3, -2 }, { 4, -1 } });
ComplexEigenDecomposition eigenDecomp = new ComplexEigenDecomposition(aR);
FieldMatrix<Complex> aC = toComplex(aR);
// testing AV = lamba V - [0]
checkScaledVector(aC.operate(eigenDecomp.getEigenvector(0)),
eigenDecomp.getEigenvector(0).mapMultiply(eigenDecomp.getEigenvalues()[0]),
1.0e-12);
// testing AV = lamba V - [1]
checkScaledVector(aC.operate(eigenDecomp.getEigenvector(1)),
eigenDecomp.getEigenvector(1).mapMultiply(eigenDecomp.getEigenvalues()[1]),
1.0e-12);
// checking definition of the decomposition A*V = V*D
checkMatrix(aC.multiply(eigenDecomp.getV()),
eigenDecomp.getV().multiply(eigenDecomp.getD()),
1.0e-12);
}
private FieldMatrix<Complex> toComplex(final RealMatrix m) {
FieldMatrix<Complex> c = MatrixUtils.createFieldMatrix(ComplexField.getInstance(),
m.getRowDimension(),
m.getColumnDimension());
for (int i = 0; i < m.getRowDimension(); ++i) {
for (int j = 0; j < m.getColumnDimension(); ++j) {
c.setEntry(i, j, new Complex(m.getEntry(i, j)));
}
}
return c;
}
private FieldVector<Complex> buildVector(final Complex... vi) {
return new ArrayFieldVector<>(vi);
}
private void checkScaledVector(final FieldVector<Complex> v, final FieldVector<Complex> reference, final double tol) {
Assert.assertEquals(reference.getDimension(), v.getDimension());
// find the global scaling factor, using the maximum reference component
Complex scale = Complex.NaN;
double norm = Double.NEGATIVE_INFINITY;
for (int i = 0; i < reference.getDimension(); i++) {
final Complex ri = reference.getEntry(i);
final double ni = FastMath.hypot(ri.getReal(), ri.getImaginary());
if (ni > norm) {
scale = ri.divide(v.getEntry(i));
norm = ni;
}
}
// check vector, applying the scaling factor
for (int i = 0; i < reference.getDimension(); ++i) {
final Complex ri = reference.getEntry(i);
final Complex vi = v.getEntry(i);
final Complex si = vi.multiply(scale);
Assert.assertEquals("" + (ri.getReal() - si.getReal()), ri.getReal(), si.getReal(), tol);
Assert.assertEquals("" + (ri.getImaginary() - si.getImaginary()), ri.getImaginary(), si.getImaginary(), tol);
}
}
private void checkMatrix(final FieldMatrix<Complex> m, final FieldMatrix<Complex> reference, final double tol) {
Assert.assertEquals(reference.getRowDimension(), m.getRowDimension());
Assert.assertEquals(reference.getColumnDimension(), m.getColumnDimension());
for (int i = 0; i < reference.getRowDimension(); ++i) {
for (int j = 0; j < reference.getColumnDimension(); ++j) {
Assert.assertEquals("" + (reference.getEntry(i, j).getReal() - m.getEntry(i, j).getReal()),
reference.getEntry(i, j).getReal(), m.getEntry(i, j).getReal(), tol);
Assert.assertEquals("" + (reference.getEntry(i, j).getImaginary() - m.getEntry(i, j).getImaginary()),
reference.getEntry(i, j).getImaginary(), m.getEntry(i, j).getImaginary(), tol);
}
}
}
}
| 47.066079 | 122 | 0.627948 |
75f39a2ea59d4dc759c16059d1810b383e396b3c | 565 | package commonadapter.adapters.nds.lane.attrMaps;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"isExternalLinkReference",
"linkReferenceChoice"
})
public class BaseLinkReference {
@JsonProperty("isExternalLinkReference")
public String isExternalLinkReference;
@JsonProperty("linkReferenceChoice")
public LinkReferenceChoice linkReferenceChoice;
} | 33.235294 | 58 | 0.80885 |
f4a077a4ba21c26497993a98f60831d160803cf1 | 7,083 | /*******************************************************************************
* Copyright (c) 2014-2016 European Molecular Biology Laboratory,
* Heidelberg, Germany.
*
* 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.
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.24 at 03:18:36 PM GMT
//
package eu.ddmore.libpharmml.dom.commontypes;
import java.util.ArrayList;
import java.util.List;
import javax.swing.tree.TreeNode;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlType;
import eu.ddmore.libpharmml.util.ChainedList;
import eu.ddmore.libpharmml.visitor.Visitor;
/**
* This type specifies a row of values in a matrix. The row can contain indexed cells or
* scalars/symbols filling the whole row. Index of the matrix row is optoinal. If cells are defined inside rows,
* the cells will be indexed relative to the row.
*
* <p>Java class for MatrixRowType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="MatrixRowType">
* <complexContent>
* <extension base="{http://www.pharmml.org/2013/03/CommonTypes}PharmMLRootType">
* <sequence>
* <element name="RowIndex" type="{http://www.pharmml.org/2013/03/CommonTypes}MatrixVectorIndexType" minOccurs="0"/>
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{http://www.pharmml.org/2013/03/CommonTypes}Scalar"/>
* <element ref="{http://www.pharmml.org/2013/03/CommonTypes}Sequence"/>
* <element ref="{http://www.pharmml.org/2013/03/CommonTypes}SymbRef"/>
* </choice>
* </sequence>
* <attribute name="default" type="{http://www.w3.org/2001/XMLSchema}double" default="0" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MatrixRowType", propOrder = {
"rowIndex",
"listOfValues"
})
public class MatrixRow
extends PharmMLRootType
{
@XmlElement(name = "RowIndex")
protected MatrixVectorIndex rowIndex;
@XmlElementRefs({
@XmlElementRef(name = "Scalar", namespace = NS_DEFAULT_CT, type = JAXBElement.class, required = false),
@XmlElementRef(name = "Sequence", namespace = NS_DEFAULT_CT, type = JAXBElement.class, required = false),
@XmlElementRef(name = "SymbRef", namespace = NS_DEFAULT_CT, type = JAXBElement.class, required = false),
@XmlElementRef(name = "Assign", namespace = NS_DEFAULT_CT, type = JAXBElement.class, required = false),
@XmlElementRef(name = "Equation", namespace = NS_DEFAULT_MATH, type = JAXBElement.class, required = false)
})
protected List<MatrixRowValue> listOfValues;
@XmlAttribute(name = "default")
protected Double _default;
/**
* Gets the value of the rowIndex property.
*
* @return
* possible object is
* {@link MatrixVectorIndex }
*
*/
public MatrixVectorIndex getRowIndex() {
return rowIndex;
}
/**
* Sets the value of the rowIndex property.
*
* @param value
* allowed object is
* {@link MatrixVectorIndex }
*
*/
public void setRowIndex(MatrixVectorIndex value) {
this.rowIndex = value;
}
/**
* Gets the value of the scalarOrSequenceOrSymbRef property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the scalarOrSequenceOrSymbRef property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getScalarOrSequenceOrSymbRef().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link Object }{@code >}
* {@link JAXBElement }{@code <}{@link IntValue }{@code >}
* {@link JAXBElement }{@code <}{@link Sequence }{@code >}
* {@link JAXBElement }{@code <}{@link StringValue }{@code >}
* {@link JAXBElement }{@code <}{@link RealValue }{@code >}
* {@link JAXBElement }{@code <}{@link TrueBoolean }{@code >}
* {@link JAXBElement }{@code <}{@link SymbolRef }{@code >}
* {@link JAXBElement }{@code <}{@link BooleanValue }{@code >}
* {@link JAXBElement }{@code <}{@link IdValue }{@code >}
* {@link JAXBElement }{@code <}{@link FalseBoolean }{@code >}
*
*
*/
public List<MatrixRowValue> getListOfValues() {
if (listOfValues == null) {
listOfValues = new ArrayList<MatrixRowValue>();
}
return this.listOfValues;
}
/**
* @deprecated The list of row values is now accessed through {@link #getListOfValues()}
*/
@SuppressWarnings("unchecked")
@Deprecated
public List<Object> getRealOrSymbRef() {
return (List<Object>) (List<?>) getListOfValues();
}
/**
* Gets the value of the default property.
*
* @return
* possible object is
* {@link Double }
*
*/
public double getDefault() {
if (_default == null) {
return 0.0D;
} else {
return _default;
}
}
/**
* Sets the value of the default property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setDefault(Double value) {
this._default = value;
}
@Override
protected List<TreeNode> listChildren() {
return new ChainedList<TreeNode>()
.addIfNotNull(rowIndex)
.addIfNotNull(listOfValues);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
| 33.728571 | 129 | 0.62883 |
8225a17df2b638c1f3ecf4486c9c42013d32a28e | 23,672 | package io.choerodon.iam.app.service.impl;
import io.choerodon.asgard.saga.annotation.Saga;
import io.choerodon.asgard.saga.producer.StartSagaBuilder;
import io.choerodon.asgard.saga.producer.TransactionalProducer;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.iam.ResourceLevel;
import io.choerodon.iam.api.dto.ProjectCategoryDTO;
import io.choerodon.iam.api.dto.RelationshipCheckDTO;
import io.choerodon.iam.api.dto.payload.ProjectRelationshipInsertPayload;
import io.choerodon.iam.app.service.OrganizationProjectService;
import io.choerodon.iam.app.service.ProjectRelationshipService;
import io.choerodon.iam.infra.asserts.ProjectAssertHelper;
import io.choerodon.iam.infra.dto.ProjectDTO;
import io.choerodon.iam.infra.dto.ProjectMapCategoryDTO;
import io.choerodon.iam.infra.dto.ProjectRelationshipDTO;
import io.choerodon.iam.infra.enums.ProjectCategory;
import io.choerodon.iam.infra.mapper.ProjectCategoryMapper;
import io.choerodon.iam.infra.mapper.ProjectMapCategoryMapper;
import io.choerodon.iam.infra.mapper.ProjectMapper;
import io.choerodon.iam.infra.mapper.ProjectRelationshipMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static io.choerodon.iam.infra.common.utils.SagaTopic.ProjectRelationship.PROJECT_RELATIONSHIP_ADD;
import static io.choerodon.iam.infra.common.utils.SagaTopic.ProjectRelationship.PROJECT_RELATIONSHIP_DELETE;
/**
* @author Eugen
*/
@Service
public class ProjectRelationshipServiceImpl implements ProjectRelationshipService {
private static final Logger logger = LoggerFactory.getLogger(ProjectRelationshipServiceImpl.class);
private static final String PROGRAM_CANNOT_BE_CONFIGURA_SUBPROJECTS = "error.program.cannot.be.configured.subprojects";
private static final String AGILE_CANNOT_CONFIGURA_SUBPROJECTS = "error.agile.projects.cannot.configure.subprojects";
private static final String RELATIONSHIP_NOT_EXIST_EXCEPTION = "error.project.relationship.not.exist";
public static final String STATUS_ADD = "add";
public static final String STATUS_UPDATE = "update";
public static final String STATUS_DELETE = "delete";
private TransactionalProducer producer;
private ProjectRelationshipMapper relationshipMapper;
private ProjectCategoryMapper projectCategoryMapper;
private ProjectMapCategoryMapper projectMapCategoryMapper;
private OrganizationProjectService organizationProjectService;
@Value("${choerodon.category.enabled:false}")
private Boolean categoryEnable;
private ProjectRelationshipMapper projectRelationshipMapper;
private ProjectAssertHelper projectAssertHelper;
private ProjectMapper projectMapper;
public ProjectRelationshipServiceImpl(TransactionalProducer producer, ProjectRelationshipMapper relationshipMapper,
ProjectCategoryMapper projectCategoryMapper, ProjectMapCategoryMapper projectMapCategoryMapper,
OrganizationProjectService organizationProjectService,
ProjectRelationshipMapper projectRelationshipMapper,
ProjectAssertHelper projectAssertHelper,
ProjectMapper projectMapper) {
this.producer = producer;
this.relationshipMapper = relationshipMapper;
this.projectCategoryMapper = projectCategoryMapper;
this.projectMapCategoryMapper = projectMapCategoryMapper;
this.organizationProjectService = organizationProjectService;
this.projectRelationshipMapper = projectRelationshipMapper;
this.projectAssertHelper = projectAssertHelper;
this.projectMapper = projectMapper;
}
@Override
public List<ProjectRelationshipDTO> getProjUnderGroup(Long projectId, Boolean onlySelectEnable) {
ProjectDTO projectDTO;
if (categoryEnable) {
projectDTO = organizationProjectService.selectCategoryByPrimaryKey(projectId);
} else {
projectDTO = projectAssertHelper.projectNotExisted(projectId);
}
if (!projectDTO.getCategory().equalsIgnoreCase(ProjectCategory.PROGRAM.value()) &&
!projectDTO.getCategory().equalsIgnoreCase(ProjectCategory.ANALYTICAL.value())) {
throw new CommonException(AGILE_CANNOT_CONFIGURA_SUBPROJECTS);
}
return projectRelationshipMapper.selectProjectsByParentId(projectId, onlySelectEnable);
}
@Override
@Saga(code = PROJECT_RELATIONSHIP_DELETE, description = "项目群下移除项目", inputSchemaClass = ProjectRelationshipInsertPayload.class)
public void removesAProjUnderGroup(Long orgId, Long groupId) {
ProjectRelationshipDTO projectRelationshipDTO = projectRelationshipMapper.selectByPrimaryKey(groupId);
if (projectRelationshipDTO == null) {
throw new CommonException(RELATIONSHIP_NOT_EXIST_EXCEPTION);
}
if (categoryEnable && projectRelationshipDTO.getEnabled()) {
removeProgramProject(projectRelationshipDTO.getProjectId());
}
ProjectRelationshipInsertPayload sagaPayload = new ProjectRelationshipInsertPayload();
ProjectDTO parent = projectAssertHelper.projectNotExisted(projectRelationshipDTO.getParentId());
sagaPayload.setCategory(parent.getCategory());
sagaPayload.setParentCode(parent.getCode());
sagaPayload.setParentId(parent.getId());
ProjectDTO project = projectAssertHelper.projectNotExisted(projectRelationshipDTO.getProjectId());
ProjectRelationshipInsertPayload.ProjectRelationship relationship
= new ProjectRelationshipInsertPayload.ProjectRelationship(project.getId(), project.getCode(),
projectRelationshipDTO.getStartDate(), projectRelationshipDTO.getEndDate(), projectRelationshipDTO.getEnabled(), STATUS_DELETE);
sagaPayload.setRelationships(Collections.singletonList(relationship));
producer.applyAndReturn(
StartSagaBuilder
.newBuilder()
.withLevel(ResourceLevel.ORGANIZATION)
.withRefType("organization")
.withSagaCode(PROJECT_RELATIONSHIP_DELETE),
builder -> {
if (projectRelationshipMapper.selectByPrimaryKey(groupId) == null) {
throw new CommonException("error.delete.project.group.not.exist");
}
if (projectRelationshipMapper.deleteByPrimaryKey(groupId) != 1) {
throw new CommonException("error.delete.project.group");
}
builder
.withPayloadAndSerialize(sagaPayload)
.withRefId(String.valueOf(orgId))
.withSourceId(orgId);
return sagaPayload;
});
}
@Override
public RelationshipCheckDTO checkRelationshipCanBeEnabled(Long id) {
ProjectRelationshipDTO projectRelationshipDTO = projectRelationshipMapper.selectByPrimaryKey(id);
if (projectRelationshipDTO == null) {
throw new CommonException(RELATIONSHIP_NOT_EXIST_EXCEPTION);
} else if (projectRelationshipDTO.getEnabled()) {
throw new CommonException("error.check.relationship.is.already.enabled");
}
return checkDate(projectRelationshipDTO);
}
@Override
public List<Map<String, Date>> getUnavailableTime(Long projectId, Long parentId) {
ProjectDTO project = projectAssertHelper.projectNotExisted(projectId);
if (!project.getCategory().equalsIgnoreCase(ProjectCategory.AGILE.value())) {
throw new CommonException(PROGRAM_CANNOT_BE_CONFIGURA_SUBPROJECTS);
}
ProjectDTO parent = projectAssertHelper.projectNotExisted(parentId);
if (parent.getCategory().equalsIgnoreCase(ProjectCategory.AGILE.value())) {
throw new CommonException(AGILE_CANNOT_CONFIGURA_SUBPROJECTS);
}
//查询projectId所有被建立的关系
ProjectRelationshipDTO selectTmpDTO = new ProjectRelationshipDTO();
selectTmpDTO.setProjectId(projectId);
List<ProjectRelationshipDTO> relationshipDOS = projectRelationshipMapper.select(selectTmpDTO);
List<Map<String, Date>> list = new ArrayList<>();
//去除已与当前项目群建立的关系
relationshipDOS = relationshipDOS.stream().filter(r -> !r.getParentId().equals(parentId)).collect(Collectors.toList());
relationshipDOS.forEach(r -> {
ProjectDTO projectDTO = projectMapper.selectByPrimaryKey(r.getParentId());
if (projectDTO != null &&
projectDTO.getCategory().equalsIgnoreCase(ProjectCategory.PROGRAM.value()) &&
r.getEnabled()) {
Map<String, Date> map = new HashMap<>();
map.put("start", r.getStartDate());
map.put("end", r.getEndDate());
list.add(map);
}
});
return list;
}
@Saga(code = PROJECT_RELATIONSHIP_ADD, description = "iam组合项目中新增子项目", inputSchemaClass = ProjectRelationshipInsertPayload.class)
@Override
@Transactional
public List<ProjectRelationshipDTO> batchUpdateRelationShipUnderProgram(Long orgId, List<ProjectRelationshipDTO> list) {
//check list
if (CollectionUtils.isEmpty(list)) {
logger.info("The array for batch update relationships cannot be empty");
return Collections.emptyList();
}
checkUpdateList(list);
//update与create分区
List<ProjectRelationshipDTO> updateNewList = new ArrayList<>();
List<ProjectRelationshipDTO> insertNewList = new ArrayList<>();
list.forEach(g -> {
if (g.getId() == null) {
insertNewList.add(g);
} else {
updateNewList.add(g);
}
});
List<ProjectRelationshipDTO> returnList = new ArrayList<>();
// build project relationship saga payload
ProjectRelationshipInsertPayload sagaPayload = new ProjectRelationshipInsertPayload();
ProjectDTO parent = projectAssertHelper.projectNotExisted(list.get(0).getParentId());
sagaPayload.setCategory(parent.getCategory());
sagaPayload.setParentCode(parent.getCode());
sagaPayload.setParentId(parent.getId());
List<ProjectRelationshipInsertPayload.ProjectRelationship> relationships = new ArrayList<>();
//批量插入
insertNewList.forEach(relationshipDTO -> {
checkGroupIsLegal(relationshipDTO);
checkCategoryEnable(relationshipDTO);
// insert
if (projectRelationshipMapper.insertSelective(relationshipDTO) != 1) {
throw new CommonException("error.create.project.group");
}
BeanUtils.copyProperties(projectRelationshipMapper.selectByPrimaryKey(relationshipDTO.getId()), relationshipDTO);
returnList.add(relationshipDTO);
if (categoryEnable && relationshipDTO.getEnabled()) {
addProgramProject(relationshipDTO.getProjectId());
}
// fill the saga payload
ProjectDTO project = projectAssertHelper.projectNotExisted(relationshipDTO.getProjectId());
ProjectRelationshipInsertPayload.ProjectRelationship relationship
= new ProjectRelationshipInsertPayload.ProjectRelationship(project.getId(), project.getCode(),
relationshipDTO.getStartDate(), relationshipDTO.getEndDate(), relationshipDTO.getEnabled(), STATUS_ADD);
relationships.add(relationship);
});
//批量更新
updateNewList.forEach(relationshipDTO -> {
checkGroupIsLegal(relationshipDTO);
// 更新项目群关系的有效结束时间
updateProjectRelationshipEndDate(relationshipDTO);
if (projectRelationshipMapper.selectByPrimaryKey(relationshipDTO.getId()) == null) {
logger.warn("Batch update project relationship exists Nonexistent relationship,id is{}:{}", relationshipDTO.getId(), relationshipDTO);
} else {
checkCategoryEnable(relationshipDTO);
ProjectRelationshipDTO projectRelationship = new ProjectRelationshipDTO();
BeanUtils.copyProperties(relationshipDTO, projectRelationship);
// update
if (projectRelationshipMapper.updateByPrimaryKey(projectRelationship) != 1) {
throw new CommonException("error.project.group.update");
}
projectRelationship = projectRelationshipMapper.selectByPrimaryKey(projectRelationship.getId());
BeanUtils.copyProperties(projectRelationship, relationshipDTO);
returnList.add(relationshipDTO);
if (categoryEnable) {
if (relationshipDTO.getEnabled()) {
addProgramProject(relationshipDTO.getProjectId());
} else {
removeProgramProject(relationshipDTO.getProjectId());
}
}
// fill the saga payload
ProjectDTO project =
projectAssertHelper.projectNotExisted(relationshipDTO.getProjectId());
ProjectRelationshipInsertPayload.ProjectRelationship relationship
= new ProjectRelationshipInsertPayload.ProjectRelationship(project.getId(), project.getCode(),
relationshipDTO.getStartDate(), relationshipDTO.getEndDate(), relationshipDTO.getEnabled(), STATUS_UPDATE);
relationships.add(relationship);
}
});
sagaPayload.setRelationships(relationships);
producer.applyAndReturn(
StartSagaBuilder
.newBuilder()
.withLevel(ResourceLevel.ORGANIZATION)
.withRefType("organization")
.withSagaCode(PROJECT_RELATIONSHIP_ADD),
builder -> {
builder
.withPayloadAndSerialize(sagaPayload)
.withRefId(String.valueOf(orgId))
.withSourceId(orgId);
return sagaPayload;
});
return returnList;
}
private void addProgramProject(Long projectId) {
ProjectCategoryDTO projectCategoryDTO = new ProjectCategoryDTO();
projectCategoryDTO.setCode("PROGRAM_PROJECT");
projectCategoryDTO = projectCategoryMapper.selectOne(projectCategoryDTO);
ProjectMapCategoryDTO projectMapCategoryDTO = new ProjectMapCategoryDTO();
projectMapCategoryDTO.setProjectId(projectId);
projectMapCategoryDTO.setCategoryId(projectCategoryDTO.getId());
if (projectMapCategoryMapper.insert(projectMapCategoryDTO) != 1) {
throw new CommonException("error.project.map.category.insert");
}
}
private void removeProgramProject(Long projectId) {
ProjectCategoryDTO projectCategoryDTO = new ProjectCategoryDTO();
projectCategoryDTO.setCode("PROGRAM_PROJECT");
projectCategoryDTO = projectCategoryMapper.selectOne(projectCategoryDTO);
ProjectMapCategoryDTO projectMapCategoryDTO = new ProjectMapCategoryDTO();
projectMapCategoryDTO.setProjectId(projectId);
projectMapCategoryDTO.setCategoryId(projectCategoryDTO.getId());
if (projectMapCategoryMapper.delete(projectMapCategoryDTO) != 1) {
throw new CommonException("error.project.map.category.delete");
}
}
/**
* 更新项目群关系的有效结束时间.
*
* @param projectRelationshipDTO 项目群关系
*/
private void updateProjectRelationshipEndDate(ProjectRelationshipDTO projectRelationshipDTO) {
// 启用操作 结束时间置为空
if (projectRelationshipDTO.getEnabled()) {
projectRelationshipDTO.setEndDate(null);
} else {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
// 禁用操作 结束时间为禁用操作的时间
projectRelationshipDTO.setEndDate(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
} catch (ParseException e) {
logger.info("Relationship end time format failed");
}
}
}
private void checkCategoryEnable(ProjectRelationshipDTO relationshipDTO) {
if (categoryEnable) {
if (organizationProjectService.selectCategoryByPrimaryKey(relationshipDTO.getParentId()).getCategory()
.equalsIgnoreCase(ProjectCategory.PROGRAM.value())) {
relationshipDTO.setProgramId(relationshipDTO.getParentId());
}
} else if (projectAssertHelper.projectNotExisted(relationshipDTO.getParentId()).getCategory()
.equalsIgnoreCase(ProjectCategory.PROGRAM.value())) {
relationshipDTO.setProgramId(relationshipDTO.getParentId());
}
}
/**
* 校验批量更新DTO
* 检验不能为空
* 校验不能批量更新不同项目群下的项目关系
* 校验项目本身已停用 则无法被项目群添加或更新
* 校验一个项目只能被一个普通项目群添加
* 校验一个项目只能被一个普通项目群更新
*
* @param list 项目群关系列表
*/
private void checkUpdateList(List<ProjectRelationshipDTO> list) {
// list不能为空
if (list == null || list.isEmpty()) {
logger.info("The array for batch update relationships cannot be empty");
return;
}
list.forEach(r -> {
// 开始时间为空则填充为当前时间
if (r.getStartDate() == null) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
r.setStartDate(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
} catch (ParseException e) {
logger.info("Relationship start time format failed");
}
}
// 项目已停用 无法被项目群添加或更新
ProjectDTO project = projectAssertHelper.projectNotExisted(r.getProjectId());
if (!project.getEnabled()) {
throw new CommonException("error.insertOrUpdate.project.relationships.when.project.disabled", project.getName());
}
if (r.getId() == null) {
// 一个项目只能被一个普通项目群添加
List<ProjectDTO> projectDTOS = relationshipMapper.selectProgramsByProjectId(r.getProjectId(), true);
if (projectDTOS != null && projectDTOS.size() > 0) {
throw new CommonException("error.insert.project.relationships.exists.one.program", projectDTOS.get(0).getName());
}
} else if (r.getEnabled()) {
// 一个项目只能被一个普通项目群更新
List<ProjectDTO> projectDTOS = relationshipMapper.selectProgramsByProjectId(r.getProjectId(), true);
if (projectDTOS != null && projectDTOS.size() > 0) {
List<String> programs = new ArrayList<>();
for (ProjectDTO projectDTO : projectDTOS) {
programs.add(projectDTO.getName());
}
throw new CommonException("error.update.project.relationships.exists.multiple.program", StringUtils.join(programs, ","));
}
}
});
Set<Long> collect = list.stream().map(ProjectRelationshipDTO::getParentId).collect(Collectors.toSet());
if (collect.size() != 1) {
throw new CommonException("error.update.project.relationships.must.be.under.the.same.program");
}
}
/**
* 校验
* 校验parent是否为空,是否非敏捷项目
* 校验project是否为空,是否为敏捷项目
*
* @param projectRelationshipDTO
*/
private void checkGroupIsLegal(ProjectRelationshipDTO projectRelationshipDTO) {
ProjectDTO parent;
if (categoryEnable) {
parent = organizationProjectService.selectCategoryByPrimaryKey(projectRelationshipDTO.getParentId());
} else {
parent = projectAssertHelper.projectNotExisted(projectRelationshipDTO.getParentId());
}
if (!parent.getCategory().equalsIgnoreCase(ProjectCategory.PROGRAM.value()) &&
!parent.getCategory().equalsIgnoreCase(ProjectCategory.ANALYTICAL.value())) {
throw new CommonException(AGILE_CANNOT_CONFIGURA_SUBPROJECTS);
}
ProjectDTO son;
if (categoryEnable) {
son = organizationProjectService.selectCategoryByPrimaryKey(projectRelationshipDTO.getProjectId());
} else {
son = projectAssertHelper.projectNotExisted(projectRelationshipDTO.getProjectId());
}
if (!son.getCategory().equalsIgnoreCase(ProjectCategory.AGILE.value())) {
throw new CommonException(PROGRAM_CANNOT_BE_CONFIGURA_SUBPROJECTS);
}
}
private RelationshipCheckDTO checkDate(ProjectRelationshipDTO needCheckDTO) {
// db list
ProjectRelationshipDTO checkDTO = new ProjectRelationshipDTO();
checkDTO.setProjectId(needCheckDTO.getProjectId());
List<ProjectRelationshipDTO> dbList = projectRelationshipMapper.select(checkDTO);
long start = needCheckDTO.getStartDate().getTime();
// build result
RelationshipCheckDTO result = new RelationshipCheckDTO();
result.setResult(true);
// check
dbList.forEach(r -> {
ProjectDTO parent = projectAssertHelper.projectNotExisted(r.getParentId());
if (!r.getId().equals(needCheckDTO.getId()) && r.getEnabled()
&& parent.getCategory().equalsIgnoreCase(ProjectCategory.PROGRAM.value())) {
long min = r.getStartDate().getTime();
Boolean flag = true;
if (needCheckDTO.getEndDate() != null) {
long end = needCheckDTO.getEndDate().getTime();
if (r.getEndDate() != null) {
long max = r.getEndDate().getTime();
if (!(start >= max || end <= min)) {
flag = false;
}
} else {
if (end > min) {
flag = false;
}
}
} else {
if (r.getEndDate() != null) {
long max = r.getEndDate().getTime();
if (start < max) {
flag = false;
}
} else {
flag = false;
}
}
if (!flag) {
result.setResult(false);
result.setProjectCode(parent.getCode());
result.setProjectName(parent.getName());
logger.warn("Project associated time is not legal,relationship:{},conflict project name:{},code:{}",
needCheckDTO, result.getProjectName(), result.getProjectCode());
return;
}
}
});
// return
return result;
}
}
| 49.010352 | 150 | 0.648868 |
a2c974f7e64a41060bc05184df1865157afba7d9 | 3,959 | package com.webstarters.lazycomponents.controller;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.webstarters.lazycomponents.services.impl.LazyComponentHelperService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* @author Aman Prasad
*
*/
@RestController
@RequestMapping(value = "/lzc")
@CrossOrigin(origins = "*")
public class LazyComponentHelperController {
@Autowired
private LazyComponentHelperService lzcService = null;
@Autowired
private Configuration templateConfiguration = null;
@GetMapping(value = "/sp-template", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getStoredProcedureTemplate(@RequestParam(name = "name", required = true) String storedProcedureName,
@RequestParam(name = "columns", required = false) String columns,
@RequestParam(name = "tableName", required = false) String tableName) throws TemplateException {
try {
Template template = getFreeMakerTemplate("storedProdTemplate");
Map<String, Object> templateParams = lzcService.getQueryTemplateForStoredProd(tableName, Arrays.asList(columns.split(",")));
templateParams.put("storedProdName", storedProcedureName);
Writer writer = new StringWriter();
template.process(templateParams, writer);
return ResponseEntity.ok(writer.toString());
} catch (IOException exception) {
exception.printStackTrace();
}
return ResponseEntity.ok(storedProcedureName);
}
@GetMapping(value = "/table-query-template", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getTableTemplate(@RequestParam(name = "tableName", required = true) String tableName) {
return ResponseEntity.ok(lzcService.getQueryTemplateForTable(tableName));
}
@GetMapping(value = "/manage-component-details", produces = MediaType.TEXT_HTML_VALUE)
public String getManageComponentDetailsPage(@RequestParam(required = false, name = "id") String componentId) throws IOException, TemplateException {
Template template = getFreeMakerTemplate("manageComponentDetails");
Map<String, Object> templateParams = new HashMap<>();
Writer writer = new StringWriter();
template.process(templateParams, writer);
return writer.toString();
}
@GetMapping(value = "/tables", produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> getTableDetails() {
return lzcService.getTablesInformation();
}
@GetMapping(value = "/columns", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Map<String, Object>> getTableColumnDetails(@RequestParam(required = true, name="table") String tableName) {
return lzcService.getTableColumnDetails(tableName);
}
private Template getFreeMakerTemplate(String templateName) throws IOException {
templateConfiguration.setAPIBuiltinEnabled(Boolean.TRUE);
String templateContent = Resources.toString(Resources.getResource("/templates/"+templateName+".ftl"), Charsets.UTF_8);
Template template = new Template(templateName, templateContent, templateConfiguration);
return template;
}
}
| 41.239583 | 150 | 0.777974 |
617bcb9f694080a7e1f085d01350945549ada1d6 | 2,183 | package com.rts.services.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
public class UserType {
private boolean selected = false;
private boolean operator = false;
private boolean poc = false;
private boolean volunteer = false;
private boolean administrator = false;
private String name = null;
public UserType() {
String usercred[] = getRoleAndName();
if (usercred[0].equals("ROLE_OPERATOR")) {
operator = true;
}
else if(usercred[0].equals("ROLE_POC"))
{
poc = true;
}
else if(usercred[0].equals("ROLE_VOLUNTEER"))
{
volunteer = true;
}
else if(usercred[0].equals("ROLE_ADMINISTRATOR"))
{
administrator = true;
}
this.name = usercred[1];
}
public void init() {
if (!selected) {
}
}
public void setPOC(String name)
{
poc = true;
this.name = name;
}
public String getPOC() {
if(isPoc())
{
return name;
}
return null;
}
public String getVolunteer() {
if(isVolunteer())
{
return name;
}
return null;
}
public String getOperator() {
if(isOperator())
{
return name;
}
return null;
}
public boolean isPoc() {
return poc;
}
public boolean isAdministrator() {
return administrator;
}
public String getName() {
return name;
}
public boolean isOperator() {
return operator;
}
public boolean isVolunteer() {
return volunteer;
}
public void setPoc(boolean poc) {
this.poc = poc;
}
public void setOperator(boolean operator) {
this.operator = operator;
}
public void setVolunteer(boolean volunteer) {
this.volunteer = volunteer;
}
public static String[] getRoleAndName() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
GrantedAuthority role = authentication.getAuthorities().iterator().next();
String values = role.getAuthority() + "," + authentication.getName();
return values.split(",");
}
}
| 18.5 | 90 | 0.642694 |
c49e0b51034c07ba2fe50cb7317183ba33a32f1c | 198 | /**
*
*/
package grapheus.persistence.exception;
/**
* @author black
*
*/
public class DbNotReadyException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| 13.2 | 59 | 0.70202 |
a00d86b15c3fd77208167c4a39941deb4cb10e16 | 4,868 | package edu.cmu.sv.ws.ssnoc.common.utils;
import edu.cmu.sv.ws.ssnoc.data.po.MemoryPO;
import edu.cmu.sv.ws.ssnoc.data.po.UserPO;
import edu.cmu.sv.ws.ssnoc.dto.Memory;
import edu.cmu.sv.ws.ssnoc.dto.User;
import edu.cmu.sv.ws.ssnoc.data.po.StatusPO;
import edu.cmu.sv.ws.ssnoc.dto.Status;
import edu.cmu.sv.ws.ssnoc.data.po.MessagePO;
import edu.cmu.sv.ws.ssnoc.dto.Message;
/**
* This is a utility class used to convert PO (Persistent Objects) and View
* Objects into DTO (Data Transfer Objects) objects, and vice versa. <br/>
* Rather than having the conversion code in all classes in the rest package,
* they are maintained here for code re-usability and modularity.
*
*/
public class ConverterUtils {
/**
* Convert UserPO to User DTO object.
*
* @param po
* - User PO object
*
* @return - User DTO Object
*/
public static final User convert(UserPO po) {
if (po == null) {
return null;
}
User dto = new User();
dto.setUserName(po.getUserName());
dto.setPassword(po.getPassword());
dto.setStatus(po.getLastStatusCode());
dto.setCreatedAt(po.getCreatedTimeStamp());
dto.setModifiedAt(po.getModifiedTimeStamp());
dto.setPrivilege(po.getPrivilege());
dto.setAccountStatus(po.getAccountStatus());
return dto;
}
/**
* Convert User DTO to UserPO object
*
* @param dto
* - User DTO object
*
* @return - UserPO object
*/
public static final UserPO convert(User dto) {
if (dto == null) {
return null;
}
UserPO po = new UserPO();
po.setUserName(dto.getUserName());
po.setPassword(dto.getPassword());
po.setCreatedTimeStamp(dto.getCreatedAt());
po.setLastStatusCode(dto.getStatus());
po.setModifiedTimeStamp(dto.getModifiedAt());
po.setPrivilege(dto.getPrivilege());
po.setAccountStatus(dto.getAccountStatus());
return po;
}
/**
* Convert StatusPO to Status DTO object.
*
* @param po
* - Status PO object
*
* @return - Status DTO Object
*/
public static final Status convert(StatusPO po) {
if (po == null) {
return null;
}
Status dto = new Status();
dto.setCrumbID(po.getCrumbID());
dto.setUserName(po.getUserName());
dto.setStatusCode(po.getStatusCode());
dto.setCreateAt(po.getCreateAt());
return dto;
}
/**
* Convert Status DTO to StatusPO object
*
* @param dto
* - Status DTO object
*
* @return - StautsPO object
*/
public static final StatusPO convert(Status dto) {
if (dto == null) {
return null;
}
StatusPO po = new StatusPO();
po.setUserName(dto.getUserName());
po.setCreateAt(dto.getCreateAt());
po.setStatusCode(dto.getStatusCode());
return po;
}
/**
* Convert MessagePO to Message DTO object.
*
* @param po
* - Message PO object
*
* @return - Message DTO Object
*/
public static final Message convert(MessagePO po) {
if (po == null) {
return null;
}
Message dto = new Message();
dto.setMessageId(po.getMessageId());
dto.setAuthor(po.getAuthor());
dto.setContent(po.getContent());
dto.setMessageType(po.getMessageType());
dto.setPostedAt(po.getPostedAt());
dto.setTarget(po.getTarget());
return dto;
}
/**
* Convert Message DTO to MessagePO object
*
* @param dto
* - Message DTO object
*
* @return - MessagePO object
*/
public static final MessagePO convert(Message dto) {
if (dto == null) {
return null;
}
MessagePO po = new MessagePO();
po.setMessageId(dto.getMessageId());
po.setAuthor(dto.getAuthor());
po.setContent(dto.getContent());
po.setMessageType(dto.getMessageType());
po.setPostedAt(dto.getPostedAt());
po.setTarget(dto.getTarget());
return po;
}
/**
* Convert MemoryPO to Memory DTO object.
*
* @param po
* - Memory PO object
*
* @return - Memory DTO Object
*/
public static final Memory convert(MemoryPO po) {
if (po == null) {
return null;
}
Memory dto = new Memory();
dto.setCrumbID(po.getCrumbID());
dto.setCreatedTimeStamp(po.getCreatedTimeStamp());
dto.setRemainingPersistent(po.getRemainingPersistent());
dto.setRemainingVolatile(po.getRemainingVolatile());
dto.setUsedPersistent(po.getUsedPersistent());
dto.setUsedVolatile(po.getUsedVolatile());
return dto;
}
/**
* Convert Memory DTO to MemoryPO object
*
* @param dto
* - Memory DTO object
*
* @return - MemoryPO object
*/
public static final MemoryPO convert(Memory dto) {
if (dto == null) {
return null;
}
MemoryPO po = new MemoryPO();
po.setCrumbID(dto.getCrumbID());
po.setCreatedTimeStamp(dto.getCreatedTimeStamp());
po.setRemainingPersistent(dto.getRemainingPersistent());
po.setRemainingVolatile(dto.getRemainingVolatile());
po.setUsedPersistent(dto.getUsedPersistent());
po.setUsedVolatile(dto.getUsedVolatile());
return po;
}
}
| 23.291866 | 77 | 0.668447 |
bc6e831fb28d3bed7fda1773584014815c832345 | 2,053 | /**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <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 cn.stylefeng.guns.modular.web.Api;
import cn.stylefeng.guns.core.util.ApiResponseUtil;
import cn.stylefeng.guns.modular.web.entity.Params;
import cn.stylefeng.guns.modular.web.service.ParamsService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 参数APi
*
* @author gsk
* @Date 201900514
*/
@RestController
@RequestMapping("/api/params")
public class ParamsApi extends BaseController {
@Autowired
private ParamsService paramsService;
/**
* 获取列表不分页
*
*/
@GetMapping("")
public Object getCouponList(Integer site) {
if (site==null)
ApiResponseUtil.fail409();
List<Map<String,Object>> couponList=paramsService.queryList(site);
return ApiResponseUtil.ok(couponList);
}
/**
* 获取轮播图列表
*
*/
@GetMapping("getBannerList")
public Object getBannerList(Integer site) {
if (site==null)
return ApiResponseUtil.fail409();
List<Map<String,Object>> bannerList=paramsService.queryListLunBo(site);
return ApiResponseUtil.ok(bannerList);
}
}
| 28.123288 | 79 | 0.717487 |
11553c9ec7cae2cf2292aab87fa9bb650fee1682 | 812 | package edu.millersville.uml_editor.modelTest;
import edu.millersville.uml_editor.model.*;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RelationshipTest {
/* test constructor and getters */
@Test
public void testConstructorandGetters() {
ClassObject class1 = new ClassObject("class1");
ClassObject class2 = new ClassObject("class2");
Relationships r = new Relationships(class1, class2, "ID1", "A");
assertEquals("Relationship name should be set properly.", "A", r.relType());
assertEquals("First class name should be set properly.", class1.getName(), r.sourceName());
assertEquals("Second class name should be set properly.", class2.getName(), r.destinationName());
assertEquals("Relationship ID name should be set properly.", "ID1", r.getId());
}
}
| 35.304348 | 99 | 0.741379 |
3363f7e0f41c732c3cb0a9d36fabf79a16b6753a | 451 | public static boolean binarySearch(int target, int{} numbers) {
int floor = -1;
int ceilingIndex = numbers.length;
while (floor + 1 < ceiling) {
int searchRange = ceiling - floor;
int halfRange = searchRange / 2;
int middle = floor + halfRange;
int middleVal = numbers[middle];
if (middleVal == target) {
return true;
}
if (middleVal > target) {
celing = middle;
} else {
floor = middle;
}
}
return false;
}
| 16.703704 | 63 | 0.631929 |
2a7ec6b4da64dcd4afc479aa0d59a35bd452816a | 4,985 | import java.io.*;
import java.net.*;
import java.util.*;
import java.security.*;
class BlockChain
{
int index;
List<Object> chain = new ArrayList<Object>();
HashMap<String, DSA> dsa;
BlockChain(HashMap<String, DSA> dsa)throws Exception
{
this.index=0;
this.dsa=dsa;
chain.add(createGenisis());
}
Block createGenisis()throws Exception
{
Block newBlock = new Block(index++,null,null,0,null,-1);
newBlock.hash=newBlock.calculateHash();
return newBlock;
}
Block getLatestBlock()throws Exception
{
return (Block)chain.get(chain.size()-1);
}
void addBlock(Block newBlock)throws Exception
{
newBlock.prevHash=getLatestBlock().hash;
newBlock.hash=newBlock.calculateHash();
chain.add(newBlock);
}
boolean isChainValid()throws Exception
{
for(int i= 1;i<chain.size();i++)
{
Block currentBlock=(Block)chain.get(i);
Block prevBlock=(Block)chain.get(i-1);
if(currentBlock.prevHash!=prevBlock.hash)
return false;
}
return true;
}
void MakeCoin(String name,int money)throws Exception
{
if(name=="goofy")
{
DSA en=(DSA)dsa.get("goofy");
addBlock(new Block(index++,en.pubKey,en.pubKey,money,en.sign(""+(index-1)+(en.pubKey).toString()+money),-1));
System.out.println("Added");
}
else
System.out.println(name+" is not the miner.");
}
void ValidateTransaction(String sender,String reciever,int amount)throws Exception
{
boolean ans;
int flag;
Block currentBlock;
DSA en=(DSA)dsa.get(sender);
DSA ef=(DSA)dsa.get(reciever);
for(int i= chain.size()-1;i>=0;i--)
{
currentBlock=(Block)chain.get(i);
if(currentBlock.reciever==en.pubKey)
if(amount<=currentBlock.amount && currentBlock.spent==false)
{
flag=0;
while(currentBlock.index>0)
{
if(en.Verify(currentBlock.reciever,""+currentBlock.index+(currentBlock.reciever).toString()+currentBlock.amount,currentBlock.signature))
{
if(currentBlock.prevPointer!=-1)
currentBlock=(Block)chain.get(currentBlock.prevPointer);
else
break;
}
else
{
flag=1;
break;
}
}
if(flag==0)
{
currentBlock=(Block)chain.get(i);
currentBlock.spent=true;
if(currentBlock.amount-amount>0)
addBlock(new Block(index++,en.pubKey,en.pubKey,currentBlock.amount-amount,en.sign(""+(index-1)+(en.pubKey).toString()+(currentBlock.amount-amount)),i));
addBlock(new Block(index++,en.pubKey,ef.pubKey,amount,ef.sign(""+(index-1)+(ef.pubKey).toString()+(amount)),i));
System.out.println("Transaction Done");
return;
}
}
}
System.out.println(sender+" do not have that much money");
}
void ValidateBlock(int no)throws Exception
{
int flag=0;
Block currentBlock;
DSA en=new DSA();
while(no!=-1)
{
currentBlock=(Block)chain.get(no);
if(en.Verify(currentBlock.reciever,""+currentBlock.index+(currentBlock.reciever).toString()+currentBlock.amount,currentBlock.signature))
{
printBlock(currentBlock);
no=currentBlock.prevPointer;
}
else
{
flag=1;
break;
}
}
if(flag==0)
System.out.println("Valid");
else
System.out.println("NOT Valid");
}
void printBlock(Block newBlock)throws Exception
{
System.out.println("{");
System.out.println(" Index : "+newBlock.index);
System.out.println(" sender's Public key : "+newBlock.sender);
System.out.println(" reciever's Public Key : "+newBlock.reciever);
System.out.println(" amount : "+newBlock.amount);
System.out.println(" prevHash : "+newBlock.prevHash);
System.out.println(" hash : "+newBlock.hash);
System.out.println(" Signed : "+newBlock.signature);
System.out.println(" prevPointer : "+newBlock.prevPointer);
System.out.println(" Spent : "+newBlock.spent);
System.out.println("}");
}
void printList()throws Exception
{
for(int i=0;i<chain.size();i++)
{
Block newBlock = (Block)chain.get(i);
System.out.println("{");
System.out.println(" Index : "+newBlock.index);
System.out.println(" sender's Public key : "+newBlock.sender);
System.out.println(" reciever's Public Key : "+newBlock.reciever);
System.out.println(" amount : "+newBlock.amount);
System.out.println(" prevHash : "+newBlock.prevHash);
System.out.println(" hash : "+newBlock.hash);
System.out.println(" Signed : "+newBlock.signature);
System.out.println(" prevPointer : "+newBlock.prevPointer);
System.out.println(" Spent : "+newBlock.spent);
System.out.println("}");
}
}
}
| 29.672619 | 169 | 0.601805 |
3e419280091fe10ff0e72d1fc7724a3585a84e36 | 9,942 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dataproc.v1beta2.model;
/**
* A configurable parameter that replaces one or more fields in the template. Parameterizable
* fields: - Labels - File uris - Job properties - Job arguments - Script variables - Main class (in
* HadoopJob and SparkJob) - Zone (in ClusterSelector)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Dataproc API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class TemplateParameter extends com.google.api.client.json.GenericJson {
/**
* Optional. Brief description of the parameter. Must not exceed 1024 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Required. Paths to all fields that the parameter replaces. A field is allowed to appear in at
* most one parameter's list of field paths.A field path is similar in syntax to a
* google.protobuf.FieldMask. For example, a field path that references the zone field of a
* workflow template's cluster selector would be specified as placement.clusterSelector.zone.Also,
* field paths can reference fields using the following syntax: Values in maps can be referenced
* by key: labels'key' placement.clusterSelector.clusterLabels'key'
* placement.managedCluster.labels'key' placement.clusterSelector.clusterLabels'key' jobs'step-
* id'.labels'key' Jobs in the jobs list can be referenced by step-id: jobs'step-
* id'.hadoopJob.mainJarFileUri jobs'step-id'.hiveJob.queryFileUri jobs'step-
* id'.pySparkJob.mainPythonFileUri jobs'step-id'.hadoopJob.jarFileUris0 jobs'step-
* id'.hadoopJob.archiveUris0 jobs'step-id'.hadoopJob.fileUris0 jobs'step-
* id'.pySparkJob.pythonFileUris0 Items in repeated fields can be referenced by a zero-based
* index: jobs'step-id'.sparkJob.args0 Other examples: jobs'step-id'.hadoopJob.properties'key'
* jobs'step-id'.hadoopJob.args0 jobs'step-id'.hiveJob.scriptVariables'key' jobs'step-
* id'.hadoopJob.mainJarFileUri placement.clusterSelector.zoneIt may not be possible to
* parameterize maps and repeated fields in their entirety since only individual map values and
* individual items in repeated fields can be referenced. For example, the following field paths
* are invalid: placement.clusterSelector.clusterLabels jobs'step-id'.sparkJob.args
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> fields;
/**
* Required. Parameter name. The parameter name is used as the key, and paired with the parameter
* value, which are passed to the template when the template is instantiated. The name must
* contain only capital letters (A-Z), numbers (0-9), and underscores (_), and must not start with
* a number. The maximum length is 40 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Optional. Validation rules to be applied to this parameter's value.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ParameterValidation validation;
/**
* Optional. Brief description of the parameter. Must not exceed 1024 characters.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* Optional. Brief description of the parameter. Must not exceed 1024 characters.
* @param description description or {@code null} for none
*/
public TemplateParameter setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Required. Paths to all fields that the parameter replaces. A field is allowed to appear in at
* most one parameter's list of field paths.A field path is similar in syntax to a
* google.protobuf.FieldMask. For example, a field path that references the zone field of a
* workflow template's cluster selector would be specified as placement.clusterSelector.zone.Also,
* field paths can reference fields using the following syntax: Values in maps can be referenced
* by key: labels'key' placement.clusterSelector.clusterLabels'key'
* placement.managedCluster.labels'key' placement.clusterSelector.clusterLabels'key' jobs'step-
* id'.labels'key' Jobs in the jobs list can be referenced by step-id: jobs'step-
* id'.hadoopJob.mainJarFileUri jobs'step-id'.hiveJob.queryFileUri jobs'step-
* id'.pySparkJob.mainPythonFileUri jobs'step-id'.hadoopJob.jarFileUris0 jobs'step-
* id'.hadoopJob.archiveUris0 jobs'step-id'.hadoopJob.fileUris0 jobs'step-
* id'.pySparkJob.pythonFileUris0 Items in repeated fields can be referenced by a zero-based
* index: jobs'step-id'.sparkJob.args0 Other examples: jobs'step-id'.hadoopJob.properties'key'
* jobs'step-id'.hadoopJob.args0 jobs'step-id'.hiveJob.scriptVariables'key' jobs'step-
* id'.hadoopJob.mainJarFileUri placement.clusterSelector.zoneIt may not be possible to
* parameterize maps and repeated fields in their entirety since only individual map values and
* individual items in repeated fields can be referenced. For example, the following field paths
* are invalid: placement.clusterSelector.clusterLabels jobs'step-id'.sparkJob.args
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getFields() {
return fields;
}
/**
* Required. Paths to all fields that the parameter replaces. A field is allowed to appear in at
* most one parameter's list of field paths.A field path is similar in syntax to a
* google.protobuf.FieldMask. For example, a field path that references the zone field of a
* workflow template's cluster selector would be specified as placement.clusterSelector.zone.Also,
* field paths can reference fields using the following syntax: Values in maps can be referenced
* by key: labels'key' placement.clusterSelector.clusterLabels'key'
* placement.managedCluster.labels'key' placement.clusterSelector.clusterLabels'key' jobs'step-
* id'.labels'key' Jobs in the jobs list can be referenced by step-id: jobs'step-
* id'.hadoopJob.mainJarFileUri jobs'step-id'.hiveJob.queryFileUri jobs'step-
* id'.pySparkJob.mainPythonFileUri jobs'step-id'.hadoopJob.jarFileUris0 jobs'step-
* id'.hadoopJob.archiveUris0 jobs'step-id'.hadoopJob.fileUris0 jobs'step-
* id'.pySparkJob.pythonFileUris0 Items in repeated fields can be referenced by a zero-based
* index: jobs'step-id'.sparkJob.args0 Other examples: jobs'step-id'.hadoopJob.properties'key'
* jobs'step-id'.hadoopJob.args0 jobs'step-id'.hiveJob.scriptVariables'key' jobs'step-
* id'.hadoopJob.mainJarFileUri placement.clusterSelector.zoneIt may not be possible to
* parameterize maps and repeated fields in their entirety since only individual map values and
* individual items in repeated fields can be referenced. For example, the following field paths
* are invalid: placement.clusterSelector.clusterLabels jobs'step-id'.sparkJob.args
* @param fields fields or {@code null} for none
*/
public TemplateParameter setFields(java.util.List<java.lang.String> fields) {
this.fields = fields;
return this;
}
/**
* Required. Parameter name. The parameter name is used as the key, and paired with the parameter
* value, which are passed to the template when the template is instantiated. The name must
* contain only capital letters (A-Z), numbers (0-9), and underscores (_), and must not start with
* a number. The maximum length is 40 characters.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. Parameter name. The parameter name is used as the key, and paired with the parameter
* value, which are passed to the template when the template is instantiated. The name must
* contain only capital letters (A-Z), numbers (0-9), and underscores (_), and must not start with
* a number. The maximum length is 40 characters.
* @param name name or {@code null} for none
*/
public TemplateParameter setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Optional. Validation rules to be applied to this parameter's value.
* @return value or {@code null} for none
*/
public ParameterValidation getValidation() {
return validation;
}
/**
* Optional. Validation rules to be applied to this parameter's value.
* @param validation validation or {@code null} for none
*/
public TemplateParameter setValidation(ParameterValidation validation) {
this.validation = validation;
return this;
}
@Override
public TemplateParameter set(String fieldName, Object value) {
return (TemplateParameter) super.set(fieldName, value);
}
@Override
public TemplateParameter clone() {
return (TemplateParameter) super.clone();
}
}
| 49.462687 | 182 | 0.742406 |
f4f12399820c7794a19d8e3ff4031634f1386298 | 5,618 | /*
* ====================================================================
* StreamEPS Platform
*
* (C) Copyright 2012.
*
* Distributed under the Modified BSD License.
* Copyright notice: The copyright for this software and a full listing
* of individual contributors are as shown in the packaged copyright.txt
* file.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the ORGANIZATION nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL 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 org.streameps.engine;
import java.util.List;
import java.util.Map;
import org.streameps.aggregation.collection.Accumulator;
import org.streameps.filter.FilterType;
import org.streameps.filter.IFilterValueSet;
/**
* A interface for executing a series of filter expressions defined in the filter
* context.
*
* @author Frank Appiah
*/
public interface IFilterChain<T extends Accumulator> {
/**
* It adds the filter context for the chain of filter context instances.
* @param context An instance of the filter context.
*/
public void addFilterContext(IFilterContext<T> context);
/**
* It adds the filter visitor with its filter type to the map of filterVisitor-filterType
* pair.
* @param filterType The specific filter type.
* @param filterVisitor The instance of the filter value set.
*/
public void addFilterVisitor(FilterType filterType, IFilterVisitor<T> filterVisitor);
/**
* It adds the filter value set with its filter type to the map of filterValue-filterType
* pair.
* @param filterType The specific filter type.
* @param filterValueSet The instance of the filter value set.
*/
public void addFilterValueSet(FilterType filterType, IFilterValueSet<T> filterValueSet);
/**
* It adds the filter visitor with its filter type to the map of filterVisitor-filterType
* pair.
* @param filterType The specific string filter type.
* @param filterVisitor The instance of the filter value set.
*/
public void addFilterVisitor(String filterType, IFilterVisitor<T> filterVisitor);
/**
* It adds the filter value set with its filter type to the map of filterValue-filterType
* pair.
* @param filterType The specific string filter type.
* @param filterValueSet The instance of the filter value set.
*/
public void addFilterValueSet(String filterType, IFilterValueSet<T> filterValueSet);
/**
* It returns the list of filter contexts to be used for the filter evaluation
* defined by the filter visitor.
* @return A list of filter context instances.
*/
public List<IFilterContext<T>> getFilterContexts();
/**
* It sets the list of filter contexts to be used for the filter evaluation
* defined by the filter visitor.
*
* @param filterContexts A list of filter context instances.
*/
public void setFilterContexts(List<IFilterContext<T>> filterContexts);
/**
* It visits the filter visitor context passed to it.
* @param filterVisitor An instance of the filter visitor.
*/
public void executeVisitor();
/**
* It returns the filter value map after execution of the filter chain.
* @return A map of filter value set.
*/
public Map<FilterType, IFilterValueSet<T>> getFilterValueMap();
/**
* It sets the filter value map after execution of the filter chain.
* @param valueMap A map of filter value set.
*/
public void setFilterValueMap(Map<FilterType, IFilterValueSet<T>> valueMap);
/**
* It sets a map containing the filter type and the filter visitor for
* each filter context.
*
* @param visitorMap A map instance containing the filterType-filterVisitor pair.
*/
public void setFilterVisitorMap(Map<FilterType, IFilterVisitor<T>> visitorMap);
/**
* It returns a map containing the filter type and the filter visitor for
* each filter context.
*
* @return A map instance containing the filterType-filterVisitor pair.
*/
public Map<FilterType, IFilterVisitor<T>> getFilterVisitorMap();
}
| 39.843972 | 93 | 0.698113 |
5c964363bc2f5c5abbe4436b6ea8b497c94f18f4 | 4,934 | /*
* Copyright 2016 Ashwin Nath Chatterji
*
* 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.example.ashwin.popularmovies;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by ashwin on 7/3/2016.
*/
public class FetchReviewTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
private final Context mContext;
public ReviewAsyncResponse delegate = null;
public FetchReviewTask(Context context) {
mContext = context;
}
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
// needs to be outside try catch to use in finally
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// will contain the raw JSON response as a string
String movieJsonStr = null;
try {
//http://api.themoviedb.org/3/movie/{movie_id}/videos?api_key=**REMOVED**
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.themoviedb.org")
.appendPath("3")
.appendPath("movie")
.appendPath(params[0])
.appendPath("reviews")
.appendQueryParameter("api_key", mContext.getString(R.string.tmdb_api_key));
String website = builder.build().toString();
URL url = new URL(website);
// Create the request to themoviedb and open connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// nothing to do
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// doesn't affect JSON but it's a lot easier for a human to read
buffer.append(line +"\n");
}
if (buffer.length() == 0) {
// empty stream
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getReviewArray(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
@Nullable
private String[] getReviewArray(String reviewJsonStr)
throws JSONException {
try {
JSONObject reviewJson = new JSONObject(reviewJsonStr);
JSONArray resultArray = reviewJson.getJSONArray("results");
String[] reviewArray = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
reviewArray[i] = resultArray.getJSONObject(i).getString("content");
}
return reviewArray;
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
delegate.reviewProcessFinish(result);
}
public interface ReviewAsyncResponse {
void reviewProcessFinish(String[] output);
}
}
| 33.337838 | 96 | 0.592217 |
51bd3dcd43f0f1ee2006241fe16480f18d02f447 | 1,422 | package com.sc2toolslab.sc2bm.ui.presenters;
import com.sc2toolslab.sc2bm.domain.RaceEnum;
import com.sc2toolslab.sc2bm.ui.providers.BuildOrdersProvider;
import com.sc2toolslab.sc2bm.ui.providers.IFilterUpdated;
import com.sc2toolslab.sc2bm.ui.views.INavDrawerView;
public class NavDrawerPresenter implements IPresenter, IFilterUpdated {
private INavDrawerView mView;
public NavDrawerPresenter(INavDrawerView view) {
this.mView = view;
BuildOrdersProvider.getInstance(mView.getContext()).setOnFilterChangedListener(this);
_bindData();
}
@Override
public void onFilterUpdated() {
_bindData();
}
private void _bindData() {
String version = BuildOrdersProvider.getInstance(mView.getContext()).getVersionFilter();
RaceEnum mainFaction = BuildOrdersProvider.getInstance(mView.getContext()).getFactionFilter();
mView.setFaction(mainFaction);
mView.setVsTerranBuildCount(_getMatchCountVsFaction(mainFaction, RaceEnum.Terran), mainFaction);
mView.setVsProtossBuildCount(_getMatchCountVsFaction(mainFaction, RaceEnum.Protoss), mainFaction);
mView.setVsZergBuildCount(_getMatchCountVsFaction(mainFaction, RaceEnum.Zerg), mainFaction);
mView.setAddon(version);
mView.setVersion(version);
}
private int _getMatchCountVsFaction(RaceEnum mainFaction, RaceEnum vsFaction) {
return BuildOrdersProvider.getInstance(mView.getContext()).getBuildOrdersCountForMatchup(mainFaction, vsFaction);
}
}
| 35.55 | 115 | 0.817159 |
2e76e58b066179077ca117a2c89bda80ccb07fd0 | 2,010 | package com.tml.server.system.controller;
import com.tml.api.system.entity.GatewayBlockListLog;
import com.tml.common.core.entity.CommonResult;
import com.tml.common.core.entity.QueryRequest;
import com.tml.common.core.entity.constant.StringConstant;
import com.tml.common.core.exception.BrightException;
import com.tml.common.core.utils.BrightUtil;
import com.tml.server.system.service.IGatewayBlockListLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import java.util.Map;
/**
* 黑名单日志 Controller
*
* @author JacksonTu
* @date 2020-08-13 09:47:31
*/
@Slf4j
@Validated
@RestController
@RequestMapping("gatewayBlockListLog")
@RequiredArgsConstructor
public class GatewayBlockListLogController {
private final IGatewayBlockListLogService gatewayBlockListLogService;
@GetMapping("list")
@PreAuthorize("hasAuthority('gatewayBlockListLog:list')")
public CommonResult gatewayBlockListLogList(QueryRequest request, GatewayBlockListLog gatewayBlockListLog) {
Map<String, Object> dataTable = BrightUtil.getDataTable(this.gatewayBlockListLogService.pageGatewayBlockListLog(request, gatewayBlockListLog));
return new CommonResult().data(dataTable);
}
@DeleteMapping("{ids}")
@PreAuthorize("hasAuthority('gatewayBlockListLog:delete')")
public void deleteGatewayBlackListLog(@NotBlank(message = "{required}") @PathVariable String ids) throws BrightException {
try {
String[] idArray = ids.split(StringConstant.COMMA);
this.gatewayBlockListLogService.deleteGatewayBlockListLog(idArray);
} catch (Exception e) {
String message = "删除GatewayBlackListLog失败";
log.error(message, e);
throw new BrightException(message);
}
}
}
| 37.222222 | 151 | 0.768657 |
9c99bfbc2a9e9c10ffae1d3d5aa2f61ddeaff146 | 1,162 | package com.dlam.pptowers.entities;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.entity.projectile.ProjectileEntity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Position;
import net.minecraft.util.math.PositionImpl;
/*
Used for towers that fire projectiles that are affected by gravity
*/
public abstract class TrajectoryTowerBlockEntity extends ProjectileTowerBlockEntity {
public TrajectoryTowerBlockEntity(BlockEntityType<?> type, double xRange, double yRange, double zRange, int fireRate) {
super(type, xRange, yRange, zRange, fireRate);
}
@Override
protected void shoot() {
Position position = new PositionImpl(pos.getX() + xFace, pos.getY() + yFace, pos.getZ() + zFace);
ProjectileEntity proj = this.createProjectile(world, position);
double x = target.getX() - proj.getX();
double y = target.getBodyY(0.33333333D) - proj.getY();
double z = target.getZ() - proj.getZ();
double d = (double) MathHelper.sqrt(x * x + z * z);
proj.setVelocity(x, y + d * 0.1D, z, 1.6F, 0);
world.spawnEntity(proj);
}
}
| 38.733333 | 123 | 0.697935 |
26175b3bb4385e1761d56005d4f90c6f4df28683 | 316 | package caca.extraction;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PathFinderApplication {
public static void main(String[] args) {
SpringApplication.run(PathFinderApplication.class, args);
}
}
| 22.571429 | 68 | 0.825949 |
0c98b5208fb1d28c0cd73fba4cfcbaf0f1e9af36 | 1,041 | package com.ettrema.http;
import com.ettrema.http.caldav.ITip;
import com.ettrema.http.caldav.ITip.StatusResponse;
/**
*
* @author brad
*/
public class SchedulingResponseItem {
// Eg mailto:[email protected]
private String recipient;
private ITip.StatusResponse status;
private String iCalText;
public SchedulingResponseItem(String recipient, StatusResponse status, String iCalText) {
this.recipient = recipient;
this.status = status;
this.iCalText = iCalText;
}
public SchedulingResponseItem() {
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public StatusResponse getStatus() {
return status;
}
public void setStatus(StatusResponse status) {
this.status = status;
}
public String getiCalText() {
return iCalText;
}
public void setiCalText(String iCalText) {
this.iCalText = iCalText;
}
}
| 20.411765 | 93 | 0.659942 |
025c73fb577ce16b357f1f6e3b2ceed74bfded83 | 622 | package test.org.springdoc.api.app33;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController<T> {
@GetMapping(value = "/hello/{numTelco}")
@Operation(summary = "GET Persons", responses = @ApiResponse(responseCode = "418"))
public T index(@PathVariable("numTelco") String numTel, String adresse) {
return null;
}
}
| 34.555556 | 87 | 0.768489 |
64f59c8adcd894c62dfb1ade383bb2fbe9fde40a | 1,150 | package com.sample.casino.model;
import java.text.DecimalFormat;
/**
* Bean <code>QueryResult</code> is used to store queries from <code>slotmachines</code> table.
*/
public class QueryResult {
private String id;
private double sentiment;
private String casinoid;
private double sum;
private int count;
public String getId() {
return id;
}
public void setId(String slotMachineId) {
this.id = slotMachineId;
}
public String getCasinoid() {
return casinoid;
}
public void setCasinoid(String casinoid) {
this.casinoid = casinoid;
}
public double getSentiment() {
return sentiment;
}
public void setSentiment(double sentiment) {
this.sentiment = sentiment;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getSum() {
return sum;
}
public void setSum(double sentimentSum) {
this.sum = sentimentSum;
}
public double getAverageSentiment() {
DecimalFormat df = new DecimalFormat("#.#");
double value = (this.sum / this.count);
value = Double.valueOf(df.format(value));
return value;
}
}
| 17.96875 | 95 | 0.681739 |
88c0aea1723d599078f764377394b2bafea76b72 | 1,958 | package com.rossos.cryptography;
import java.util.Scanner;
/**
* @author Daniel Rossos
*
*/
public class Vigenere extends Cipher{
private String key;
/**
* @param encOrDec int deciding to encode (0) or decode (1)
* @param phrase String for encoding or decoding
* @param key String that will be compared against in making and
* decoding the message
*/
public Vigenere(int encOrDec, String phrase, String key) {
super(encOrDec,phrase);
this.key = formatKey(key,phrase);
if (encOrDec == Cipher.ENCODE) {
super.setEncoded(encode(super.getDecoded(),super.getEncoded()));
System.out.println("Encoded message is: " + super.getEncoded());
}
if (encOrDec == Cipher.DECODE) {
super.setDecoded(decode(super.getDecoded(),super.getEncoded()));
System.out.println("Encoded message is: " + super.getDecoded());
}
}
private String formatKey(String key2, String phrase) {
String updateKey = key2;
int indexInKey = 0;
while (updateKey.length() < phrase.length()) {
if (indexInKey == key2.length())
indexInKey = 0;
updateKey += key2.charAt(indexInKey);
}
return updateKey;
}
private String decode(String decoded, String encoded) {
int keyIndex = 0;
for (int i = 0; i < encoded.length();i++){
char x = (char) (encoded.charAt(i) - (key.charAt(keyIndex)-65));
if (x < 65)
x += 26;
decoded += x;
keyIndex++;
if (keyIndex == key.length())
keyIndex = 0;
}
return decoded;
}
private String encode(String decoded, String encoded) {
int keyIndex = 0;
for (int i = 0; i < decoded.length();i++){
char x = (char) (decoded.charAt(i) + (key.charAt(keyIndex)-65));
if (x > 90)
x -= 26;
encoded += x;
keyIndex++;
if (keyIndex == key.length())
keyIndex = 0;
}
return encoded;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
} | 25.763158 | 68 | 0.620531 |
3540755bcc13855d82c58f8ad337da5a1a372cb3 | 1,335 | package dk.in2isoft.onlineobjects.services;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jdt.annotation.Nullable;
import com.google.common.collect.Lists;
import dk.in2isoft.onlineobjects.core.SubSession;
public class SessionService {
private static final Logger log = LogManager.getLogger(SessionService.class);
private List<SubSession> subSessions = Lists.newArrayList();
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
//session.setMaxInactiveInterval(10);
log.debug("Session created: id="+session.getId()+",interval="+session.getMaxInactiveInterval());
}
public void sessionDestroyed(HttpSessionEvent event) {
log.debug("Session destroyed: "+event.getSession().getId());
}
public void registerSubSession(SubSession subSession) {
this.subSessions.add(subSession);
}
@Deprecated
@SuppressWarnings("unchecked")
public <T extends SubSession> @Nullable T getSubSession(String id, Class<T> type) {
for (SubSession subSession : subSessions) {
if (subSession.getId().equals(id) && type.isAssignableFrom(subSession.getClass())) {
return (T) subSession;
}
}
return null;
}
}
| 27.244898 | 98 | 0.764794 |
bfe4cb1a2bb82d2df522b39c6b019d2e484b9454 | 390 | public class S372 {
public int superPow(int a, int[] b) {
return dfs(a, b, b.length - 1);
}
int dfs(int a, int[] b, int u) {
if (u == -1) return 1;
return pow(dfs(a, b, u - 1), 10) * pow(a, b[u]) % 1337;
}
int pow(int a, int b) {
int ans = 1;
a %= 1337;
while (b-- > 0) ans = ans * a % 1337;
return ans;
}
}
| 21.666667 | 63 | 0.433333 |
af38c3a747fdd04cfc65f6a5c408d8bacd073d0a | 6,536 | /*
* 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 gobblin.source.extractor.extract.kafka.workunit.packer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import com.google.common.collect.Lists;
import gobblin.configuration.SourceState;
import gobblin.configuration.State;
import gobblin.source.extractor.extract.AbstractSource;
import gobblin.source.workunit.MultiWorkUnit;
import gobblin.source.workunit.WorkUnit;
/**
* An implementation of {@link KafkaWorkUnitPacker} with two levels of bin packing.
*
* In the first level, some {@link WorkUnit}s corresponding to partitions
* of the same topic are grouped together into a single {@link WorkUnit}. The number of grouped {@link WorkUnit}s
* is approximately {@link #WORKUNIT_PRE_GROUPING_SIZE_FACTOR} * number of {@link MultiWorkUnit}s. The value of
* {@link #WORKUNIT_PRE_GROUPING_SIZE_FACTOR} should generally be 3.0 or higher, since the worst-fit-decreasing
* algorithm (used by the second level) may not achieve a good balance if the number of items
* is less than 3 times the number of bins.
*
* In the second level, these grouped {@link WorkUnit}s are assembled into {@link MultiWorkunit}s
* using worst-fit-decreasing.
*
* Bi-level bin packing has two advantages: (1) reduce the number of small output files since it tends to pack
* partitions of the same topic together; (2) reduce the total number of workunits / tasks since multiple partitions
* of the same topic are assigned to the same task. A task has a non-trivial cost of initialization, tear down and
* task state persistence. However, bi-level bin packing has more mapper skew than single-level bin packing, because
* if we pack lots of partitions of the same topic to the same mapper, and we underestimate the avg time per record
* for this topic, then this mapper could be much slower than other mappers.
*
* @author Ziyang Liu
*/
public class KafkaBiLevelWorkUnitPacker extends KafkaWorkUnitPacker {
public static final String WORKUNIT_PRE_GROUPING_SIZE_FACTOR = "workunit.pre.grouping.size.factor";
public static final double DEFAULT_WORKUNIT_PRE_GROUPING_SIZE_FACTOR = 3.0;
protected KafkaBiLevelWorkUnitPacker(AbstractSource<?, ?> source, SourceState state) {
super(source, state);
}
@Override
public List<WorkUnit> pack(Map<String, List<WorkUnit>> workUnitsByTopic, int numContainers) {
double totalEstDataSize = setWorkUnitEstSizes(workUnitsByTopic);
double avgGroupSize = totalEstDataSize / numContainers / getPreGroupingSizeFactor(this.state);
List<MultiWorkUnit> mwuGroups = Lists.newArrayList();
for (List<WorkUnit> workUnitsForTopic : workUnitsByTopic.values()) {
double estimatedDataSizeForTopic = calcTotalEstSizeForTopic(workUnitsForTopic);
if (estimatedDataSizeForTopic < avgGroupSize) {
// If the total estimated size of a topic is smaller than group size, put all partitions of this
// topic in a single group.
MultiWorkUnit mwuGroup = MultiWorkUnit.createEmpty();
addWorkUnitsToMultiWorkUnit(workUnitsForTopic, mwuGroup);
mwuGroups.add(mwuGroup);
} else {
// Use best-fit-decreasing to group workunits for a topic into multiple groups.
mwuGroups.addAll(bestFitDecreasingBinPacking(workUnitsForTopic, avgGroupSize));
}
}
List<WorkUnit> groups = squeezeMultiWorkUnits(mwuGroups);
return worstFitDecreasingBinPacking(groups, numContainers);
}
private static double calcTotalEstSizeForTopic(List<WorkUnit> workUnitsForTopic) {
double totalSize = 0;
for (WorkUnit w : workUnitsForTopic) {
totalSize += getWorkUnitEstSize(w);
}
return totalSize;
}
private static double getPreGroupingSizeFactor(State state) {
return state.getPropAsDouble(WORKUNIT_PRE_GROUPING_SIZE_FACTOR, DEFAULT_WORKUNIT_PRE_GROUPING_SIZE_FACTOR);
}
/**
* Group {@link WorkUnit}s into groups. Each group is a {@link MultiWorkUnit}. Each group has a capacity of
* avgGroupSize. If there's a single {@link WorkUnit} whose size is larger than avgGroupSize, it forms a group itself.
*/
private static List<MultiWorkUnit> bestFitDecreasingBinPacking(List<WorkUnit> workUnits, double avgGroupSize) {
// Sort workunits by data size desc
Collections.sort(workUnits, LOAD_DESC_COMPARATOR);
PriorityQueue<MultiWorkUnit> pQueue = new PriorityQueue<>(workUnits.size(), LOAD_DESC_COMPARATOR);
for (WorkUnit workUnit : workUnits) {
MultiWorkUnit bestGroup = findAndPopBestFitGroup(workUnit, pQueue, avgGroupSize);
if (bestGroup != null) {
addWorkUnitToMultiWorkUnit(workUnit, bestGroup);
} else {
bestGroup = MultiWorkUnit.createEmpty();
addWorkUnitToMultiWorkUnit(workUnit, bestGroup);
}
pQueue.add(bestGroup);
}
return Lists.newArrayList(pQueue);
}
/**
* Find the best group using the best-fit-decreasing algorithm.
* The best group is the fullest group that has enough capacity for the new {@link WorkUnit}.
* If no existing group has enough capacity for the new {@link WorkUnit}, return null.
*/
private static MultiWorkUnit findAndPopBestFitGroup(WorkUnit workUnit, PriorityQueue<MultiWorkUnit> pQueue,
double avgGroupSize) {
List<MultiWorkUnit> fullWorkUnits = Lists.newArrayList();
MultiWorkUnit bestFit = null;
while (!pQueue.isEmpty()) {
MultiWorkUnit candidate = pQueue.poll();
if (getWorkUnitEstSize(candidate) + getWorkUnitEstSize(workUnit) <= avgGroupSize) {
bestFit = candidate;
break;
}
fullWorkUnits.add(candidate);
}
for (MultiWorkUnit fullWorkUnit : fullWorkUnits) {
pQueue.add(fullWorkUnit);
}
return bestFit;
}
}
| 42.441558 | 120 | 0.747705 |
e53801554aba2ec144495e61229e8e6fb2f4fff2 | 312 | package Eventos;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
public class DeathEvent implements Listener {
@EventHandler
public void morrer(PlayerDeathEvent e) {
e.setDeathMessage(null);
e.setDroppedExp(0);
}
}
| 20.8 | 49 | 0.753205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.