blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
1d35373d2c0209dcdf1333db5b5d4b390a94b439
Java
aws/aws-sdk-java
/aws-java-sdk-licensemanager/src/main/java/com/amazonaws/services/licensemanager/model/CreateLicenseConfigurationRequest.java
UTF-8
36,074
1.703125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.licensemanager.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseConfiguration" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateLicenseConfigurationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Name of the license configuration. * </p> */ private String name; /** * <p> * Description of the license configuration. * </p> */ private String description; /** * <p> * Dimension used to track the license inventory. * </p> */ private String licenseCountingType; /** * <p> * Number of licenses managed by the license configuration. * </p> */ private Long licenseCount; /** * <p> * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of new * instances. * </p> */ private Boolean licenseCountHardLimit; /** * <p> * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available rules * vary by dimension, as follows. * </p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | <code>maximumVcpus</code> * | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * </p> */ private java.util.List<String> licenseRules; /** * <p> * Tags to add to the license configuration. * </p> */ private java.util.List<Tag> tags; /** * <p> * When true, disassociates a resource when software is uninstalled. * </p> */ private Boolean disassociateWhenNotFound; /** * <p> * Product information. * </p> */ private java.util.List<ProductInformation> productInformationList; /** * <p> * Name of the license configuration. * </p> * * @param name * Name of the license configuration. */ public void setName(String name) { this.name = name; } /** * <p> * Name of the license configuration. * </p> * * @return Name of the license configuration. */ public String getName() { return this.name; } /** * <p> * Name of the license configuration. * </p> * * @param name * Name of the license configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withName(String name) { setName(name); return this; } /** * <p> * Description of the license configuration. * </p> * * @param description * Description of the license configuration. */ public void setDescription(String description) { this.description = description; } /** * <p> * Description of the license configuration. * </p> * * @return Description of the license configuration. */ public String getDescription() { return this.description; } /** * <p> * Description of the license configuration. * </p> * * @param description * Description of the license configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * Dimension used to track the license inventory. * </p> * * @param licenseCountingType * Dimension used to track the license inventory. * @see LicenseCountingType */ public void setLicenseCountingType(String licenseCountingType) { this.licenseCountingType = licenseCountingType; } /** * <p> * Dimension used to track the license inventory. * </p> * * @return Dimension used to track the license inventory. * @see LicenseCountingType */ public String getLicenseCountingType() { return this.licenseCountingType; } /** * <p> * Dimension used to track the license inventory. * </p> * * @param licenseCountingType * Dimension used to track the license inventory. * @return Returns a reference to this object so that method calls can be chained together. * @see LicenseCountingType */ public CreateLicenseConfigurationRequest withLicenseCountingType(String licenseCountingType) { setLicenseCountingType(licenseCountingType); return this; } /** * <p> * Dimension used to track the license inventory. * </p> * * @param licenseCountingType * Dimension used to track the license inventory. * @return Returns a reference to this object so that method calls can be chained together. * @see LicenseCountingType */ public CreateLicenseConfigurationRequest withLicenseCountingType(LicenseCountingType licenseCountingType) { this.licenseCountingType = licenseCountingType.toString(); return this; } /** * <p> * Number of licenses managed by the license configuration. * </p> * * @param licenseCount * Number of licenses managed by the license configuration. */ public void setLicenseCount(Long licenseCount) { this.licenseCount = licenseCount; } /** * <p> * Number of licenses managed by the license configuration. * </p> * * @return Number of licenses managed by the license configuration. */ public Long getLicenseCount() { return this.licenseCount; } /** * <p> * Number of licenses managed by the license configuration. * </p> * * @param licenseCount * Number of licenses managed by the license configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withLicenseCount(Long licenseCount) { setLicenseCount(licenseCount); return this; } /** * <p> * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of new * instances. * </p> * * @param licenseCountHardLimit * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of * new instances. */ public void setLicenseCountHardLimit(Boolean licenseCountHardLimit) { this.licenseCountHardLimit = licenseCountHardLimit; } /** * <p> * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of new * instances. * </p> * * @return Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of * new instances. */ public Boolean getLicenseCountHardLimit() { return this.licenseCountHardLimit; } /** * <p> * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of new * instances. * </p> * * @param licenseCountHardLimit * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of * new instances. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withLicenseCountHardLimit(Boolean licenseCountHardLimit) { setLicenseCountHardLimit(licenseCountHardLimit); return this; } /** * <p> * Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of new * instances. * </p> * * @return Indicates whether hard or soft license enforcement is used. Exceeding a hard limit blocks the launch of * new instances. */ public Boolean isLicenseCountHardLimit() { return this.licenseCountHardLimit; } /** * <p> * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available rules * vary by dimension, as follows. * </p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | <code>maximumVcpus</code> * | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * </p> * * @return License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available * rules vary by dimension, as follows.</p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values * for <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. */ public java.util.List<String> getLicenseRules() { return licenseRules; } /** * <p> * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available rules * vary by dimension, as follows. * </p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | <code>maximumVcpus</code> * | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * </p> * * @param licenseRules * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available * rules vary by dimension, as follows.</p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. */ public void setLicenseRules(java.util.Collection<String> licenseRules) { if (licenseRules == null) { this.licenseRules = null; return; } this.licenseRules = new java.util.ArrayList<String>(licenseRules); } /** * <p> * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available rules * vary by dimension, as follows. * </p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | <code>maximumVcpus</code> * | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setLicenseRules(java.util.Collection)} or {@link #withLicenseRules(java.util.Collection)} if you want to * override the existing values. * </p> * * @param licenseRules * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available * rules vary by dimension, as follows.</p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withLicenseRules(String... licenseRules) { if (this.licenseRules == null) { setLicenseRules(new java.util.ArrayList<String>(licenseRules.length)); } for (String ele : licenseRules) { this.licenseRules.add(ele); } return this; } /** * <p> * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available rules * vary by dimension, as follows. * </p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | <code>maximumVcpus</code> * | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * </p> * * @param licenseRules * License rules. The syntax is #name=value (for example, #allowedTenancy=EC2-DedicatedHost). The available * rules vary by dimension, as follows.</p> * <ul> * <li> * <p> * <code>Cores</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumCores</code> | <code>minimumCores</code> * </p> * </li> * <li> * <p> * <code>Instances</code> dimension: <code>allowedTenancy</code> | <code>maximumCores</code> | * <code>minimumCores</code> | <code>maximumSockets</code> | <code>minimumSockets</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * <li> * <p> * <code>Sockets</code> dimension: <code>allowedTenancy</code> | <code>licenseAffinityToHost</code> | * <code>maximumSockets</code> | <code>minimumSockets</code> * </p> * </li> * <li> * <p> * <code>vCPUs</code> dimension: <code>allowedTenancy</code> | <code>honorVcpuOptimization</code> | * <code>maximumVcpus</code> | <code>minimumVcpus</code> * </p> * </li> * </ul> * <p> * The unit for <code>licenseAffinityToHost</code> is days and the range is 1 to 180. The possible values for * <code>allowedTenancy</code> are <code>EC2-Default</code>, <code>EC2-DedicatedHost</code>, and * <code>EC2-DedicatedInstance</code>. The possible values for <code>honorVcpuOptimization</code> are * <code>True</code> and <code>False</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withLicenseRules(java.util.Collection<String> licenseRules) { setLicenseRules(licenseRules); return this; } /** * <p> * Tags to add to the license configuration. * </p> * * @return Tags to add to the license configuration. */ public java.util.List<Tag> getTags() { return tags; } /** * <p> * Tags to add to the license configuration. * </p> * * @param tags * Tags to add to the license configuration. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new java.util.ArrayList<Tag>(tags); } /** * <p> * Tags to add to the license configuration. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * Tags to add to the license configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withTags(Tag... tags) { if (this.tags == null) { setTags(new java.util.ArrayList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * Tags to add to the license configuration. * </p> * * @param tags * Tags to add to the license configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * <p> * When true, disassociates a resource when software is uninstalled. * </p> * * @param disassociateWhenNotFound * When true, disassociates a resource when software is uninstalled. */ public void setDisassociateWhenNotFound(Boolean disassociateWhenNotFound) { this.disassociateWhenNotFound = disassociateWhenNotFound; } /** * <p> * When true, disassociates a resource when software is uninstalled. * </p> * * @return When true, disassociates a resource when software is uninstalled. */ public Boolean getDisassociateWhenNotFound() { return this.disassociateWhenNotFound; } /** * <p> * When true, disassociates a resource when software is uninstalled. * </p> * * @param disassociateWhenNotFound * When true, disassociates a resource when software is uninstalled. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withDisassociateWhenNotFound(Boolean disassociateWhenNotFound) { setDisassociateWhenNotFound(disassociateWhenNotFound); return this; } /** * <p> * When true, disassociates a resource when software is uninstalled. * </p> * * @return When true, disassociates a resource when software is uninstalled. */ public Boolean isDisassociateWhenNotFound() { return this.disassociateWhenNotFound; } /** * <p> * Product information. * </p> * * @return Product information. */ public java.util.List<ProductInformation> getProductInformationList() { return productInformationList; } /** * <p> * Product information. * </p> * * @param productInformationList * Product information. */ public void setProductInformationList(java.util.Collection<ProductInformation> productInformationList) { if (productInformationList == null) { this.productInformationList = null; return; } this.productInformationList = new java.util.ArrayList<ProductInformation>(productInformationList); } /** * <p> * Product information. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setProductInformationList(java.util.Collection)} or * {@link #withProductInformationList(java.util.Collection)} if you want to override the existing values. * </p> * * @param productInformationList * Product information. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withProductInformationList(ProductInformation... productInformationList) { if (this.productInformationList == null) { setProductInformationList(new java.util.ArrayList<ProductInformation>(productInformationList.length)); } for (ProductInformation ele : productInformationList) { this.productInformationList.add(ele); } return this; } /** * <p> * Product information. * </p> * * @param productInformationList * Product information. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateLicenseConfigurationRequest withProductInformationList(java.util.Collection<ProductInformation> productInformationList) { setProductInformationList(productInformationList); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getLicenseCountingType() != null) sb.append("LicenseCountingType: ").append(getLicenseCountingType()).append(","); if (getLicenseCount() != null) sb.append("LicenseCount: ").append(getLicenseCount()).append(","); if (getLicenseCountHardLimit() != null) sb.append("LicenseCountHardLimit: ").append(getLicenseCountHardLimit()).append(","); if (getLicenseRules() != null) sb.append("LicenseRules: ").append(getLicenseRules()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()).append(","); if (getDisassociateWhenNotFound() != null) sb.append("DisassociateWhenNotFound: ").append(getDisassociateWhenNotFound()).append(","); if (getProductInformationList() != null) sb.append("ProductInformationList: ").append(getProductInformationList()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateLicenseConfigurationRequest == false) return false; CreateLicenseConfigurationRequest other = (CreateLicenseConfigurationRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getLicenseCountingType() == null ^ this.getLicenseCountingType() == null) return false; if (other.getLicenseCountingType() != null && other.getLicenseCountingType().equals(this.getLicenseCountingType()) == false) return false; if (other.getLicenseCount() == null ^ this.getLicenseCount() == null) return false; if (other.getLicenseCount() != null && other.getLicenseCount().equals(this.getLicenseCount()) == false) return false; if (other.getLicenseCountHardLimit() == null ^ this.getLicenseCountHardLimit() == null) return false; if (other.getLicenseCountHardLimit() != null && other.getLicenseCountHardLimit().equals(this.getLicenseCountHardLimit()) == false) return false; if (other.getLicenseRules() == null ^ this.getLicenseRules() == null) return false; if (other.getLicenseRules() != null && other.getLicenseRules().equals(this.getLicenseRules()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; if (other.getDisassociateWhenNotFound() == null ^ this.getDisassociateWhenNotFound() == null) return false; if (other.getDisassociateWhenNotFound() != null && other.getDisassociateWhenNotFound().equals(this.getDisassociateWhenNotFound()) == false) return false; if (other.getProductInformationList() == null ^ this.getProductInformationList() == null) return false; if (other.getProductInformationList() != null && other.getProductInformationList().equals(this.getProductInformationList()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getLicenseCountingType() == null) ? 0 : getLicenseCountingType().hashCode()); hashCode = prime * hashCode + ((getLicenseCount() == null) ? 0 : getLicenseCount().hashCode()); hashCode = prime * hashCode + ((getLicenseCountHardLimit() == null) ? 0 : getLicenseCountHardLimit().hashCode()); hashCode = prime * hashCode + ((getLicenseRules() == null) ? 0 : getLicenseRules().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); hashCode = prime * hashCode + ((getDisassociateWhenNotFound() == null) ? 0 : getDisassociateWhenNotFound().hashCode()); hashCode = prime * hashCode + ((getProductInformationList() == null) ? 0 : getProductInformationList().hashCode()); return hashCode; } @Override public CreateLicenseConfigurationRequest clone() { return (CreateLicenseConfigurationRequest) super.clone(); } }
true
ce8a3077fba1a44ba61c70b409585edf62ec8b1f
Java
stelian-mihalceanu/LordOfJava
/Warg.java
UTF-8
654
3.046875
3
[]
no_license
public class Warg extends Creature implements IBite { private double bitePower; public Warg(double stamina, double speed, int agility, String nickname, long score, double bitePower) { super(stamina, speed, agility, nickname, score); this.bitePower = bitePower; } @Override public void powerUp(double stamina, double speed, int agility) { super.powerUp(stamina / 2, speed * 4, agility); } @Override public double getBitePower() { return this.bitePower; } @Override public String toString() { return super.toString() + "\nBite Power: " + this.bitePower; } }
true
38a838e815c17be0fca414b327e4590dc07fe216
Java
ZUP779/InformationSystemTraining1110
/src/main/java/com/example/esdemo/config/Swagger2Config.java
UTF-8
1,782
2.15625
2
[]
no_license
package com.example.esdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import javax.swing.text.Document; /** * Author: ZUP779 * Date: 2020/4/27 21:05 * Description: */ @EnableSwagger2 @Configuration public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2 .apiInfo(apiInfo()) // 用于定义api文档汇总信息 .select() .apis(RequestHandlerSelectors .basePackage("com.example.esdemo")) // 指定controller包 .paths(PathSelectors.any()) // 所有controller .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("esdemo api") // 文档页标题 .contact(new Contact("zup779", "https://www.bonjour.com", "abc@bupt.edu.cn")) // 联系人信息 .description("esdemo restful api文档") // 详细信息 .version("1.0.0") // 文档版本号 .termsOfServiceUrl("https://www.bonjour.com") // 网站地址 .build(); } }
true
69024261af9f9f322ca72d41d09e2c6bdacad24a
Java
sol-work/RepoGarage
/src/main/java/com/qa/controllers/TruckController.java
UTF-8
788
2.234375
2
[]
no_license
package com.qa.controllers; import java.util.List; import com.qa.dao.TruckDAO; import com.qa.utils.UserInput; import com.qa.vehicles.Car; import com.qa.vehicles.Truck; public class TruckController implements GarageController<Truck> { private TruckDAO truckDAO; private UserInput input = UserInput.getInstance(); public TruckController(TruckDAO truckDAO) { super(); this.truckDAO = truckDAO; } @Override public Truck create() { // TODO Auto-generated method stub return null; } @Override public boolean delete() { // TODO Auto-generated method stub return false; } @Override public List<Truck> readAll() { // TODO Auto-generated method stub return null; } @Override public Truck update() { // TODO Auto-generated method stub return null; } }
true
eded553d10ddd22915002716468a28e37e237c32
Java
navi07/FEM
/src/Model/Matrix_H.java
UTF-8
8,452
2.375
2
[]
no_license
package Model; import Resources.InitialData; import Resources.PrintMatrix; import static Resources.CleanMatrix.clean_Matrix; import static java.lang.Math.sqrt; public class Matrix_H { public double[][] Hsum = new double[4][4]; public double[][] HBC = new double[4][4]; public VectorP vectorPLocal; public Matrix_H(Jacobian jacobian, Element element, InitialData data) { double conductivity = data.getConductivity(); double alfa = data.getAlfa(); for (int i = 0; i < 4; i++) { /** ->dN/dx i dN/dy */ double[] dNdy = new double[4]; double[] dNdx = new double[4]; for (int j = 0; j < 4; j++) { dNdx[j] = jacobian.getJ_inv()[0][0] * jacobian.getUvEl().getdN_dksi()[i][j] + jacobian.getJ_inv()[0][1] * jacobian.getUvEl().getdN_dEta()[i][j]; dNdy[j] = jacobian.getJ_inv()[1][0] * jacobian.getUvEl().getdN_dksi()[i][j] + jacobian.getJ_inv()[1][1] * jacobian.getUvEl().getdN_dEta()[i][j]; } /** ->Macierze Hx, Hy i H */ double[][] h = new double[4][4]; for (int k = 0; k < 4; k++) { for (int j = 0; j < 4; j++) { double[][] hx = new double[4][4]; hx[k][j] = (dNdx[j] * dNdx[k]); double[][] hy = new double[4][4]; hy[k][j] = (dNdy[j] * dNdy[k]); h[k][j] = (hx[k][j] + hy[k][j]); } } /** ->Macierz H = "K*({dN/dx}{dN/dx}T + {dN/dy}{dN/dy}T)*DetJ * H = K(conductivity) * H[k][j] * detJ */ double[][] HLocal = new double[4][4]; for (int k = 0; k < 4; k++) { for (int j = 0; j < 4; j++) { HLocal[k][j] = (conductivity * h[k][j] * jacobian.getDetJ()); } } /** ->Macierz HSum[k][j] += HLocal[k][j] */ for (int k = 0; k < 4; k++) { for (int j = 0; j < 4; j++) { Hsum[k][j] += HLocal[k][j]; } } } /** ->Macierz H_BC(z warunkami brzegowymi) */ final double[] ksi = new double[]{((-1) / sqrt(3)), ((1) / sqrt(3)), 1, 1, ((1) / sqrt(3)), ((-1) / sqrt(3)), -1, -1}; final double[] eta = new double[]{-1, -1, ((-1) / sqrt(3)), ((1) / sqrt(3)), 1, 1, ((1) / sqrt(3)), ((-1) / sqrt(3)),}; double[] lengthOfSide = new double[4]; double[] detJ = new double[4]; double[][] shapeFunctionPow1 = new double[2][4]; double[][] shapeFunctionPow2 = new double[2][4]; double[][] shapeFunctionPow3 = new double[2][4]; double[][] shapeFunctionPow4 = new double[2][4]; double[][] pc1pow1 = new double[4][4]; double[][] pc2pow1 = new double[4][4]; double[][] pc1pow2 = new double[4][4]; double[][] pc2pow2 = new double[4][4]; double[][] pc1pow3 = new double[4][4]; double[][] pc2pow3 = new double[4][4]; double[][] pc1pow4 = new double[4][4]; double[][] pc2pow4 = new double[4][4]; double[][] sum1 = new double[4][4]; double[][] sum2 = new double[4][4]; double[][] sum3 = new double[4][4]; double[][] sum4 = new double[4][4]; clean_Matrix(HBC); clean_Matrix(shapeFunctionPow1); clean_Matrix(shapeFunctionPow2); clean_Matrix(shapeFunctionPow3); clean_Matrix(shapeFunctionPow4); for (int i = 0; i < 4; i++) { if (i == 3) { lengthOfSide[i] = sqrt(Math.pow(element.getNodes()[3].getX() - element.getNodes()[0].getX(), 2) + Math.pow(element.getNodes()[3].getY() - element.getNodes()[0].getY(), 2)); } else { lengthOfSide[i] = sqrt(Math.pow(element.getNodes()[i + 1].getX() - element.getNodes()[i].getX(), 2) + Math.pow(element.getNodes()[i + 1].getY() - element.getNodes()[i].getY(), 2)); } detJ[i] = lengthOfSide[i] / 2; } for (int i = 0; i < 2; i++) { shapeFunctionPow1[i][0] = (1.0 / 4.0) * (1 - ksi[i]) * (1 - eta[i]); shapeFunctionPow1[i][1] = (1.0 / 4.0) * (1 + ksi[i]) * (1 - eta[i]); shapeFunctionPow1[i][2] = (1.0 / 4.0) * (1 + ksi[i]) * (1 + eta[i]); shapeFunctionPow1[i][3] = (1.0 / 4.0) * (1 - ksi[i]) * (1 + eta[i]); shapeFunctionPow2[i][0] = (1.0 / 4.0) * (1 - ksi[i + 2]) * (1 - eta[i + 2]); shapeFunctionPow2[i][1] = (1.0 / 4.0) * (1 + ksi[i + 2]) * (1 - eta[i + 2]); shapeFunctionPow2[i][2] = (1.0 / 4.0) * (1 + ksi[i + 2]) * (1 + eta[i + 2]); shapeFunctionPow2[i][3] = (1.0 / 4.0) * (1 - ksi[i + 2]) * (1 + eta[i + 2]); shapeFunctionPow3[i][0] = (1.0 / 4.0) * (1 - ksi[i + 4]) * (1 - eta[i + 4]); shapeFunctionPow3[i][1] = (1.0 / 4.0) * (1 + ksi[i + 4]) * (1 - eta[i + 4]); shapeFunctionPow3[i][2] = (1.0 / 4.0) * (1 + ksi[i + 4]) * (1 + eta[i + 4]); shapeFunctionPow3[i][3] = (1.0 / 4.0) * (1 - ksi[i + 4]) * (1 + eta[i + 4]); shapeFunctionPow4[i][0] = (1.0 / 4.0) * (1 - ksi[i + 6]) * (1 - eta[i + 6]); shapeFunctionPow4[i][1] = (1.0 / 4.0) * (1 + ksi[i + 6]) * (1 - eta[i + 6]); shapeFunctionPow4[i][2] = (1.0 / 4.0) * (1 + ksi[i + 6]) * (1 + eta[i + 6]); shapeFunctionPow4[i][3] = (1.0 / 4.0) * (1 - ksi[i + 6]) * (1 + eta[i + 6]); } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { pc1pow1[i][j] = shapeFunctionPow1[0][i] * shapeFunctionPow1[0][j] * alfa; pc2pow1[i][j] = shapeFunctionPow1[1][i] * shapeFunctionPow1[1][j] * alfa; pc1pow2[i][j] = shapeFunctionPow2[0][i] * shapeFunctionPow2[0][j] * alfa; pc2pow2[i][j] = shapeFunctionPow2[1][i] * shapeFunctionPow2[1][j] * alfa; pc1pow3[i][j] = shapeFunctionPow3[0][i] * shapeFunctionPow3[0][j] * alfa; pc2pow3[i][j] = shapeFunctionPow3[1][i] * shapeFunctionPow3[1][j] * alfa; pc1pow4[i][j] = shapeFunctionPow4[0][i] * shapeFunctionPow4[0][j] * alfa; pc2pow4[i][j] = shapeFunctionPow4[1][i] * shapeFunctionPow4[1][j] * alfa; sum1[i][j] = detJ[0] * (pc1pow1[i][j] + pc2pow1[i][j]); sum2[i][j] = detJ[1] * (pc1pow2[i][j] + pc2pow2[i][j]); sum3[i][j] = detJ[2] * (pc1pow3[i][j] + pc2pow3[i][j]); sum4[i][j] = detJ[3] * (pc1pow4[i][j] + pc2pow4[i][j]); } } /** ->Wektor P(po wyliczeniu potrzebnych danych) */ vectorPLocal = new VectorP(data, shapeFunctionPow1, shapeFunctionPow2, shapeFunctionPow3, shapeFunctionPow4, detJ); if (element.getNodes()[0].isBoundaryCondition() && element.getNodes()[1].isBoundaryCondition()) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { HBC[i][j] += sum1[i][j]; } } vectorPLocal.addToP(1); } if (element.getNodes()[1].isBoundaryCondition() && element.getNodes()[2].isBoundaryCondition()) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { HBC[i][j] += sum2[i][j]; } } vectorPLocal.addToP(2); } if (element.getNodes()[2].isBoundaryCondition() && element.getNodes()[3].isBoundaryCondition()) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { HBC[i][j] += sum3[i][j]; } } vectorPLocal.addToP(3); } if (element.getNodes()[3].isBoundaryCondition() && element.getNodes()[0].isBoundaryCondition()) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { HBC[i][j] += sum4[i][j]; } } vectorPLocal.addToP(4); } vectorPLocal.calculateP(); //showMatrix(); } public void showMatrix() { System.out.println("\nMacierz HSum lokalna : "); PrintMatrix.print_Matrix(Hsum); System.out.println("\nMacierz H_BC(warunki brzegowe) lokalna : "); PrintMatrix.print_Matrix(HBC); vectorPLocal.showVectorP(); } }
true
eceba020797855b812d31594fec7d0aa2625219b
Java
Robin-Hoodie/io.oreon.video.rental.store
/src/main/java/io/oreon/casumo/video/rental/store/startup/FilmInitializer.java
UTF-8
2,863
2.390625
2
[]
no_license
package io.oreon.casumo.video.rental.store.startup; import io.oreon.casumo.video.rental.store.constants.SpringProfiles; import io.oreon.casumo.video.rental.store.dao.CustomerRepository; import io.oreon.casumo.video.rental.store.dao.FilmRepository; import io.oreon.casumo.video.rental.store.model.Customer; import io.oreon.casumo.video.rental.store.model.Film; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Profile; import javax.inject.Inject; import javax.inject.Named; import static io.oreon.casumo.video.rental.store.constants.SpringProfiles.DEV; import static io.oreon.casumo.video.rental.store.model.Customer.Builder.aCustomer; import static io.oreon.casumo.video.rental.store.model.Film.Builder.aFilm; import static io.oreon.casumo.video.rental.store.model.FilmType.OLD; import static io.oreon.casumo.video.rental.store.model.FilmType.PREMIUM; import static io.oreon.casumo.video.rental.store.model.FilmType.REGULAR; import static java.util.Arrays.asList; @Named @Profile(DEV) //Only run this on DEV environment public class FilmInitializer implements CommandLineRunner { private FilmRepository filmRepository; private CustomerRepository customerRepository; public FilmInitializer(FilmRepository filmRepository, CustomerRepository customerRepository) { this.filmRepository = filmRepository; this.customerRepository = customerRepository; } @Override public void run(String... args) { this.filmRepository.deleteAll(); //Make sure DB is in clean state Film lotr = aFilm().withName("The Lord of the Rings: The Return of the King").withType(PREMIUM).build(); Film starWars = aFilm().withName("Star Wars Episode IV: A New Hope").withType(PREMIUM).build(); Film fightClub = aFilm().withName("Fight Club").withType(PREMIUM).build(); Film topGun = aFilm().withName("Top Gun").build(); Film southPark = aFilm().withName("South Park: The Movie").build(); Film forrestGump = aFilm().withName("Forrest Gump").build(); Film exorcist = aFilm().withName("The Exorcist").withType(OLD).build(); Film spaceOdyssey = aFilm().withName("2001: A Space Odyssey").withType(OLD).build(); Film fullmetalJacket = aFilm().withName("Full Metal Jacket").withType(OLD).build(); Film montyPython = aFilm().withName("Monty Python and the Holy Grail").withType(OLD).build(); this.filmRepository.saveAll(asList(lotr, starWars, fightClub, topGun, southPark, forrestGump, exorcist, spaceOdyssey, fullmetalJacket, montyPython)); Customer gandalf = aCustomer().withName("Gandalf Greybeard").build(); Customer sam = aCustomer().withName("Samwise Gamgee").build(); Customer bilbo = aCustomer().withName("Bilbo Baggins").build(); this.customerRepository.saveAll(asList(gandalf, sam, bilbo)); } }
true
fcc1a0efdba7e72edc908c05185c8b802dc87f48
Java
tomasz-ludek/dashcontrol-android
/app/src/main/java/com/dash/dashapp/models/WalletBalance.java
UTF-8
2,089
1.953125
2
[]
no_license
package com.dash.dashapp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by Dexter Barretto on 18/2/18. * Github : @dbarretto */ public class WalletBalance { @SerializedName("address") @Expose private String address; @SerializedName("txid") @Expose private String transactionId; @SerializedName("vout") @Expose private Integer vout; @SerializedName("scriptPubKey") @Expose private String scriptPubKey; @SerializedName("amount") @Expose private Double amount; @SerializedName("satoshis") @Expose private Integer satoshis; @SerializedName("height") @Expose private Integer height; @SerializedName("confirmations") @Expose private Integer confirmations; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Integer getVout() { return vout; } public void setVout(Integer vout) { this.vout = vout; } public String getScriptPubKey() { return scriptPubKey; } public void setScriptPubKey(String scriptPubKey) { this.scriptPubKey = scriptPubKey; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public Integer getSatoshis() { return satoshis; } public void setSatoshis(Integer satoshis) { this.satoshis = satoshis; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public Integer getConfirmations() { return confirmations; } public void setConfirmations(Integer confirmations) { this.confirmations = confirmations; } }
true
bcfb929008e7911fb1ab7880c6abc16d9ca1eea7
Java
spincast/spincast-framework
/spincast-plugins/spincast-plugins-attempts-limiter-parent/spincast-plugins-attempts-limiter/src/main/java/org/spincast/plugins/attemptslimiter/config/SpincastAttemptsLimiterPluginConfig.java
UTF-8
1,754
2.453125
2
[ "Apache-2.0" ]
permissive
package org.spincast.plugins.attemptslimiter.config; import org.spincast.core.config.SpincastConfig; import org.spincast.plugins.attemptslimiter.Attempt; import org.spincast.plugins.attemptslimiter.AttemptsAutoIncrementType; import org.spincast.plugins.attemptslimiter.AttemptsManager; /** * Configurations for the Spincast Attempts Limiter plugin. */ public interface SpincastAttemptsLimiterPluginConfig { /** * Is attempts validation enabled? * <p> * You can set this to <code>true</code> when developing * locally. * <p> * Defaults to the negation of {@link SpincastConfig#isDevelopmentMode()}. */ public boolean isValidationEnabled(); /** * Should the scheduled task to delete old attempts in the database * be automatically added? */ public boolean isAutoBindDeleteOldAttemptsScheduledTask(); /** * The number of minutes between two launches of * the scheduled task that will clean the database from old * attempts, if {@link #isAutoBindDeleteOldAttemptsScheduledTask()} * is enabled. */ public int getDeleteOldAttemptsScheduledTaskIntervalMinutes(); /** * Should the {@link AttemptsManager#attempt(String, org.spincast.plugins.attemptslimiter.AttemptCriteria...)} * method automatically increment the number of attempts <em>by default</em>, * when not specified otherwise? * <p> * If you don't let the method increment the number of attempts, * you are responsible to call {@link Attempt#incrementAttemptsCount()} * by yourself, when required. * <p> * Defaults to {@link AttemptsAutoIncrementType#ALWAYS}. */ public AttemptsAutoIncrementType getDefaultAttemptAutoIncrementType(); }
true
73520f6adcc664097d7d79fcc5b569d8a9637fdd
Java
alandrieu/geektic2014
/src/main/java/com/ninja_squad/geektic/geek/TypeSexe.java
UTF-8
77
1.640625
2
[]
no_license
package com.ninja_squad.geektic.geek; public enum TypeSexe { homme, femme }
true
1b31490af4a58742ca8301b09202905da6895f62
Java
tshep159/webstore
/src/main/java/com/mrd/controller/PaymentsController.java
UTF-8
1,134
1.851563
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mrd.controller; import com.mrd.entity.Address; import com.mrd.entity.Payments; import com.mrd.service.AddressService; import com.mrd.service.PaymentService; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author User */ @RestController public class PaymentsController { @Autowired PaymentService paymentService; @Autowired AddressService addressService; List <Payments> availPayments= new ArrayList<>(); @GetMapping("/all/payments") public List <Payments> allPayments(){ return paymentService.listPayments(); } }
true
4ffbdc176a112fe3cabdbd740339d4b064558048
Java
bananagg/NLKM
/src/main/java/com/wake/nlkm/controller/GuwenController.java
UTF-8
6,315
2.203125
2
[]
no_license
package com.wake.nlkm.controller; import com.alibaba.fastjson.JSONObject; import com.wake.nlkm.entity.Guwen; import com.wake.nlkm.entity.IdBean; import com.wake.nlkm.entity.Idiom; import com.wake.nlkm.error.FailException; import com.wake.nlkm.error.RequestParamIsEmptyException; import com.wake.nlkm.service.GuwenService; import com.wake.nlkm.service.IdiomService; import com.wake.nlkm.utils.RespBean; import com.wake.nlkm.utils.RespPageBean; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController @ResponseBody @RequestMapping("/api/v1/guwen") @Slf4j @Api(value = "古文管理Api文档", tags = "古文操作接口") public class GuwenController { private Logger logger = LoggerFactory.getLogger(getClass()); @Resource GuwenService guwenService; @RequestMapping(value = "/get/list", method = RequestMethod.GET) @ApiOperation(value = "分页查询", notes = "分页查询古文") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "title", value = "诗词标题", dataType = "String"), @ApiImplicitParam(paramType = "query", name = "page", value = "页数(默认1)", dataType = "int"), @ApiImplicitParam(paramType = "query", name = "size", value = "查询长度(默认20)", dataType = "int") }) public RespBean getGuwenList(@RequestParam(defaultValue = "") String title, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer size) throws Exception { // List<Word> wordList = wordService.queryWordByBatch(page,size); logger.info("getGuwenList title = " + title+ " page = " + page + " size = " + size); RespPageBean respPageBean = guwenService.queryGuwenByBatch(title, page, size); RespBean respBean = RespBean.ok("sucess", respPageBean); return respBean; } @RequestMapping(value = "/get/info", method = RequestMethod.GET) @ApiOperation(value = "指定查询", notes = "根据id查询") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "id", value = "古文id", required = false, dataType = "Integer"), }) public RespBean queryInfoById(@RequestParam(required = false) Integer id) throws Exception { logger.info("queryInfoById guwen id = " + id); if (id == null) { throw new RequestParamIsEmptyException(); } Guwen guwen = guwenService.queryGuwenById(id); RespBean respBean = RespBean.ok(guwen); return respBean; } @RequestMapping(value = "/get/info/bytitle", method = RequestMethod.GET) @ApiOperation(value = "模糊查询", notes = "根据输入模糊查询") public RespBean queryInfoByTitle(@RequestParam String title) throws Exception { logger.info("queryInfoById guwen title = " + title); if (title == null || title.equals("")) { throw new RequestParamIsEmptyException(); } RespPageBean idiomRes = guwenService.queryGuwenInfoByTitle(title); RespBean respBean = RespBean.ok(idiomRes); return respBean; } @RequestMapping(value = "/add", method = RequestMethod.POST) @ApiOperation(value = "新增", notes = "新增") public RespBean add(@RequestBody Guwen guwenInfo) throws Exception { logger.info("add guwen = " + JSONObject.toJSONString(guwenInfo)); int res = guwenService.addGuwenInfo(guwenInfo); RespBean respBean; if (res == 0) { throw new FailException(); } else { IdBean idBean = new IdBean(res); respBean = RespBean.ok(idBean); } return respBean; } @RequestMapping(value = "/del/word", method = RequestMethod.DELETE) @ApiOperation(value = "删除", notes = "根据id 删除") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "id", value = "id", required = true, dataType = "Integer") }) public RespBean delword(@RequestParam(required = false) Integer id) throws Exception { logger.info("id = " + id); if (id == null || id == 0) { throw new RequestParamIsEmptyException("缺少必要参数"); } int res = guwenService.deleteGuwen(id); RespBean respBean; if (res == 0) { throw new FailException(); } else { respBean = RespBean.ok(); } return respBean; } @RequestMapping(value = "/update/info", method = RequestMethod.POST) @ApiOperation(value = "更新", notes = "根据id 更新") public RespBean updateInfo(@RequestBody Guwen guwen) throws Exception { logger.info("updateInfo guwen = " + JSONObject.toJSONString(guwen)); int res = guwenService.updateGuwenInfo(guwen); RespBean respBean; if (res == 0) { throw new FailException(); } else { respBean = RespBean.ok(); } return respBean; } @RequestMapping(value = "/update/checkstate", method = RequestMethod.POST) @ApiOperation(value = "更新", notes = "更新审核状态") public RespBean updateCheckState(@RequestBody String text) throws Exception { logger.info("guwen updateCheckState text = " + text); JSONObject paramJson = JSONObject.parseObject(text); if (!paramJson.containsKey("id") || !paramJson.containsKey("state")) { throw new RequestParamIsEmptyException("缺少必要参数"); } Integer id = paramJson.getInteger("id"); Integer state = paramJson.getInteger("state"); if (id == null || state == null) { throw new RequestParamIsEmptyException("参数值为空"); } int res = guwenService.updateGuwenCheckState(id, state); RespBean respBean; if (res == 0) { throw new FailException(); } else { respBean = RespBean.ok(); } return respBean; } }
true
48a55bac9570815c689a546669c9a83d5792e3ab
Java
gyygit/searchH
/src/main/java/com/sinovatech/search/utils/RedisBusinessHelper.java
UTF-8
870
2.25
2
[]
no_license
package com.sinovatech.search.utils; import com.sinovatech.common.util.StringUtils; import com.sinovatech.search.entity.abstractdto.UserAbstractDTO; /*** * * @ClassName: RedisBusinessHelper * @Description: * @author Ma Tengfei * @date 2017年3月14日 下午2:20:30 * */ public class RedisBusinessHelper { private static JedisHelper jedisHelper = SpringContextHolder .getBean(JedisHelper.class); // 通过access_token得到登录的user信息 public static UserAbstractDTO getUserDto(String access_token){ String userDtojson=""; UserAbstractDTO twlmUser = null; if(org.springframework.util.StringUtils.hasLength(access_token)){ userDtojson = jedisHelper.get(access_token); if (StringUtils.isNotBlank(userDtojson)) { twlmUser = JsonUtil.getDTO(userDtojson, UserAbstractDTO.class); } } return twlmUser; } }
true
be4c5966a5daae77129dede7b69ede6657796fdd
Java
Rock3306/Stack-Queue
/stackAndqueue/src/main/java/com/common/TwoQueueForStack.java
UTF-8
1,444
4.21875
4
[]
no_license
package com.common; import java.util.ArrayDeque; import java.util.Queue; /** * 两个队列实现一个栈 * 思路:将 1、2、3 一次放入队列一,然后最上面的 3 留在队列一, * 将下面的 2、3 入队列二,把 3 出队列一,此时队列一空了,然后把队列二中的所有数据 * 入队列一;将最上面的 2 留在队列一,将下面的 3 入队列二。。一次循环 * @author rocki * */ public class TwoQueueForStack { Queue<Integer> queue1 = new ArrayDeque<Integer>(); Queue<Integer> queue2 = new ArrayDeque<Integer>(); // 方法:入栈操作 public void push(int data) { queue1.add(data); } // 方法:出栈操作 public int pop() throws Exception{ int data; if (queue1.size() == 0) { throw new Exception("栈为空"); } while (queue1.size() != 0) { if (queue1.size() == 1) { data = queue1.poll();// 取队列中第一位元素 while (queue2.size() != 0) { // 把queue2中的全部数据放到队列一中 queue1.add(queue2.poll()); } return data; } queue2.add(queue1.poll()); } throw new Exception("栈为空"); } public static void main(String[] args) throws Exception { TwoQueueForStack stack = new TwoQueueForStack(); stack.push(1); stack.push(2); stack.push(3); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); stack.push(4); } }
true
11a3aeb8e7621ba37c16cf9610491d8c5b661f97
Java
CiprianOlteanu23/pacaneaFX
/src/main/java/misc/ToolbarHandle.java
UTF-8
2,195
2.75
3
[]
no_license
package misc; import javafx.animation.PauseTransition; import javafx.scene.text.Text; import javafx.util.Duration; import misc.data.CashManager; import java.util.concurrent.atomic.AtomicInteger; public class ToolbarHandle { public void initialText(Text creditIndicator, Integer credit, Text betText, Text messageText) { creditIndicator.setText(Integer.toString(credit)); betText.setText(Integer.toString(1)); messageText.setText("SELECTEAZA MANA SI DA-I TALPA BOSS"); } public void minusCredit(Text credit, CashManager cashManager) { if(cashManager.getCurrentWin() != 0){ cashManager.giveMoney(); cashManager.setCurrentWin(0); } cashManager.takeMoney(); credit.setText(Integer.toString(cashManager.getCurrentMoney())); } public void plusBet(Text bet, CashManager cashManager){ int plusBet = cashManager.plusBet(); cashManager.setCurrentBet(plusBet); bet.setText(Integer.toString(plusBet)); } public void minusBet(Text bet, CashManager cashManager){ int minusBet = cashManager.minusBet(); cashManager.setCurrentBet(minusBet); bet.setText(Integer.toString(minusBet)); } // private void dropToDrop(Text credit, int current, int next) { // int doubledCurrent = current; // doubledCurrent++; // if (doubledCurrent != next) { // // credit.setText(Integer.toString(doubledCurrent)); // // PauseTransition pauseTransition = new PauseTransition(Duration.millis(100)); // pauseTransition.setOnFinished(actionEvent -> { // dropToDrop(credit, current, next); // }); // pauseTransition.play(); // } // // } // public void updateCredit(Text credit, CashManager cashManager) { // if (cashManager.getCurrentWin() != 0) { // Integer currentMoney = cashManager.getCurrentMoney(); // // cashManager.giveMoney(); // dropToDrop(credit, currentMoney, cashManager.getCurrentMoney()); // cashManager.setCurrentWin(0); // minusCredit(credit, cashManager); // } // } }
true
7af116de2a0367d8309718a2831c1375e93c777d
Java
Sofia-Kyba/apps20kyba-hw5
/src/main/java/ua/edu/ucu/stream/AsIntStream.java
UTF-8
3,960
3.078125
3
[]
no_license
package ua.edu.ucu.stream; import ua.edu.ucu.function.IntBinaryOperator; import ua.edu.ucu.function.IntConsumer; import ua.edu.ucu.function.IntPredicate; import ua.edu.ucu.function.IntToIntStreamFunction; import ua.edu.ucu.function.IntUnaryOperator; import java.util.Arrays; public class AsIntStream implements IntStream { private final int [] stream; private AsIntStream(int[] stream){ this.stream = Arrays.copyOf(stream, stream.length); } public static IntStream of(int... values) { return new AsIntStream(Arrays.copyOf(values, values.length)); } @Override public Double average() { if (isEmpty()) { throw new IllegalArgumentException(); } int sum = sum(); return (double) (sum/ (double) stream.length); } @Override public Integer max() { if (isEmpty()) { throw new IllegalArgumentException(); } int max = 0; for (int element: stream) { if (element > max) { max = element; } } return max; } @Override public Integer min() { if (isEmpty()) { throw new IllegalArgumentException(); } int min = stream[0]; for (int element: stream) { if (element < min) { min = element; } } return min; } @Override public long count() { int counter = 0; for (Integer element: stream) { if (element != null) { counter += 1; } } return counter; } @Override public Integer sum() { if (isEmpty()) { throw new IllegalArgumentException(); } int sum = 0; for (Integer element: stream) { sum += element; } return sum; } @Override public IntStream filter(IntPredicate predicate) { int [] values = new int[stream.length]; int ind = 0; for (int i = 0; i < stream.length; i++) { if (predicate.test(stream[i])) { values[ind] = stream[i]; ind += 1; } } int [] resultArray = Arrays.copyOf(values, ind); return of(resultArray); } @Override public void forEach(IntConsumer action) { for (Integer element: stream) { action.accept(element); } } @Override public IntStream map(IntUnaryOperator mapper) { int [] resultArray = new int[stream.length]; int index = 0; for (Integer element: stream) { resultArray[index] = mapper.apply(element); index += 1; } return of(resultArray); } @Override public IntStream flatMap(IntToIntStreamFunction func) { IntStream [] totalStream = new IntStream[stream.length]; int mappedSize = 0; int index = 0; for (Integer element: stream) { IntStream mappedStream = func.applyAsIntStream(element); totalStream[index] = mappedStream; mappedSize += mappedStream.count(); index += 1; } int [] resultArray = new int[mappedSize]; mappedSize = 0; for (IntStream mappedStream: totalStream) { System.arraycopy(mappedStream.toArray(), 0, resultArray, mappedSize, (int) mappedStream.count()); mappedSize += mappedStream.count(); } return of(resultArray); } @Override public int reduce(int identity, IntBinaryOperator op) { for (Integer element: stream) { identity = op.apply(identity, element); } return identity; } @Override public int[] toArray() { return Arrays.copyOf(stream, stream.length); } public boolean isEmpty() { return stream.length == 0; } }
true
19d6caac7f7d6eb8e53b993cb52cf45c2bba59e8
Java
herasimau/alexa-runner-pizza
/src/it/runnerpizza/alexa/models/PaymentRequest.java
UTF-8
507
1.992188
2
[]
no_license
package it.runnerpizza.alexa.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class PaymentRequest { private Boolean error; private String transactionId; public Boolean getError() { return error; } public void setError(Boolean error) { this.error = error; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } }
true
7ce3adf014d964d02350f89420ffb730cdfe0ba6
Java
thu512/SamsungSwTest
/src/D3_2806/Solution.java
UTF-8
936
3
3
[]
no_license
package D3_2806; import java.util.ArrayList; import java.util.Scanner; class Solution { static int Answer; static int n; static int[] col; static int result=0; public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int test_case = 0; test_case < T; test_case++) { n = sc.nextInt(); col=new int[n+1]; col[0]=0; queen(0); System.out.println("#"+(test_case+1)+" "+result); result=0; } } public static void queen(int i) { if(promising(i)) { if(i==n) { result++; }else { for(int j=1; j<=n; j++) { col[i+1]=j; queen(i+1); } } } } public static boolean promising(int i) { boolean s = true; int k = 1; while(k<i && s) { if(col[i]==col[k] || (Math.abs(col[i]-col[k]) == i-k)) { s=false; } k++; } return s; } }
true
3ee457404e86ee116527face629b1a4de3713617
Java
4shael/XChange
/xchange-yobit/src/main/java/org/knowm/xchange/yobit/service/YoBitTradeService.java
UTF-8
10,067
1.8125
2
[ "MIT" ]
permissive
package org.knowm.xchange.yobit.service; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; import org.knowm.xchange.service.trade.params.CancelOrderParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit; import org.knowm.xchange.service.trade.params.TradeHistoryParamOffset; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsIdSpan; import org.knowm.xchange.service.trade.params.TradeHistoryParamsSorted; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; import org.knowm.xchange.utils.DateUtils; import org.knowm.xchange.yobit.YoBit; import org.knowm.xchange.yobit.YoBitAdapters; import org.knowm.xchange.yobit.YoBitExchange; import org.knowm.xchange.yobit.dto.BaseYoBitResponse; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; public class YoBitTradeService extends YoBitBaseService<YoBit> implements TradeService { public YoBitTradeService(YoBitExchange exchange) { super(YoBit.class, exchange); } @Override public OpenOrders getOpenOrders() throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotYetImplementedForExchangeException("Need to specify OpenOrdersParams"); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { if (params instanceof OpenOrdersParamCurrencyPair) { CurrencyPair currencyPair = ((OpenOrdersParamCurrencyPair) params).getCurrencyPair(); String market = YoBitAdapters.adapt(currencyPair); BaseYoBitResponse response = service.activeOrders( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "ActiveOrders", exchange.getNonceFactory(), market ); if (!response.success) throw new ExchangeException("failed to get open orders"); List<LimitOrder> orders = new ArrayList<>(); if (response.returnData != null) { for (Object key : response.returnData.keySet()) { Map tradeData = (Map) response.returnData.get(key); String id = key.toString(); LimitOrder order = YoBitAdapters.adaptOrder(id, tradeData); orders.add(order); } } return new OpenOrders(orders); } throw new IllegalStateException("Need to specify currency pair"); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { String market = YoBitAdapters.adapt(limitOrder.getCurrencyPair()); String direction = limitOrder.getType().equals(Order.OrderType.BID) ? "buy" : "sell"; BaseYoBitResponse response = service.trade( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "Trade", exchange.getNonceFactory(), market, direction, limitOrder.getLimitPrice(), limitOrder.getTradableAmount() ); if (!response.success) throw new ExchangeException("failed to get place order"); return response.returnData.get("order_id").toString(); } @Override public boolean cancelOrder(String orderId) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { return cancelOrder(new CancelOrderByIdParams(orderId)); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { if (orderParams instanceof CancelOrderByIdParams) { CancelOrderByIdParams params = (CancelOrderByIdParams) orderParams; BaseYoBitResponse response = service.cancelOrder( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "CancelOrder", exchange.getNonceFactory(), Long.valueOf(params.getOrderId()) ); return response.success; } throw new IllegalStateException("Need to specify order id"); } @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { Integer count = 1000; if (params instanceof TradeHistoryParamLimit) { count = ((TradeHistoryParamLimit) params).getLimit(); } Long offset = 0L; if (params instanceof TradeHistoryParamOffset) { offset = ((TradeHistoryParamOffset) params).getOffset(); } String market = null; if (params instanceof TradeHistoryParamCurrencyPair) { CurrencyPair currencyPair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair(); market = YoBitAdapters.adapt(currencyPair); } Long fromTransactionId = null; Long endTransactionId = null; if (params instanceof TradeHistoryParamsIdSpan) { TradeHistoryParamsIdSpan tradeHistoryParamsIdSpan = (TradeHistoryParamsIdSpan) params; String startId = tradeHistoryParamsIdSpan.getStartId(); if (startId != null) fromTransactionId = Long.valueOf(startId); String endId = tradeHistoryParamsIdSpan.getEndId(); if (endId != null) endTransactionId = Long.valueOf(endId); } String order = "DESC"; if (params instanceof TradeHistoryParamsSorted) { order = ((TradeHistoryParamsSorted) params).getOrder().equals(TradeHistoryParamsSorted.Order.desc) ? "DESC" : "ASC"; } Long fromTimestamp = null; Long toTimestamp = null; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan tradeHistoryParamsTimeSpan = (TradeHistoryParamsTimeSpan) params; Date startTime = tradeHistoryParamsTimeSpan.getStartTime(); if (startTime != null) fromTimestamp = DateUtils.toUnixTimeNullSafe(startTime); Date endTime = tradeHistoryParamsTimeSpan.getEndTime(); if (endTime != null) toTimestamp = DateUtils.toUnixTimeNullSafe(endTime); } BaseYoBitResponse response = service.tradeHistory( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "TradeHistory", exchange.getNonceFactory(), offset, count, fromTransactionId, endTransactionId, order, fromTimestamp, toTimestamp, market ); List<UserTrade> trades = new ArrayList<>(); if (response.returnData != null) { for (Object key : response.returnData.keySet()) { Map tradeData = (Map) response.returnData.get(key); String id = key.toString(); String type = tradeData.get("type").toString(); String amount = tradeData.get("amount").toString(); String rate = tradeData.get("rate").toString(); String orderId = tradeData.get("order_id").toString(); String pair = tradeData.get("pair").toString(); String timestamp = tradeData.get("timestamp").toString(); Date time = DateUtils.fromUnixTime(Long.valueOf(timestamp)); UserTrade userTrade = new UserTrade( YoBitAdapters.adaptType(type), new BigDecimal(amount), YoBitAdapters.adaptCurrencyPair(pair), new BigDecimal(rate), time, id, orderId, null, null ); trades.add(userTrade); } } return new UserTrades(trades, Trades.TradeSortType.SortByTimestamp); } @Override public TradeHistoryParams createTradeHistoryParams() { throw new NotYetImplementedForExchangeException(); } @Override public OpenOrdersParams createOpenOrdersParams() { throw new NotYetImplementedForExchangeException(); } @Override public void verifyOrder(LimitOrder limitOrder) { throw new NotYetImplementedForExchangeException(); } @Override public void verifyOrder(MarketOrder marketOrder) { throw new NotYetImplementedForExchangeException(); } @Override public Collection<Order> getOrder(String... orderIds) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { List<Order> orders = new ArrayList<>(); for (String orderId : orderIds) { Long id = Long.valueOf(orderId); BaseYoBitResponse response = service.orderInfo( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "OrderInfo", exchange.getNonceFactory(), id ); if (response.returnData != null) { Map map = (Map) response.returnData.get(orderId); Order order = YoBitAdapters.adaptOrder(orderId, map); orders.add(order); } } return orders; } }
true
3e41831ea1faba30f338227569022aca4fba887b
Java
alijavidan/Internet-Engineering-Course-Project
/CA-6/ie-ca6/server/src/main/java/com/internet/engineering/IECA5/IeCa5Application.java
UTF-8
1,047
2.015625
2
[]
no_license
package com.internet.engineering.IECA5; import com.internet.engineering.IECA5.repository.MzRepository; import com.internet.engineering.IECA5.services.CourseEnrolmentService; import com.internet.engineering.IECA5.utils.schedulers.SecJob; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @SpringBootApplication public class IeCa5Application { public static void main(String[] args) { MzRepository.getInstance().createAllTables(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); try { CourseEnrolmentService.getInstance().importCoursesFromWeb(); CourseEnrolmentService.getInstance().importStudentsFromWeb(); scheduler.scheduleAtFixedRate(new SecJob(), 0, 15, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } SpringApplication.run(IeCa5Application.class, args); } }
true
a01a2aba359cef934d195ae1d9d1c1ae1cf05e19
Java
paul-g/protrade
/tests-system/org/ic/protrade/model/connection/BetfairConnectionHandlerTest.java
UTF-8
1,264
2.1875
2
[]
no_license
package org.ic.protrade.model.connection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.List; import org.ic.protrade.data.market.connection.BetfairConnectionHandler; import org.ic.protrade.data.market.connection.ProfileData; import org.ic.protrade.data.market.connection.Tournament; import org.junit.Ignore; import org.junit.Test; @Ignore public class BetfairConnectionHandlerTest extends BetfairConnectionTest{ @Test public void testGetTournamentsData() { if (setUp) { List<Tournament> tours = BetfairConnectionHandler .getTournamentsData(); assertNotNull(tours); } else { fail(SETUP_FAILED_MESSAGE); } } @Test public void testProfileData() { if (setUp) { try { ProfileData profileData = BetfairConnectionHandler .getProfileData(); assertEquals(0, profileData.getAusAccountFunds().getBalance(), Math.pow(10, -5)); assertEquals(10, profileData.getUkAccountFunds().getBalance(), Math.pow(10, -5)); assertEquals(username, profileData.getUsername()); } catch (Exception e) { fail("Profile data could not be retrieved form Betfair"); } } else { fail(SETUP_FAILED_MESSAGE); } } }
true
7be762c18632462d7313ba0b36f837c87540be9e
Java
mythread/rongyi_source
/rongyi-crm5/src/main/java/com/mallcms/service/IShopsService.java
UTF-8
309
1.625
2
[]
no_license
package com.mallcms.service; import java.util.List; import com.mallcms.domain.Shops; import com.mallcms.domain.ShopsPojo; public interface IShopsService { public List<Shops> getShopsByMallId(String mallId); public void updateShop(ShopsPojo shop); Shops getShopById(String Id); }
true
307c8b23c51653ab99dbd64cbbd9b552f7a2c240
Java
kangzhenkang/fat-jar-isolation
/fat-jar-classloader/src/main/java/com/laomei/fatjar/classloader/FatJarClassLoader.java
UTF-8
6,264
2.8125
3
[]
no_license
package com.laomei.fatjar.classloader; import com.laomei.fatjar.common.boot.jar.Handler; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.Enumeration; import java.util.jar.JarFile; /** * 拿 Spring Boot ClassLoader 抄的。一个中间件模块对应一个 Fat Jar ClassLoader。 * Spring Boot ClassLoader 会解析 fat jar 路径。如果是 fat jar,我们必须定义 package,保证能够找到对应的类。 * @see #definePackageIfNecessary(String) * * @author Phillip Webb * @author Dave Syer * @author Andy Wilkinson * @author laomei on 2019/1/9 17:32 */ public class FatJarClassLoader extends URLClassLoader { public FatJarClassLoader(final URL[] urls, ClassLoader parent) { super(urls, parent); } @Override public URL findResource(String name) { Handler.setUseFastConnectionExceptions(true); try { return super.findResource(name); } finally { Handler.setUseFastConnectionExceptions(false); } } @Override public Enumeration<URL> findResources(String name) throws IOException { Handler.setUseFastConnectionExceptions(true); try { return super.findResources(name); } finally { Handler.setUseFastConnectionExceptions(false); } } @Override protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { Handler.setUseFastConnectionExceptions(true); try { try { definePackageIfNecessary(name); } catch (IllegalArgumentException ex) { // Tolerate race condition due to being parallel capable if (getPackage(name) == null) { // This should never happen as the IllegalArgumentException indicates // that the package has already been defined and, therefore, // getPackage(name) should not return null. throw new AssertionError("Package " + name + " has already been " + "defined but it could not be found"); } } return super.loadClass(name, resolve); } finally { Handler.setUseFastConnectionExceptions(false); } } /** * Define a package before a {@code findClass} call is made. This is necessary to * ensure that the appropriate manifest for nested JARs is associated with the * package. * @param className the class name being found */ private void definePackageIfNecessary(String className) { int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { String packageName = className.substring(0, lastDot); if (getPackage(packageName) == null) { try { definePackage(className, packageName); } catch (IllegalArgumentException ex) { // Tolerate race condition due to being parallel capable if (getPackage(packageName) == null) { // This should never happen as the IllegalArgumentException // indicates that the package has already been defined and, // therefore, getPackage(name) should not have returned null. throw new AssertionError( "Package " + packageName + " has already been defined " + "but it could not be found"); } } } } } private void definePackage(final String className, final String packageName) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws ClassNotFoundException { String packageEntryName = packageName.replace('.', '/') + "/"; String classEntryName = className.replace('.', '/') + ".class"; for (URL url : getURLs()) { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection) connection) .getJarFile(); if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); return null; } } } catch (IOException ex) { // Ignore } } return null; } }, AccessController.getContext()); } catch (java.security.PrivilegedActionException ex) { // Ignore } } /** * Clear URL caches. */ public void clearCache() { for (URL url : getURLs()) { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { clearCache(connection); } } catch (IOException ex) { // Ignore } } } private void clearCache(URLConnection connection) throws IOException { Object jarFile = ((JarURLConnection) connection).getJarFile(); if (jarFile instanceof com.laomei.fatjar.common.boot.jar.JarFile) { ((com.laomei.fatjar.common.boot.jar.JarFile) jarFile).clearCache(); } } }
true
858ef193972ad2ed172592d2e13649728125b09c
Java
BBogomilov/MainRepository
/Collections, Threads/Library/src/SchoolBook.java
UTF-8
775
3.203125
3
[]
no_license
public class SchoolBook extends Reading implements Comparable<SchoolBook>{ private String theme; private String author; public SchoolBook(String name, String theme, String publishingHouse, String author) { super(name, publishingHouse); this.author = author; this.theme = theme; } protected String getAuthor() { return author; } public String getTheme() { return theme; } @Override public String toString() { return "Name: " + this.getName() + "\nAuthor: " + this.getAuthor() + "\nPublishing house: " + this.getPublishingHouse(); } @Override public int compareTo(SchoolBook o) { if(this.getTheme().compareTo(o.getTheme()) == 0) return this.getName().compareTo(o.getName()); return this.getTheme().compareTo(o.getTheme()); } }
true
d6504827c1f56f2ccdf190a84e3864986878bbb4
Java
UMKC-BigDataLab/RIQ
/RIS/virtuoso/eduDBS/umkc/sce/dbis/anask/DbStarter.java
UTF-8
5,873
2.515625
3
[]
no_license
package eduDBS.umkc.sce.dbis.anask; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; public class DbStarter { public static void main(String[] args) throws IOException, InterruptedException { // another way to pass args (for testing): /* args = new String[] { "-index","/usr/local/Cellar/virtuoso/7.1.0/var/lib/virtuoso/db", "-candidates", "/Users/anask/Downloads/RIQ/Data10/dir/ndF.txt", }; */ Options options = getProgramOptions(); HelpFormatter formatter = new HelpFormatter(); String candidates_file; String index_dir; if (args.length <= 1) { formatter.printHelp("querier", options); return; } else { CommandLineParser parser = new PosixParser(); try { CommandLine line = parser.parse(options, args); candidates_file = line.getOptionValue("candidates"); index_dir = line.getOptionValue("index"); if (line.hasOption("h")) { formatter.printHelp("querier", options); return; } } catch (ParseException exp) { System.err .println("error: parsing failed. " + exp.getMessage()); formatter.printHelp("querier", options); return; } } File candidates = new File(candidates_file); ArrayList<String> db_list = null; try { db_list = readFile(candidates, index_dir); } catch (IOException exp) { System.err.println("error: IOException caught"); return; } ArrayList<String> candProtList = configureAndStartDBs(db_list); FileOutputStream fos = new FileOutputStream(candidates_file); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (String i : candProtList ) { bw.write(i); bw.newLine(); } bw.close(); } private static ArrayList<String> configureAndStartDBs(ArrayList<String> db_list) throws IOException, InterruptedException { int baseHttpPort = 8890; int baseServerPort = 1111; int numDBs = db_list.size(); int httpPort = baseHttpPort + 1; int srvPort = baseServerPort + 1; ArrayList<String> candisates = new ArrayList<String>(); for (int i = 0; i < numDBs; i++) { String db = db_list.get(i); System.err.println("Checking ports for "+db); // check if ports are available while (!available(httpPort)) httpPort += 1; while (!available(srvPort)) srvPort += 1; System.err.println("Ports selected: "+httpPort+" and "+srvPort); // configure db virtuoso.ini file to run on these ports new DbInitiater(db, httpPort, srvPort); String[] fullpath = db.split("/"); String cand = fullpath[fullpath.length - 1]; // store cand to port mapping candisates.add(cand + ":" + srvPort); startDb(db); httpPort += 1; srvPort += 1; } System.err.println("DB Start Request Initiated, Sleeping .."); Thread.sleep(12000); System.err.println("Woke up."); return candisates;// to be used for querying } private static void startDb(String db) { String[] cmd = { "/bin/sh", "-c","/usr/bin/virtuoso-t -f"}; //String[] cmd = { "/bin/sh", "-c","/usr/local/bin/virtuoso-t -f"}; File DB = new File(db); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(DB); Process p = null; try { p = pb.start(); } catch (IOException e) { System.err.println("Error: Starting DB (VirtQuerier.java/startDb())!"); e.printStackTrace(); } } // http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java private static boolean available(int port) { // System.err.println("--------------Testing port " + port); Socket s = null; try { s = new Socket("localhost", port); // If the code makes it this far without an exception it means // something is using the port and has responded. // System.err.println("--------------Port " + port + // " is not available"); return false; } catch (IOException e) { // System.err.println("--------------Port " + port + // " is available"); return true; } finally { if (s != null) { try { s.close(); } catch (IOException e) { throw new RuntimeException("You should handle this error.", e); } } } } private static ArrayList<String> readFile(File fin, String indDir) throws IOException { FileInputStream fis = new FileInputStream(fin); ArrayList<String> files = new ArrayList<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; while ((line = br.readLine()) != null) { try{ String[] cand_Port = line.split(":"); files.add(indDir + "/" +cand_Port[0]); } catch (Exception e){ files.add(indDir + "/" +line); } } br.close(); return files; } private static Options getProgramOptions() { Options options = new Options(); Option help = new Option("h", "print this message"); Option index = OptionBuilder.withArgName("dir").hasArg(true) .withDescription("candidate dbs are stored in this dir") .isRequired(true).create("index"); Option candidates = OptionBuilder.withArgName("file").hasArg(true) .withDescription("list of candidates").isRequired(true) .create("candidates"); options.addOption(help); options.addOption(index); options.addOption(candidates); return options; } }
true
6cbc79789b662605cc08f6bb4c53159a7fc16f98
Java
mufanglintest/testui-core
/jorge-testui-core/src/main/java/com/jorge/testui/marshall/CaseApiRequestMarshall.java
UTF-8
416
1.828125
2
[]
no_license
/* * acooly.cn Inc. * Copyright (c) 2016 All Rights Reserved. * create by zhangpu * date:2016年3月17日 * */ package com.jorge.testui.marshall; import com.jorge.testui.message.CaseBaseRequest; /** * 请求报文组装接口 * * @author zhangpu * @param <T> */ public interface CaseApiRequestMarshall<T extends CaseBaseRequest, S> extends CaseApiMarshall<T, S> { @Override T marshall(S source); }
true
daf98237853a00524589fc2f3eebfba309400d86
Java
dngamage/Project
/src/main/java/com/service/IServiceGateway.java
UTF-8
113
1.90625
2
[]
no_license
package com.service; public interface IServiceGateway { public String birdInfo(); public String fishInfo(); }
true
d9a91f97364618145cefd58d5f3afd15770970c5
Java
JasperLue/Uatu
/buildSrc/src/main/java/com/vinctor/log/AbstractLogger.java
UTF-8
848
2.515625
3
[ "Apache-2.0" ]
permissive
package com.vinctor.log; import org.gradle.api.logging.LogLevel; abstract class AbstractLogger implements ILogger { @Override public void d(String tag, String msg) { log(LogLevel.DEBUG, tag, msg, null); } @Override public void i(String tag, String msg) { log(LogLevel.INFO, tag, msg, null); } @Override public void w(String tag, String msg) { w(tag, msg, null); } @Override public void w(String tag, String msg, Throwable t) { log(LogLevel.WARN, tag, msg, t); } @Override public void e(String tag, String msg) { e(tag, msg, null); } @Override public void e(String tag, String msg, Throwable t) { log(LogLevel.ERROR, tag, msg, t); } protected abstract void log(LogLevel level, String tag, String msg, Throwable t); }
true
17636d4027e80cddc51c0917787b8bab9927f10a
Java
nastya0715/Projects
/AirPorts/src/main/java/com/fedorova/airPorts/dao/jdbcImplement/CancellationDAO.java
UTF-8
3,487
2.625
3
[]
no_license
package com.fedorova.airPorts.dao.jdbcImplement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import org.apache.log4j.Logger; import com.fedorova.airPorts.dao.ICancellationDAO; import com.fedorova.airPorts.models.flights.Cancellation; public class CancellationDAO extends AbstractJDBC implements ICancellationDAO{ private final static Logger logger= Logger.getLogger(CancellationDAO.class); private final static String SET_CANCELLATION=("INSERT INTO cancellation (cancellation_time, reason) VALUES (?,?)"); private final static String UPDATE_CANCELLATION=("UPDATE cancellation SET cancellation_time=?, reason=? WHERE id=?"); private final static String GET_CANCELLATION=("SELECT * FROM cancellation where id = ?"); private final static String DELETE_CANCELLATION=("DELETE FROM cancellation WHERE id=?"); @Override public void insert(Cancellation cancellation) { Connection connection =null; PreparedStatement ps = null; try { connection = pool.getConnection(); ps = connection.prepareStatement(SET_CANCELLATION); ps.setString(1, cancellation.getDateTime()); ps.setString(2, cancellation.getReason()); ps.executeUpdate(); } catch (SQLException e) { logger.error(e); } finally { pool.releaseConnection(connection); try { ps.close(); } catch (SQLException e) { logger.error(e); } } } @Override public Cancellation getById(int id) { Connection connection =null; PreparedStatement ps = null; ResultSet rs = null; Cancellation cancellation = new Cancellation(); try { connection = pool.getConnection(); ps = connection.prepareStatement(GET_CANCELLATION); ps.setInt(1, id); rs = ps.executeQuery(); if (rs.next()) { buildCancellation(rs, cancellation); } } catch (SQLException e) { logger.error(e); } catch (ParseException e) { logger.error(e); } finally { pool.releaseConnection(connection); try { ps.close(); rs.close(); } catch (SQLException e) { logger.error(e); } } return cancellation; } @Override public void update(Cancellation cancellation) { Connection connection=null; PreparedStatement ps = null; try { connection = pool.getConnection(); ps = connection.prepareStatement(UPDATE_CANCELLATION); ps.setString(1, cancellation.getDateTime()); ps.setString(2, cancellation.getReason()); ps.setInt(3, cancellation.getId()); ps.executeUpdate(); } catch (SQLException e) { logger.error(e); } finally { pool.releaseConnection(connection); try { ps.close(); } catch (SQLException e) { logger.error(e); } } } @Override public void delete(Cancellation cancellation) { Connection connection =null; PreparedStatement ps = null; try { connection = pool.getConnection(); ps = connection.prepareStatement(DELETE_CANCELLATION); ps.setInt(1, cancellation.getId()); ps.executeUpdate(); } catch (SQLException e) { logger.error(e); } finally { pool.releaseConnection(connection); try { ps.close(); } catch (SQLException e) { logger.error(e); } } } private void buildCancellation(ResultSet rs, Cancellation cancellation) throws SQLException, ParseException { cancellation.setId(rs.getInt("id")); cancellation.setDateTime(rs.getString("cancellation_time")); cancellation.setReason(rs.getString("reason")); } }
true
4fb8814436f602651918d57cb3d123e43685fc77
Java
wzqly1120/my-test1
/crm-project/crm-test/src/main/java/com/bjpowernode/crm/workbench/service/impl/ActivityServiceImpl.java
UTF-8
666
2.03125
2
[]
no_license
package com.bjpowernode.crm.workbench.service.impl;/* *2020/12/10 */ import com.bjpowernode.crm.workbench.domain.Activity; import com.bjpowernode.crm.workbench.mapper.ActivityMapper; import com.bjpowernode.crm.workbench.service.ActivityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("activityService") public class ActivityServiceImpl implements ActivityService { //注入mapper @Autowired private ActivityMapper activityMapper; @Override public int saveCreateActivity(Activity activity) { return activityMapper.insertActivity(activity); } }
true
253c262acf33878623dc93d86708cf6a9b1ba5d8
Java
Genhis/Evolution
/src/sk/genhis/evolution/OrganismDisplay.java
UTF-8
297
2.203125
2
[]
no_license
package sk.genhis.evolution; import javax.swing.JPanel; public class OrganismDisplay extends JPanel { private static final long serialVersionUID = 0L; private final Organism o; public OrganismDisplay(Organism o) { this.o = o; } public Organism getOrganism() { return this.o; } }
true
a313128e8225687f68d05f656f2b14944943b40e
Java
robellgabriel/risk
/tests/GameTest.java
UTF-8
9,690
2.859375
3
[]
no_license
import org.junit.*; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import static org.junit.Assert.*; public class GameTest { Game game; HashMap<String, Boolean> playerNames; @Before public void SetUp() throws IOException, SAXException, ParserConfigurationException { game = new Game(); playerNames = new HashMap<>(); playerNames.put("a",false); playerNames.put("b",false); game.initialize(playerNames); } @After public void TearDown(){ game = null; playerNames = null; } @Test public void testMovePhase() { Player p = game.getCurrentPlayer(); Territory t1 = p.getAllLandOwned().get(0); Territory t2 = p.getAllLandOwned().get(1); int i = 4, k = 9, j = 1; t1.setNumArmies(k); t2.setNumArmies(j); game.movePhase(i, t1, t2); assertEquals(t1.getNumArmies(), t2.getNumArmies()); assertEquals(t1.getNumArmies() + i, k); assertEquals(t2.getNumArmies() - i, j); assertNotEquals(p, game.getCurrentPlayer()); k = 1; j = 10; t1.setNumArmies(k); t2.setNumArmies(j); game.movePhase(i,t1,t2); assertEquals(t1.getNumArmies() , k); assertEquals(t2.getNumArmies() , j); assertEquals(p,game.getCurrentPlayer()); } /** * This method test place phase when player add all bonus armies into a single territory */ @Test public void testPlacePhaseSingleTer() { Player p = game.getCurrentPlayer(); Territory placing = p.getAllLandOwned().get(0); int placingArmies = placing.getNumArmies(); HashMap<String,Integer> mt = new HashMap<>(); mt.put(placing.getId(), 3); game.placePhase(mt); assertEquals(placingArmies + 3, placing.getNumArmies()); } /** * tests to see if all players have the right amount of territories and armies total * * @author Robell Gabriel */ @Test public void testInitialize() { int totalTerr = 0; for (Player player : game.getActivePlayers()) { totalTerr += player.getAllLandOwnedSize(); int totalArm = 0; for (Territory territory : player.getAllLandOwned()){ totalArm += territory.getNumArmies(); } assertEquals(50, totalArm); } assertEquals(42, totalTerr); totalTerr = 0; playerNames.put("c", false); game = new Game(); game.initialize(playerNames); for (Player player : game.getActivePlayers()) { totalTerr += player.getAllLandOwnedSize(); int totalArm = 0; for (Territory territory : player.getAllLandOwned()){ totalArm += territory.getNumArmies(); } assertEquals(35, totalArm); } assertEquals(42, totalTerr); totalTerr = 0; playerNames.put("d",false); game = new Game(); game.initialize(playerNames); for (Player player : game.getActivePlayers()) { totalTerr += player.getAllLandOwnedSize(); int totalArm = 0; for (Territory territory : player.getAllLandOwned()){ totalArm += territory.getNumArmies(); } assertEquals(30, totalArm); } assertEquals(42, totalTerr); totalTerr = 0; playerNames.put("e",false); game = new Game(); game.initialize(playerNames); for (Player player : game.getActivePlayers()) { totalTerr += player.getAllLandOwnedSize(); int totalArm = 0; for (Territory territory : player.getAllLandOwned()){ totalArm += territory.getNumArmies(); } assertEquals(25, totalArm); } assertEquals(42, totalTerr); totalTerr = 0; playerNames.put("f",false); game = new Game(); game.initialize(playerNames); for (Player player : game.getActivePlayers()) { totalTerr += player.getAllLandOwnedSize(); int totalArm = 0; for (Territory territory : player.getAllLandOwned()){ totalArm += territory.getNumArmies(); } assertEquals(20, totalArm); } assertEquals(42, totalTerr); } /** * This method test place phase when player distribute multiple armies to multiple territories */ @Test public void testPlacePhaseMultipleTer() { //Testing place phase for multiple territories involved Territory testTer1, testTer2, testTer3; int ter1Armies, ter2Armies, ter3Armies; Player p = game.getCurrentPlayer(); //Creating multiple territory testTer1 = p.getAllLandOwned().get(0); ter1Armies = testTer1.getNumArmies(); testTer2 = p.getAllLandOwned().get(1); ter2Armies = testTer2.getNumArmies(); testTer3 = p.getAllLandOwned().get(2); ter3Armies = testTer3.getNumArmies(); //Making hashmap to fulfil the parameter of place phase in game model HashMap<String, Integer> mt = new HashMap<>(); //Setting up for testing mt.put(testTer1.getId(), 3); mt.put(testTer2.getId(), 2); mt.put(testTer3.getId(), 1); game.placePhase(mt); assertEquals(ter1Armies + 3, testTer1.getNumArmies()); assertEquals(ter2Armies + 2, testTer2.getNumArmies()); assertEquals(ter3Armies + 1, testTer3.getNumArmies()); } @Test public void testAttackWon() { Player player1 = game.getActivePlayers().get(0); Player player2 = game.getActivePlayers().get(1); // Remove all territories from player 2 List<Territory> player2Land = player2.getAllLandOwned(); player2Land.clear(); Territory attacking = new Territory("Attacking", "ATT", List.of()); attacking.setPlayer(player1); attacking.setNumArmies(10); player1.addTerritory(attacking); Territory defending1 = new Territory("Defending", "DEF", List.of()); Territory defending2 = new Territory("Defending", "DEF", List.of()); defending1.setPlayer(player2); defending1.setNumArmies(2); player2.addTerritory(defending1); defending2.setPlayer(player2); defending2.setNumArmies(2); player2.addTerritory(defending2); assertTrue(game.getActivePlayers().contains(player2)); assertEquals(player2.getAllLandOwnedSize(), 2); game.attackWon(attacking, defending1, 3); assertEquals(defending1.getNumArmies(), 3); assertEquals(defending1.getOwner(), player1); assertTrue(player1.getAllLandOwned().contains(defending1)); game.attackWon(attacking, defending2, 3); assertFalse(game.getActivePlayers().contains(player2)); assertEquals(defending2.getNumArmies(), 3); assertEquals(defending2.getOwner(), player1); assertTrue(player1.getAllLandOwned().contains(defending2)); } /** * Test save and load features for GameModel * * @throws IOException if the GameModelfile is invalid * @throws ClassNotFoundException if adding objects from GameModelfile is invalid * @throws FileNotFoundException if game file doesnt exist * * @author Robell Gabriel */ @Test public void saveEqualsLoadGame() throws IOException, ClassNotFoundException, FileNotFoundException { Game gSave = new Game(); Game gLoad = new Game(); Map<String, Boolean> playerNames = new HashMap<>(); playerNames.put("a",false); playerNames.put("b",false); gSave.initialize(playerNames); gSave.saveGame(); gLoad.loadGame(); assertEquals(gSave, gLoad); } /** * Test importing a custom map. * @throws IOException If the file cannot be read * @throws SAXException If the file is improperly formatted * @throws ParserConfigurationException If the parser is incorrectly configured * @author Nicolas Tuttle */ @Test public void testImportValidMap() throws IOException, SAXException, ParserConfigurationException { HashMap<String, Continent> expectedContinents = new HashMap<>(); expectedContinents.put("NA", new Continent( "North America", List.of( new Territory("Eastern United States", "NA1", List.of("NA2", "NA3", "NA4")), new Territory("Western United States", "NA2", List.of("NA1", "NA3", "NA4")), new Territory("Northern United States", "NA3", List.of("NA2")), new Territory("Southern United States", "NA4", List.of("NA2")) ), 4 )); Game game = new Game(); game.importCustomMap("tests/validCustomMap.xml"); assertEquals(expectedContinents, game.getContinents()); } /** * Test importing an invalid custom map. * @throws IOException If the file cannot be read * @throws SAXException Should throw this as the file is invalid * @throws ParserConfigurationException If the parser is incorrectly configured * @author Nicolas Tuttle */ @Test(expected = SAXException.class) public void testImportInvalidMap() throws IOException, SAXException, ParserConfigurationException { Game game = new Game(); game.importCustomMap("tests/invalidCustomMap.xml"); } }
true
f3bc0c9ef4f440e795cc88b761af14b9f82e62cf
Java
Fundamental-OOP/final-project-b07902042
/src/hearthclone/model/minion/AnnoyRobot.java
UTF-8
1,310
3.015625
3
[]
no_license
package hearthclone.model.minion; import hearthclone.model.DivineShield; import hearthclone.model.Taunt; //Complete public class AnnoyRobot extends AbstractMinion implements DivineShield, Taunt { private static String name = "AnnoyRobot"; private static String description = "DivineShield & Taunt"; private static int baseCost = 2; private static int baseATK = 1; private static int baseHP = 2; private boolean divineShield = true; public AnnoyRobot() { super(AnnoyRobot.name, AnnoyRobot.description, AnnoyRobot.baseCost, AnnoyRobot.baseHP, AnnoyRobot.baseATK); } @Override public void setHP(int HP) { // Heal if (this.HP < HP) { System.out.printf("%s +%d HP.\n", name, HP - this.HP); this.HP = Math.min(HP, this.buffHP); } // damage else if (this.HP > HP) { if (this.divineShield) { System.out.printf("%s deny damage by DivineShield.\n", name); this.divineShield = false; } else { System.out.printf("%s -%d HP.\n", name, this.HP - HP); this.HP = HP; } } this.minionChange(); } @Override public boolean hasDivineShield() { return this.divineShield; } }
true
28aedab9aaf38c778dde87d5b2c83e6bf78a2312
Java
benoist-lab/planificateur_voyage
/src/main/java/com/planificateurVoyage/repository/StatutVoyageRepository.java
UTF-8
934
2.203125
2
[]
no_license
package com.planificateurVoyage.repository; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.planificateurVoyage.model.StatutVoyage; import com.planificateurVoyage.tools.JPASpecificationUtility; public interface StatutVoyageRepository extends JpaRepository <StatutVoyage, Long>, JpaSpecificationExecutor { public static Specification hasStatutVoyage (StatutVoyage statutVoyageCritere) { Specification specification=null; if ((statutVoyageCritere.getLibelle()!=null) && (!statutVoyageCritere.getLibelle().isEmpty())) { specification=JPASpecificationUtility.andToSpecification (specification, (statutVoyage,criteriaQuery,criteriaBuilder) -> criteriaBuilder.equal (statutVoyage.get("libelle"),statutVoyageCritere.getLibelle())); } return specification; } }
true
cd1737bc277421b7c5a905b9ed764ea0e4a392f8
Java
nikolabaska/Selenium-AutomationPractice
/objects/Loginpage.java
UTF-8
434
1.5625
2
[]
no_license
package objects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class Loginpage { protected By signin =By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a"); protected By email =By.id("email"); protected By password =By.id("passwd"); protected By Submit1 =By.id("SubmitLogin"); public String usser = "milevskinikola@gmail.com"; public String pass = "nikolabaska10"; }
true
e4c9f278a5d4bdc7b1b7038c06c4c36d3353bc66
Java
e88z4/mythtvguide
/src/main/java/org/jmythapi/protocol/events/IFileWritten.java
UTF-8
1,205
2.546875
3
[]
no_license
package org.jmythapi.protocol.events; import java.util.Date; import org.jmythapi.protocol.annotation.MythParameterType; import org.jmythapi.protocol.request.IMythCommand; /** * @see IMythCommand#BACKEND_MESSAGE_FILE_WRITTEN */ public interface IFileWritten extends IRecordingEvent<IFileWritten.Props> { public static enum Props { /** * e.g. {@code /var/lib/mythtv/recordings/4008_20141021052500.mpg} */ @MythParameterType(String.class) FILE_PATH, @MythParameterType(Long.class) FILE_SIZE } /** * {@inheritDoc} */ public Integer getChannelID(); /** * {@inheritDoc} */ public Date getRecordingStartTime(); /** * {@inheritDoc} */ public String getUniqueRecordingID(); /** * The base name of the written file. * * @return * the base name, e.g. {@code 4008_20141021052500.mpg} */ public String getFileBaseName(); /** * The full path to the written file. * * @return * the full file-name, e.g. {@code /var/lib/mythtv/recordings/4008_20141021052500.mpg} */ public String getFilePath(); /** * The amount of data written to the file so far. * * @return * the amount of bytes written. */ public Long getFileSize(); }
true
b0c67914620482b7247c514748f6a6d50ce6943b
Java
Catmaniscatlord/ProjectEuler
/problem_32/Problem32.java
UTF-8
2,042
3.28125
3
[]
no_license
package problem_32; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Problem32 { public static void main(String[] args) { String digits = "123456789"; String tmp; Set<Integer> panDigitals = new HashSet<Integer>(); int total = 0; char[] tmpArray; for (int i = 1; i < 10; i++) { for (int j = 1000; j < 10000 ; j++) { tmp = ""; tmp += i; tmp += j; tmp += (i * j); if(tmp.length() == 9){ tmpArray = tmp.toCharArray(); Arrays.sort(tmpArray); if(new String(tmpArray).equals(digits)) { if(!panDigitals.contains(i * j)) { panDigitals.add(i * j); total += i * j; } System.out.println(i * j + " = " + i + " * " + j); } } else if (tmp.length() > 9){ break; } } } for (int i = 10; i < 100; i++) { for (int j = 100; j < 1000 ; j++) { tmp = ""; tmp += i; tmp += j; tmp += (i * j); if(tmp.length() == 9){ tmpArray = tmp.toCharArray(); Arrays.sort(tmpArray); if(new String(tmpArray).equals(digits)) { if(!panDigitals.contains(i * j)) { panDigitals.add(i * j); total += i * j; } System.out.println(i * j + " = " + i + " * " + j); } } else if (tmp.length() > 9){ break; } } } System.out.println(total); } }
true
ae91128a078cd9812ba4b1353e7158531edf3e52
Java
Rakesh-Subudhi-GitHub/Associtation
/Anno_ManyToMany_Bi/src/main/java/com/rk/dao/ManyToManyDAO.java
UTF-8
141
1.648438
2
[]
no_license
package com.rk.dao; public interface ManyToManyDAO { public void saveDataUsingParent(); public void saveDataUsingChilds(); }
true
08b4db35d768ff538c901ae0b3f2a9f7631ef58f
Java
g2vinay/azure-sdk-for-java
/sdk/apimanagement/azure-resourcemanager-apimanagement/src/samples/java/com/azure/resourcemanager/apimanagement/ApiManagementServiceBackupSamples.java
UTF-8
1,351
1.929688
2
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement; import com.azure.core.util.Context; import com.azure.resourcemanager.apimanagement.models.ApiManagementServiceBackupRestoreParameters; /** Samples for ApiManagementService Backup. */ public final class ApiManagementServiceBackupSamples { /* * operationId: ApiManagementService_Backup * api-version: 2020-12-01 * x-ms-examples: ApiManagementCreateBackup */ /** * Sample code: ApiManagementCreateBackup. * * @param manager Entry point to ApiManagementManager. */ public static void apiManagementCreateBackup(com.azure.resourcemanager.apimanagement.ApiManagementManager manager) { manager .apiManagementServices() .backup( "rg1", "apimService1", new ApiManagementServiceBackupRestoreParameters() .withStorageAccount("teststorageaccount") .withAccessKey("**************************************************") .withContainerName("backupContainer") .withBackupName("apimService1backup_2017_03_19"), Context.NONE); } }
true
02fc63c1fdd5013b44e9e2787da47402e8fec88a
Java
jinrang2/TJS_BigData
/src/1_JAVA/ch13_interface/src/com/lec/ex09lib/CDLib.java
UTF-8
1,629
3.3125
3
[]
no_license
package com.lec.ex09lib; public class CDLib extends CDInfo implements ILendable { private String borrower; private String checkOutDate; private byte state; public CDLib() {} public CDLib(String cdNo, String cdTitle, String bookNo) { super(cdNo, cdTitle, bookNo); this.borrower = ""; this.checkOutDate = ""; state = STATE_NORMAL; } @Override public void checkOut(String borrower, String checkOutDate) { if(state != STATE_NORMAL) { System.out.println("대출중인 CD입니다"); return; } this.borrower = borrower; this.checkOutDate = checkOutDate; state = STATE_BORROWED; System.out.printf("\"%s\" CD가 대출되었습니다\n", getCdTitle() ); } @Override public void checkIn() { if(state != STATE_BORROWED) { System.out.println("대출중인 CD가 아닙니다. 어디서 났어!?"); return; } System.out.printf("\"%s\" CD가 반납 처리 되었습니다\n", getCdTitle() ); borrower = null; checkOutDate = null; state = STATE_NORMAL; } @Override public void printState() { if (state == STATE_NORMAL) { System.out.printf("CD이름 : %s\t책번호 : %s\t- 대출가능\n",getCdTitle(), getCdNo() ); } else if (state == STATE_BORROWED) { System.out.printf("CD이름 : %s\t책번호 : %s\t- 대출중\n", getCdTitle(), getCdNo() ); } else { System.out.printf("CD이름 : %s\t책번호 : %s\t - 유령상태\n",getCdTitle(), getCdNo() ); } } public boolean isBorrowable() { if(this.getState()==ILendable.STATE_BORROWED) { return true; } return false; } public byte getState() { return state; } }
true
58e7b2c74e6450df0e42550db29590411f65e6ee
Java
xinqipei/YumFoodProject
/app/src/main/java/com/example/yummfoodapp/util/Loading.java
UTF-8
510
2.234375
2
[]
no_license
package com.example.yummfoodapp.util; import android.app.ProgressDialog; import android.content.Context; public class Loading { ProgressDialog progressDialog; public Loading(Context context){ progressDialog=new ProgressDialog(context); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); } public void showLoading(){ progressDialog.show(); } public void hideLoading(){ progressDialog.hide(); } }
true
f1fe631275f8eb852c2ae8a310c7769c3af50387
Java
274336317/avt_ui
/com.coretek.spte.core/src/com/coretek/spte/core/locators/MidpointOffsetLocatorForDot.java
GB18030
874
2.28125
2
[]
no_license
package com.coretek.spte.core.locators; import org.eclipse.draw2d.Connection; import org.eclipse.draw2d.MidpointLocator; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; /** * ϢеʡԺűǩλ * * @author Ρ * @date 2010-9-1 * */ public class MidpointOffsetLocatorForDot extends MidpointLocator { private Point offset; public MidpointOffsetLocatorForDot(Connection c, int i, int increment) { super(c, i); PointList points = c.getPoints(); offset = new Point(points.getPoint(0).x, points.getPoint(0).y + increment); } @Override protected Point getReferencePoint() { Point point = super.getReferencePoint(); return point.getTranslated(offset); } public Point getOffset() { return offset; } public void setOffset(Point offset) { this.offset = offset; } }
true
0056bb2c2ce4ec7383e1121adba507d1e244ab64
Java
sengeiou/wqb_yzj
/bookkeeper/src/main/java/com/wqb/dao/subject/impl/TBasicSubjectMappingMapperImpl.java
UTF-8
6,885
2.046875
2
[]
no_license
package com.wqb.dao.subject.impl; import com.wqb.common.Log4jLogger; import com.wqb.dao.subject.TBasicSubjectMappingMapper; import com.wqb.model.TBasicMeasure; import com.wqb.model.TBasicSubjectMapping; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component @Service("TBasicSubjectMappingMapper") public class TBasicSubjectMappingMapperImpl implements TBasicSubjectMappingMapper { private static Log4jLogger logger = Log4jLogger.getLogger(TBasicSubjectMappingMapperImpl.class); @Autowired SqlSessionFactory sqlSessionFactory; @Override public int uploadSubMappingList(List<TBasicSubjectMapping> tBasicSubjectMappingList) { SqlSession sqlSesion = null; int results = 0; try { sqlSesion = sqlSessionFactory.openSession(); results = sqlSesion.insert("subjectMapping.updateSubMappingList", tBasicSubjectMappingList); } catch (Exception e) { e.printStackTrace(); } finally { sqlSesion.close(); } return results; } @Override public int deleteByAccountId(TBasicMeasure tBasicMeasure) { SqlSession sqlSesion = null; int results = 0; try { // sqlSesion = sqlSessionFactory.openSession(); // results = sqlSesion.insert("subjectMapping.deleteByAccountId", tBasicMeasure); } catch (Exception e) { e.printStackTrace(); } finally { // sqlSesion.close(); } return results; } @Override public int deleteByPrimaryKey(Integer pkSubMappingId) { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.delete("subjectMapping.deleteByPrimaryKey", pkSubMappingId); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.deleteByPrimaryKey--delete错误"); } finally { sqlSesion.close(); } return num; } @Override public int insert(TBasicSubjectMapping tBasicSubjectMapping) { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.insert("subjectMapping.insert", tBasicSubjectMapping); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.insert--insert错误"); } finally { sqlSesion.close(); } return num; } @Override public int insertSelective(TBasicSubjectMapping tBasicSubjectMapping) { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.insert("subjectMapping.insertSelective", tBasicSubjectMapping); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.subjectMapping--insertSelective错误"); } finally { sqlSesion.close(); } return num; } @Override public TBasicSubjectMapping selectByPrimaryKey(Integer pkSubMappingId) { SqlSession sqlSesion = null; TBasicSubjectMapping tBasicSubjectMapping = null; try { sqlSesion = sqlSessionFactory.openSession(); Object selectOne = sqlSesion.selectOne("subjectMapping.selectByPrimaryKey", pkSubMappingId); tBasicSubjectMapping = (TBasicSubjectMapping) selectOne; } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.selectByPrimaryKey--selectOne错误"); } finally { sqlSesion.close(); } return tBasicSubjectMapping; } @Override public int updateByPrimaryKeySelective(TBasicSubjectMapping tBasicSubjectMapping) { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.update("subjectMapping.updateByPrimaryKeySelective", tBasicSubjectMapping); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.subjectMapping--updateByPrimaryKeySelective错误"); } finally { sqlSesion.close(); } return num; } @Override public int updateByPrimaryKey(TBasicSubjectMapping tBasicSubjectMapping) { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.update("subjectMapping.updateByPrimaryKey", tBasicSubjectMapping); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.subjectMapping--updateByPrimaryKey错误"); } finally { sqlSesion.close(); } return num; } @Override public int deleteAll() { SqlSession sqlSesion = null; int num = 0; try { sqlSesion = sqlSessionFactory.openSession(); num = sqlSesion.delete("subjectMapping.deleteAll"); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.deleteAll--deleteAll错误"); } finally { sqlSesion.close(); } return num; } @Override public List<TBasicSubjectMapping> querySubMappingList(Integer accountType) { SqlSession sqlSesion = null; List<TBasicSubjectMapping> selectList = new ArrayList<TBasicSubjectMapping>(); try { sqlSesion = sqlSessionFactory.openSession(); Map<String, Object> param = new HashMap<String, Object>(); param.put("accountType", accountType); selectList = sqlSesion.selectList("subjectMapping.querySubMappingList", param); } catch (Exception e) { e.printStackTrace(); logger.error("subjectMapping.querySubMappingList--selectList错误"); } finally { sqlSesion.close(); } return selectList; } @Override public int deleteMeasureList(List<TBasicSubjectMapping> tBasicSubMappingList) { SqlSession sqlSesion = null; int results = 0; try { sqlSesion = sqlSessionFactory.openSession(); results = sqlSesion.delete("subjectMapping.querySubMappingList", tBasicSubMappingList); } catch (Exception e) { e.printStackTrace(); } finally { sqlSesion.close(); } return results; } }
true
dc8da2e2d9fa3feaa2120edb4804c13e305106c0
Java
spinachgit/itextpdf-demo
/src/main/java/sandbox/images/WatermarkedImages2.java
UTF-8
3,302
2.78125
3
[]
no_license
/** * This code sample was written by Bruno Lowagie in answer to this question: * http://stackoverflow.com/questions/26814958/pdf-vertical-postion-method-gives-the-next-page-position-instead-of-current-page */ package sandbox.images; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.Image; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.GrayColor; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPCellEvent; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import sandbox.WrapToTest; @WrapToTest public class WatermarkedImages2 { public static final String IMAGE1 = "resources/images/bruno.jpg"; public static final String IMAGE2 = "resources/images/dog.bmp"; public static final String IMAGE3 = "resources/images/fox.bmp"; public static final String IMAGE4 = "resources/images/bruno_ingeborg.jpg"; public static final Font FONT = new Font(FontFamily.HELVETICA, 12, Font.NORMAL, GrayColor.GRAYWHITE); public static final String DEST = "results/images/watermark_table.pdf"; public static void main(String[] args) throws IOException, DocumentException { File file = new File(DEST); file.getParentFile().mkdirs(); new WatermarkedImages2().createPdf(DEST); } public void createPdf(String dest) throws IOException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); document.open(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); PdfPCell cell; cell = new PdfPCell(Image.getInstance(IMAGE1), true); cell.setCellEvent(new WatermarkedCell("Bruno")); table.addCell(cell); cell = new PdfPCell(Image.getInstance(IMAGE2), true); cell.setCellEvent(new WatermarkedCell("Dog")); table.addCell(cell); cell = new PdfPCell(Image.getInstance(IMAGE3), true); cell.setCellEvent(new WatermarkedCell("Fox")); table.addCell(cell); cell = new PdfPCell(Image.getInstance(IMAGE4), true); cell.setCellEvent(new WatermarkedCell("Bruno and Ingeborg")); table.addCell(cell); document.add(table); document.close(); } class WatermarkedCell implements PdfPCellEvent { String watermark; public WatermarkedCell(String watermark) { this.watermark = watermark; } public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS]; ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase(watermark, FONT), (position.getLeft() + position.getRight()) / 2, (position.getBottom() + position.getTop()) / 2, 30); } } }
true
627a2b55dd3dfb3d9fec91c99a06513d881fef45
Java
AY1920S1-CS2113T-F10-2/main
/src/main/java/list/UpdateFile.java
UTF-8
2,094
3.140625
3
[]
no_license
package list; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; public class UpdateFile { private final String filename = "../data/savedegree.txt"; //text file that stores all the information File file = new File(filename); private List<String> lines; //private ArrayList<String> list = DegreeList.getDegrees(); /** * The method changes the value of the ranks of the degrees after a degree has been removed from the list. * * @param degree * @return newLines */ private List<String> changeValueOf(String degree){ List<String> newLines = new ArrayList<String>(); for(String line: lines){ String [] vals = line.split("-"); if(vals[1].equals(degree)){ int newVal = Integer.parseInt(vals[2]) - 1; newLines.add(vals[0] + "-" + vals[1] + "-" + newVal); } else { newLines.add(line); } } return newLines; } private List<String> swapValue(String degree){ List<String> newLines = new ArrayList<String>(); for(String line: lines){ String [] vals = line.split("-"); if(vals[1].equals(degree)){ int newVal = Integer.parseInt(vals[2]) - 1; newLines.add(vals[0] + "-" + vals[1] + "-" + newVal); } else { newLines.add(line); } } return newLines; } /** * The method calls changeValueof function to write to the text file the new index of the degrees post removal of a degree. * @param degree * @throws IOException */ public void reduce_index(String degree) throws IOException { lines = Files.readAllLines(file.toPath(), Charset.defaultCharset()); changeValueOf(degree); Files.write(file.toPath(), changeValueOf(degree), Charset.defaultCharset()); } }
true
fff0180056c2ebdd8ba3f6c376521499b2372603
Java
vodrazka/GOF-DesignPatterns
/src/pl/fane/gof/creational/builder/user/model/UserBuilder.java
UTF-8
927
2.734375
3
[]
no_license
package pl.fane.gof.creational.builder.user.model; import pl.fane.gof.creational.builder.user.Builder; public class UserBuilder implements Builder<User> { private User user; public UserBuilder() { this.user = new User(); } @Override public User build() { try{ return user; }finally { user = new User(); } } public UserBuilder surname(String surname) { user.setSurname(surname); return this; } public UserBuilder lastname(String lastname) { user.setLastname(lastname); return this; } public UserBuilder email(String email) { user.setEmail(email); return this; } public UserBuilder age(Integer age) { user.setAge(age); return this; } public UserBuilder height(Integer height) { user.setHeight(height); return this; } }
true
222ccdaa259bfe49ce24467af7c39efaac1a2498
Java
jarvisxiong/dev
/src/main/java/com/hengyun/service/account/PatientAccountService.java
UTF-8
1,128
2.078125
2
[]
no_license
package com.hengyun.service.account; import java.util.List; import com.hengyun.domain.account.PatientInfo; import com.hengyun.domain.loginInfo.LoginResult; import com.hengyun.service.BaseService; import com.hengyun.service.impl.account.UserNotExistException; /** * @author bob E-mail:panbaoan@thealth.cn * @version 创建时间:2016年4月5日 下午2:51:43 * 病人信息业务接口 */ public interface PatientAccountService extends BaseService<PatientInfo,Integer>{ public PatientInfo getPatientInfoById(int id) ; //用户是否存在 public int existPatient(String sign, String type); public List<PatientInfo> getUserAccountALL(); //更改密码 public void updatePassword(String password,int userId) ; //注册账号 public int registerPatient(String username,String type,String password); //改变用户找好绑定信息 public int change(String type,String username,int userId); //第三方登陆注册 public int registerThirdAccount(String sign,String type); //验证用户是否有效,返回用户userId public LoginResult validateUserBySign(String sign, String type,String password) ; }
true
9619e44274e6d7931606a8d3a8b8bad653072b1a
Java
arabhossain/Retail_Pos
/src/FileIOService/Local_DB_ConfigCreate.java
UTF-8
4,283
2.359375
2
[]
no_license
/* Software Engineer --------------------------------------- Md. Arab Hossain Email: arabhossain317@diu.edu.bd green.arab1995@gmail.com Mobile: +8801827-464330 +8801737-331037 Daffodil International University(Student) */ package FileIOService; import AppConfig.vars; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author Loser */ public class Local_DB_ConfigCreate { /** * */ public Local_DB_ConfigCreate(){ try{ new Delete("./Configs/Localconfig.xml"); }catch(Exception e){ e.printStackTrace(); } } /** * */ public void db_data(){ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Local_Database"); doc.appendChild(rootElement); // staff elements Element staff = doc.createElement("Driver"); rootElement.appendChild(staff); Attr attr = doc.createAttribute("Connection"); attr.setValue(vars.getDRIVER_Type()); staff.setAttributeNode(attr); Element driveer = doc.createElement("JDBC_DRIVER"); driveer.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getJDBC_DRIVER()))); staff.appendChild(driveer); Element dburl = doc.createElement("DB_URL"); dburl.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getDB_Url()))); staff.appendChild(dburl); Element dbname = doc.createElement("DB_Name"); dbname.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getDbName()))); staff.appendChild(dbname); Element user = doc.createElement("DB_User"); user.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getDbUser()))); staff.appendChild(user); Element pass = doc.createElement("DB_Password"); pass.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getDbPass()))); staff.appendChild(pass); // staff elements Element a = doc.createElement("Branch"); rootElement.appendChild(a); Attr b = doc.createAttribute("Area"); b.setValue("Local"); a.setAttributeNode(b); Element c = doc.createElement("Shop_Name"); c.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getShopName()))); a.appendChild(c); Element d = doc.createElement("BranchId"); d.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(String.valueOf(vars.getBranchID())))); a.appendChild(d); Element e = doc.createElement("MoneySymble"); e.appendChild(doc.createTextNode(Arab.Arab3SH.En_Code(vars.getMoneySymble()))); a.appendChild(e); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("./Configs/Localconfig.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } }
true
f71bf97dfe022bb7c21937b70dd93d5d91486901
Java
Frexiona/Digital-Work-Traceability-System
/BackEnd/src/main/java/com/numsource/artproject/DTO/PictureInfo.java
UTF-8
328
1.632813
2
[]
no_license
package com.numsource.artproject.DTO; import lombok.Data; import java.io.File; @Data public class PictureInfo { private String picture; private String name; private String author; private Integer price; private String info; private Integer hot; private String owner; private String status; }
true
f5da8118944e97d42104cf562113931b2d0d6357
Java
AishaKaplan/Company.java
/src/day26/MoodRing.java
UTF-8
941
3.609375
4
[]
no_license
package day26; import java.util.Scanner; public class MoodRing { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is the mood ring color?"); String color = input.next(); String mood = ""; double budget = 0.0; switch (color) { case "pink": mood = "happy"; budget = 200.0; break; case "blue": mood = "relaxed"; budget = 150.0; break; case "orange": mood = "nervous"; budget = 50.0; break; case "red": mood = "angry"; budget = 0.0; break; } System.out.println("Your color was: " + color); System.out.println("Which means you are " +mood); System.out.println("You mode means you can spend $" + budget); } }
true
73c79bfbe34f6e2c6178c7cc1ee7f72356543952
Java
KarlaGallegos/AlgoritmosSistemas
/ene-jun-2021/Karla Sarabi Gallegos Arredondo/Objeto.java
UTF-8
656
3.53125
4
[]
no_license
package AlgoritmosDeOrdenamiento; public class Objeto { private String nombre; private int cantidad; public Objeto(){ nombre = " "; cantidad = 0; } public Objeto(String s, int x){ nombre = s; cantidad = x; } public void setNombre(String s){ nombre = s; } public String getNombre(){ return nombre; } public void setCantidad(int x){ cantidad = x; } public int getCantidad(){ return cantidad; } public String toString(){ return nombre + " "; } }
true
49ef982d28a239efecfa738f39b82a0819a959e1
Java
verygoodwlk/shop_1810pom
/shop_web/shop_item/src/main/java/com/qf/controller/ItemController.java
UTF-8
1,913
2.453125
2
[]
no_license
package com.qf.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.qf.entity.Goods; import com.qf.service.IGoodsService; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/item") public class ItemController { @Reference private IGoodsService goodsService; @Autowired private Configuration configuration; /** * 生成静态页面 * @return */ @RequestMapping("/createHtml") public String createHtml(int gid, HttpServletRequest request){ //通过商品id获得商品详细信息 Goods goods = goodsService.queryById(gid); String gimage = goods.getGimage(); String[] images = gimage.split("\\|"); //通过模板生成Html页面 try { //获得商品详情的模板对象 Template template = configuration.getTemplate("goodsitem.ftl"); //准备商品数据 Map<String, Object> map = new HashMap<>(); map.put("goods", goods); map.put("images", images); map.put("context", request.getContextPath()); //生成静态页 //获得classpath路径 //静态页的名称必须和商品有所关联,最简单的做法就是用商品id作为页面的名字 String path = this.getClass().getResource("/static/page/").getPath() + goods.getId() + ".html"; template.process(map, new FileWriter(path)); } catch (Exception e) { e.printStackTrace(); } return null; } }
true
f793c6e303e8905d1c07f6b7cdafa9cc02a511d7
Java
chaijewon/2020-12-22-JavaStudy
/20210121-예외처리(간접처리)/src/com/sist/main/MainClass2.java
UHC
1,782
2.90625
3
[]
no_license
package com.sist.main; /* * ȸ : ýۿ ó => throws * ) * ޼ҵ(Ű..) throws Ǵ .... * * ) * public void display() throws NumberFormatException,NullPointerException, * ClassCastException,Exception * ================================ * => display() ȣÿ * = ȸ * public void main() throws NumberFormatException,NullPointerException, * ClassCastException,Exception * { * display(); * } * * public void main() throws Exception * { * display() * } * * public void main() throws Throwable * { * display() * } * = * public void main() * { * try * { * display() * }catch(Exception ex){} * } */ // ̺귯 import java.io.*; public class MainClass2 { public void display() throws Exception,NumberFormatException,ArithmeticException,ArrayIndexOutOfBoundsException { } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub MainClass2 m=new MainClass2(); FileReader fr=new FileReader("c:\\javaDev\\movie.json"); } }
true
295a2a5034b429138f6e8924a85d6f2b0c879f1b
Java
biaostats/CS-417-IntroCS
/Recusions/src/RecursionExample.java
UTF-8
920
3.875
4
[]
no_license
public class RecursionExample { public static int factorial(int n) { System.out.println( "n is " + n ); if (n == 0) { System.out.println( "0!=1" ); return 1; } else { System.out.println( "need factorial of " + (n-1) ); int answer = factorial(n-1); System.out.println( "factorial of " + (n-1) + " is " + answer ); return answer * n; } } public static void count1(int n) { if (n >= 1) { System.out.println(n); count1(n-1); } } public static void count2(int n) { if (n >= 1) { count2(n-1); System.out.println(n); } } public static void main(String[] args) { /*System.out.println( "3!=" + factorial(3) );*/ count2(5); } }
true
c8c9569df48ceb28bf66bf04a44302a97d5cd911
Java
moon70717/test
/exam/src/p15/Exam.java
UTF-8
182
2.21875
2
[]
no_license
package p15; public class Exam { static String str="3"; public static void main(String[]args) { Exam e=new Exam(); Exam.str="33"; System.out.println(str); } }
true
2ed0fb1c22a0b521216638ad90560d30e35c417c
Java
jairodealmeida/easy-gpa
/MobileCore/src/br/com/core/services/communicator/Communicator.java
ISO-8859-1
2,956
2.0625
2
[]
no_license
package br.com.core.services.communicator; import java.util.List; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import br.com.core.services.http.HttpClientImpl; import br.com.core.session.Preferences; import br.com.core.util.ChronometerUtil; import br.com.core.util.Log; public abstract class Communicator { //private static ConfigParameters configParameters; public static String url_services; public static String ACTION; public static ChronometerUtil chronometerUtil = new ChronometerUtil(); static{ initParameters(); } public static void logout(HttpClientImpl httpclient) { try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, HttpClientImpl.TIMEOUT_CONNECTION); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, HttpClientImpl.TIMEOUT_SOCKET); httpclient.logout(httpclient,Communicator.url_services); } catch (Exception e) { Log.e("Falha ao tentar finalizar a sesso HTTP"); } } /** *Mtodo que executa o servio Rest do ServletController, *@param String - Nome do commando, referente classe extende Command para reflexo */ //public abstract List<Entity> execute(HttpClientImpl http,String methodName) throws Exception; /** *Mtodo que executa o servio Rest do ServletController, *@param String - Nome do commando, referente classe extende Command para reflexo *@param List<Usuario> elements - Lista de parametros se necessrio para o servio */ /*public abstract String uploadFoto(HttpClientImpl http, List<Foto> fotos) throws Exception ; public abstract List<Entity> execute(HttpClientImpl http,String methodName,String contentType) throws Exception ; public abstract List<Entity> execute(HttpClientImpl http,String methodName, List<Entity> elements) throws Exception; public abstract List<Entity> execute(HttpClientImpl http,String methodName, Entity entity) throws Exception; public abstract List<Entity> execute(HttpClientImpl http,String methodName, Collection requestCollection) throws Exception;*/ public static void initParameters(){ //url_services = "http://www.myzus.com.br/myzus-geo-connector-services"; //url_services = "http://jairodealmeida.zapto.org:8080/myzus-geo-connector-services"; StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("http://"); urlBuilder.append(Preferences.getServiceUrl()); if(Preferences.getPorta()!=null){ urlBuilder.append(":"); urlBuilder.append(Preferences.getPorta()); } urlBuilder.append("/"); urlBuilder.append(Preferences.getApplicationName()); url_services = urlBuilder.toString(); ACTION = "ServletController"; } }
true
766c641aa23372031ab8c9f53027a9e00d8849a2
Java
jonyeneho/635TRLProject
/TP_4_Onyeneho_Bicharge/tests/PatronTests.java
UTF-8
1,407
2.46875
2
[]
no_license
import static org.junit.Assert.*; import org.junit.Test; public class PatronTests { @Test public void testPatronFound() { String pid = "P102"; CopyPatronStore cpStore = new CopyPatronStore(); BorrowOutController outController = new BorrowOutController(cpStore); Patron p = outController.enterPatronForCheckOut(pid); assertNotNull(p); assertEquals(p, outController.enterPatronForCheckOut(pid)); assertFalse(p.getHasHold()); StdOut.println("Patron found."); } @Test public void testPatronNotFound() { String pid = "P109"; CopyPatronStore cpStore = new CopyPatronStore(); Patron p = cpStore.fetchPatrons(pid); BorrowOutController outController = new BorrowOutController(cpStore); outController.enterPatronForCheckOut(pid); p = outController.enterPatronForCheckOut(pid); assertNull(p); StdOut.println("Patron not found."); } @Test public void testPatronHasHold() { CopyPatronStore cpStore = new CopyPatronStore(); String pid = "P106"; Patron p = cpStore.fetchPatrons(pid); BorrowOutController outController = new BorrowOutController(cpStore); outController.enterPatronForCheckOut(pid); p = outController.enterPatronForCheckOut(pid); assertNotNull(p); assertTrue(p.getHasHold()); StdOut.println("Patron found but has a hold on record."); } }
true
e55a7a2e3407e26a708a8b0ed4d522597bf707c1
Java
qinxiaoyu123/OnJava8
/On_java/src/exceptions/ExceptionSilencer.java
UTF-8
346
3.140625
3
[]
no_license
package exceptions; public class ExceptionSilencer { public static void main(String []args){ try{ try{ throw new RuntimeException(); }finally { return; } } catch(RuntimeException e){ System.out.println("Caught it !"); } } }
true
8f6fc506bcb02476f472388bf5c6aea5e2e5e95f
Java
ralexandre11/restApiCpf
/src/main/java/com/ribeiro/restApiCpf/api/resource/PersonResource.java
UTF-8
2,881
2.40625
2
[]
no_license
package com.ribeiro.restApiCpf.api.resource; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ribeiro.restApiCpf.api.dto.PersonDTO; import com.ribeiro.restApiCpf.exception.MyRuleException; import com.ribeiro.restApiCpf.model.entity.Person; import com.ribeiro.restApiCpf.service.PersonService; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/api/person") @RequiredArgsConstructor public class PersonResource { private final PersonService service; @GetMapping public ResponseEntity search( @RequestParam(value = "name", required = false) String name, @RequestParam(value = "cpf", required = false) String cpf ) { Person personFilter = new Person(); personFilter.setName(name); personFilter.setCpf(cpf); List<Person> personList = service.searchPerson(personFilter); return ResponseEntity.ok(personList); } @PostMapping public ResponseEntity save( @RequestBody PersonDTO dto ) { try { Person person = convert(dto); Person personSaved = service.savePerson(person); return new ResponseEntity(personSaved, HttpStatus.CREATED); } catch (MyRuleException e) { return ResponseEntity.badRequest().body(e.getMessage()); } } @PutMapping("{id}") public ResponseEntity update( @PathVariable("id") Integer id, @RequestBody PersonDTO dto) { return service.getPersonByID(id).map(entity -> { try { Person person = convert(dto); person.setId(entity.getId()); Person personSaved = service.updatePerson(person); System.out.println(personSaved); return ResponseEntity.ok(person); } catch (Exception e) { return ResponseEntity.badRequest().body(e.getMessage()); } }).orElseGet( () -> new ResponseEntity("Registro inexistente!", HttpStatus.BAD_REQUEST )); } @DeleteMapping("{id}") public ResponseEntity delete( @PathVariable("id") Integer id) { return service.getPersonByID(id).map( entity -> { service.deletePerson(entity); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }).orElseGet( () -> new ResponseEntity("Registro inexistente!", HttpStatus.BAD_REQUEST )); } private Person convert(PersonDTO dto) { Person person = new Person(); person.setName(dto.getName()); person.setCpf(dto.getCpf()); return person; } }
true
f9b9abf9cb3a12e9e748601f18cd7dc6de952ed1
Java
balavart/JavaTraining
/6.Collections/src/ru/epam/balayan/tasksolution6/service/fileio/StrListReverse.java
UTF-8
453
2.484375
2
[]
no_license
package ru.epam.balayan.tasksolution6.service.fileio; import java.util.ArrayList; /** * Interface for reverse list of strings. * * @author Vardan Balayan * @version 1.8 * @created 15.09.2019 * @see SimpleStrListReverse implements */ public interface StrListReverse { /** * reverse strings. * * @param strList list of strings. * @return list of reversing strings. */ ArrayList<String> getListStrReverse(ArrayList<String> strList); }
true
bbd20376ae01745efc3c2d6a00d86d280a81cd23
Java
k2v-dev/datalogger_android_app
/HelmetStability/app/src/main/java/com/decalthon/helmet/stability/Fragments/CalendarPagerFragment.java
UTF-8
15,001
2.03125
2
[]
no_license
package com.decalthon.helmet.stability.fragments; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.widget.ViewPager2; import com.decalthon.helmet.stability.activities.MainActivity; import com.decalthon.helmet.stability.adapters.CalendarPagerAdapter; import com.decalthon.helmet.stability.database.SessionCdlDb; import com.decalthon.helmet.stability.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.concurrent.ExecutionException; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link CalendarPagerFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link CalendarPagerFragment#newInstance} factory method to * create an instance of this fragment. */ public class CalendarPagerFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private static final int NUM_PAGES = 10; private static final String ARG_PARAM3 = "param3"; // TODO: Rename and change types of parameters private String calendarType; private int calendarValue; private int clickedYear; private OnFragmentInteractionListener mListener; private ViewPager2 viewPager; private FragmentStateAdapter calendarPagerAdapter; private Context mContext; private View leftNavigationView; private View rightNavigationView; public CalendarPagerFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment YearPagerFragment. */ // TODO: Rename and change types and number of parameters public static CalendarPagerFragment newInstance(String param1, int param2, int mYearPassed) { CalendarPagerFragment fragment = new CalendarPagerFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putInt(ARG_PARAM2, param2); args.putInt(ARG_PARAM3,mYearPassed); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { calendarType = getArguments().getString(ARG_PARAM1); calendarValue = getArguments().getInt(ARG_PARAM2); clickedYear = getArguments().getInt(ARG_PARAM3); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_calendar_pager, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.back_navigation).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.shared().onBackPressed(); } }); List<Long> allSessionTimestamps = new ArrayList<>(); try { allSessionTimestamps = new GetAllSessionSummaryDatesAsyncTask().execute().get(); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } Date earliestSession = new Date( allSessionTimestamps.get(allSessionTimestamps.size() - 1) ); Date latestSession = new Date(allSessionTimestamps.get(0)); String earliestYear = new SimpleDateFormat("YYYY", Locale.getDefault()).format(earliestSession); String earliestMonth = new SimpleDateFormat("MM", Locale.getDefault()).format(earliestSession); String earliestDay = new SimpleDateFormat("dd", Locale.getDefault()).format(earliestSession); String latestYear = new SimpleDateFormat("YYYY", Locale.getDefault()).format(latestSession); String latestMonth = new SimpleDateFormat("MM", Locale.getDefault()).format(new Date()); String latestDay = new SimpleDateFormat("dd", Locale.getDefault()).format(latestSession); final int session_range_year = Integer.parseInt(latestYear) - Integer.parseInt(earliestYear); // int session_range_month = // Math.abs( ( session_range_year * 12 ) - Integer.parseInt(latestMonth) - Integer.parseInt(earliestMonth) ); int monthDiff = Integer.parseInt(latestMonth) - Integer.parseInt(earliestMonth); int earliestMonthIndex = Integer.parseInt(earliestMonth); final int session_range_month = (Math.abs( ( 12 * session_range_year ) + monthDiff)); viewPager = view.findViewById(R.id.calendar_pager); if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())){ calendarPagerAdapter = new CalendarPagerAdapter(this,getString(R.string.months), session_range_month + 1, allSessionTimestamps); viewPager.setAdapter(calendarPagerAdapter); }else if(calendarType.equals(YearlyCalendarFragment.class.getSimpleName())){ Fragment yearlyCalendarFragment = YearlyCalendarFragment.newInstance(calendarValue,Integer.parseInt(earliestYear)); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(this.getId(),yearlyCalendarFragment,CalendarPagerFragment.class.getSimpleName()); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); // calendarPagerAdapter = // new CalendarPagerAdapter(this,getString(R.string.years), // session_range_year + 1,allSessionTimestamps); } if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())) { if (calendarValue == -1) { viewPager.postDelayed(new Runnable() { @Override public void run() { viewPager.setCurrentItem(calendarPagerAdapter.getItemCount(), true); } }, 20); } else { viewPager.postDelayed(new Runnable() { @Override public void run() { int month_diff = (clickedYear - Integer.parseInt(earliestYear)) * 12 - (earliestMonthIndex - calendarValue); viewPager.setCurrentItem(month_diff + 1, true); } }, 20); } } viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { super.onPageSelected(position); registerPageLimits(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { super.onPageScrolled(position, positionOffset, positionOffsetPixels); Log.d("VIEWPAGER", "onPageScrolled: Page scrolled " +position); registerPageLimits(position); } }); // viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // super.onPageScrolled(position, positionOffset, positionOffsetPixels); // if (position == 0) { // MainActivity.shared().findViewById(R.id.left_month_pager).setVisibility(View.INVISIBLE); // } else { // MainActivity.shared().findViewById(R.id.left_month_pager).setVisibility(View.VISIBLE); // } // } // }); } private void registerPageLimits(int position){ if (position == 0) { if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())) { this.getView().findViewById(R.id.left_month_pager).setVisibility(View.INVISIBLE); }else if(calendarType.equals(YearlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.previous_year_link_vp).setVisibility(View.INVISIBLE); } } else { if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())) { this.getView().findViewById(R.id.left_month_pager).setVisibility(View.VISIBLE); } else if(calendarType.equals(YearlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.previous_year_link_vp).setVisibility(View.VISIBLE); } } if (position == calendarPagerAdapter.getItemCount() - 1) { if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.right_month_pager).setVisibility(View.INVISIBLE); } else if(calendarType.equals(YearlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.next_year_link_vp).setVisibility(View.INVISIBLE); } } else { if(calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.right_month_pager).setVisibility(View.VISIBLE); } else if(calendarType.equals(YearlyCalendarFragment.class.getSimpleName())){ this.getView().findViewById(R.id.next_year_link_vp).setVisibility(View.VISIBLE); } } if( calendarType.equals(MonthlyCalendarFragment.class.getSimpleName())){ leftNavigationView = this.getView().findViewById(R.id.left_month_pager); rightNavigationView = this.getView().findViewById(R.id.right_month_pager); leftNavigationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // View viewroot = view.getRootView(); // ViewPager2 viewPager2 = // (ViewPager2) viewroot.findViewById(R.id.calendar_pager); int currentPage = viewPager.getCurrentItem(); viewPager.setCurrentItem( currentPage - 1 ); } }); rightNavigationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // View viewroot = view.getRootView(); // ViewPager2 viewPager2 = // (ViewPager2) viewroot.findViewById(R.id.calendar_pager); int currentPage = viewPager.getCurrentItem(); viewPager.setCurrentItem( currentPage + 1 ); } }); }else{ leftNavigationView = this.getView().findViewById(R.id. previous_year_link_vp); rightNavigationView = this.getView().findViewById(R.id.next_year_link_vp); leftNavigationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // View viewroot = view.getRootView(); // ViewPager2 viewPager2 = // (ViewPager2) viewroot.findViewById(R.id.calendar_pager); int currentPage = viewPager.getCurrentItem(); viewPager.setCurrentItem( currentPage - 1 ); } }); rightNavigationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // View viewroot = view.getRootView(); // ViewPager2 viewPager2 = // (ViewPager2) viewroot.findViewById(R.id.calendar_pager); int currentPage = viewPager.getCurrentItem(); viewPager.setCurrentItem( currentPage + 1 ); } }); } } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } public String getCalendarType(){ return calendarType; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; mContext = context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private static class GetAllSessionSummaryDatesAsyncTask extends AsyncTask<Void, Void, List<Long>> { @Override protected List<Long> doInBackground(Void... voids) { return SessionCdlDb.getInstance().getSessionDataDAO().getTimestampsFromSessionSummary(); } } }
true
e66692007aa7f5159a0bf685738df1781398724f
Java
DenisProkhorov/qa-automation-java
/app/src/main/java/com/tinkoff/edu/app/repository/DynamicLoanCalcRepository.java
UTF-8
483
2.4375
2
[]
no_license
package com.tinkoff.edu.app.repository; import com.tinkoff.edu.app.model.LoanRequest; public class DynamicLoanCalcRepository implements LoanCalcRepository { private int requestId; public DynamicLoanCalcRepository(int requestId){ this.requestId=requestId; } public DynamicLoanCalcRepository(){ this(0); } /** * TODO persists request */ @Override public int save(LoanRequest request) { return ++requestId; } }
true
1eddc86b0d10a13802ac2e2fae853f88a8c590bf
Java
noceravictor/projetosbs
/fj21-agenda/src/br/com/caelum/mvc/logica/BuscaContatoLogic.java
UTF-8
709
2.21875
2
[]
no_license
package br.com.caelum.mvc.logica; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.caelum.agenda.dao.ContatoDao; import br.com.caelum.agenda.modelo.Contato; public class BuscaContatoLogic implements Logica{ @Override public String executa(HttpServletRequest req, HttpServletResponse resp) throws Exception { long id = Long.parseLong(req.getParameter("id")); ContatoDao dao = new ContatoDao(); Contato contato = dao.busca(id); req.setAttribute("contatoBusca", contato); return "altera-contato.jsp"; } }
true
761bf7ec3f213022bab1926530635c1c310cc170
Java
maisamali/coinbase_decompile
/src/main/java/com/coinbase/android/deposits/fiat/WithdrawFiatPresenter$$Lambda$6.java
UTF-8
533
1.640625
2
[]
no_license
package com.coinbase.android.deposits.fiat; import android.util.Pair; import rx.functions.Func1; final /* synthetic */ class WithdrawFiatPresenter$$Lambda$6 implements Func1 { private static final WithdrawFiatPresenter$$Lambda$6 instance = new WithdrawFiatPresenter$$Lambda$6(); private WithdrawFiatPresenter$$Lambda$6() { } public static Func1 lambdaFactory$() { return instance; } public Object call(Object obj) { return WithdrawFiatPresenter.lambda$hookUpKeypad$5((Pair) obj); } }
true
fc45f53f6f2a8db1fe0714430802e2b2ab5291d6
Java
arraycto/dh_trade_manage
/dh_trade_manage_dao/src/main/java/com/giao/ssm/dao/ExportProductCDao.java
UTF-8
6,501
2.15625
2
[]
no_license
package com.giao.ssm.dao; import com.giao.ssm.domain.ExportProductC; import org.apache.ibatis.annotations.*; import org.apache.ibatis.mapping.FetchType; import java.util.List; /** * @program: oracle-ssm * @description * @author: 影耀子(YingYew) * @create: 2020-10-11 22:32 * 报运商品明细dao **/ public interface ExportProductCDao { /** * 添加报运商品明细 * @param ep */ @Insert("insert into EXPORT_PRODUCT_C(EXPORT_PRODUCT_ID,CONTRACT_PRODUCT_ID,EXPORT_ID,FACTORY_ID,CONTRACT_ID," + "CONTRACT_NO,PRODUCT_NAME,PRODUCT_NO,PRODUCT_IMAGE,PRODUCT_DESC," + "LOADING_RATE,PACKING_UNIT,CNUMBER,OUT_NUMBER,FINISHED," + "GROSS_WEIGHT,NET_WEIGHT,SIZE_LENGHT,SIZE_WIDTH,SIZE_HEIGHT," + "PRODUCT_REQUEST,FACTORY,PRICE,AMOUNT,CUNIT," + "BOX_NUM,EX_PRICE,EX_UNIT,NO_TAX,TAX," + "COST_PRICE,COST_TAX,ACCESSORIES,ORDER_NO)" + " values(#{exportProductId,jdbcType=VARCHAR},#{contractProductId,jdbcType=VARCHAR},#{exportId,jdbcType=VARCHAR},#{factoryId,jdbcType=VARCHAR},#{contractId,jdbcType=VARCHAR}," + "#{contractNo,jdbcType=VARCHAR},#{productName,jdbcType=VARCHAR},#{productNo,jdbcType=VARCHAR},#{productImage,jdbcType=VARCHAR},#{productDesc,jdbcType=VARCHAR}," + "#{loadingRate,jdbcType=VARCHAR},#{packingUnit,jdbcType=VARCHAR},#{cnumber,jdbcType=INTEGER},#{outNumber,jdbcType=INTEGER},#{finished,jdbcType=INTEGER}," + "#{grossWeight,jdbcType=DOUBLE},#{netWeight,jdbcType=DOUBLE},#{sizeLenght,jdbcType=DOUBLE},#{sizeWidth,jdbcType=DOUBLE},#{sizeHeight,jdbcType=DOUBLE}," + "#{productRequest,jdbcType=VARCHAR},#{factory,jdbcType=VARCHAR},#{price,jdbcType=DOUBLE},#{amount,jdbcType=DOUBLE},#{cunit,jdbcType=VARCHAR}," + "#{boxNum,jdbcType=INTEGER},#{exPrice,jdbcType=DOUBLE},#{exUnit,jdbcType=VARCHAR},#{noTax,jdbcType=DOUBLE},#{tax,jdbcType=DOUBLE}," + "#{costPrice,jdbcType=DOUBLE},#{costTax,jdbcType=DOUBLE},#{accessories,jdbcType=INTEGER},#{orderNo,jdbcType=INTEGER})") void insert(ExportProductC ep); /** * 根据外键查询ExportProductC(报运商品明细) * @param exportId * @return */ @Select("select * from EXPORT_PRODUCT_C where EXPORT_ID = #{exportId}") @Results(id = "ExportProductCAllMap", value = { @Result(id = true,column = "EXPORT_PRODUCT_ID",property = "exportProductId"), @Result(column = "CONTRACT_PRODUCT_ID",property = "contractProductId"), @Result(column = "EXPORT_ID",property = "exportId"), @Result(column = "FACTORY_ID",property = "factoryId"), @Result(column = "CONTRACT_ID",property = "contractId"), @Result(column = "CONTRACT_NO",property = "contractNo"), @Result(column = "PRODUCT_NAME",property = "productName"), @Result(column = "PRODUCT_NO",property = "productNo"), @Result(column = "PRODUCT_IMAGE",property = "productImage"), @Result(column = "PRODUCT_DESC",property = "productDesc"), @Result(column = "LOADING_RATE",property = "loadingRate"), @Result(column = "PACKING_UNIT",property = "packingUnit"), @Result(column = "CNUMBER",property = "cnumber"), @Result(column = "OUT_NUMBER",property = "outNumber"), @Result(column = "FINISHED",property = "finished"), @Result(column = "GROSS_WEIGHT",property = "grossWeight"), @Result(column = "NET_WEIGHT",property = "netWeight"), @Result(column = "SIZE_LENGHT",property = "sizeLenght"), @Result(column = "SIZE_WIDTH",property = "sizeWidth"), @Result(column = "SIZE_HEIGHT",property = "sizeHeight"), @Result(column = "PRODUCT_REQUEST",property = "productRequest"), @Result(column = "FACTORY",property = "factory"), @Result(column = "PRICE",property = "price"), @Result(column = "AMOUNT",property = "amount"), @Result(column = "CUNIT",property = "cunit"), @Result(column = "BOX_NUM",property = "boxNum"), @Result(column = "EX_PRICE",property = "exPrice"), @Result(column = "EX_UNIT",property = "exUnit"), @Result(column = "NO_TAX",property = "noTax"), @Result(column = "TAX",property = "tax"), @Result(column = "COST_PRICE",property = "costPrice"), @Result(column = "COST_TAX",property = "costTax"), @Result(column = "ACCESSORIES",property = "accessories"), @Result(column = "ORDER_NO",property = "orderNo"), @Result(property = "exportC",column = "EXPORT_ID",one = @One(select = "com.giao.ssm.dao.ExportCDao.findById",fetchType = FetchType.EAGER)), @Result(property = "factoryC",column = "FACTORY_ID",one = @One(select = "com.giao.ssm.dao.FactoryCDao.findFactorycById",fetchType = FetchType.EAGER)), }) List<ExportProductC> findByExportId(String exportId); /** * 根据主键查询一个 * @param s * @return */ @Select("select * from EXPORT_PRODUCT_C where EXPORT_PRODUCT_ID = #{exportProductId}") @ResultMap("ExportProductCAllMap") ExportProductC findById(String exportProductId); /** * 修改报运商品明细(货物信息) * @param ep */ @Update({ "<script>", "update EXPORT_PRODUCT_C " + "<set>" + "<if test='orderNo!=null'>ORDER_NO=#{orderNo,jdbcType=INTEGER},</if> " + "<if test='cnumber!=null'>CNUMBER=#{cnumber,jdbcType=INTEGER},</if> " + "<if test='grossWeight!=null'>GROSS_WEIGHT=#{grossWeight,jdbcType=DOUBLE},</if> " + "<if test='netWeight!=null'>NET_WEIGHT=#{netWeight,jdbcType=DOUBLE},</if> " + "<if test='sizeLenght!=null'>SIZE_LENGHT=#{sizeLenght,jdbcType=DOUBLE},</if> " + "<if test='sizeWidth!=null'>SIZE_WIDTH=#{sizeWidth,jdbcType=DOUBLE},</if> " + "<if test='sizeHeight!=null'>SIZE_HEIGHT=#{sizeHeight,jdbcType=DOUBLE},</if> " + "<if test='exPrice!=null'>EX_PRICE=#{exPrice,jdbcType=DOUBLE},</if> " + "<if test='tax!=null'>TAX=#{tax,jdbcType=DOUBLE},</if> " + "</set>" + " where EXPORT_PRODUCT_ID=#{exportProductId}", "</script>" }) void updateExportProductC(ExportProductC ep); }
true
f4d9317b1ded1cd79ba9c77f2c16e3ba6905ac05
Java
Retera/WarsmashModEngine
/core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/behaviors/CAbstractRangedBehavior.java
UTF-8
3,588
2.5
2
[ "MIT", "GPL-1.0-or-later" ]
permissive
package com.etheller.warsmash.viewer5.handlers.w3x.simulation.behaviors; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CSimulation; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnit; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.targeting.AbilityTarget; public abstract class CAbstractRangedBehavior implements CRangedBehavior { protected final CUnit unit; public CAbstractRangedBehavior(final CUnit unit) { this.unit = unit; } protected AbilityTarget target; private boolean wasWithinPropWindow = false; private boolean wasInRange = false; private boolean disableMove = false; private CBehaviorMove moveBehavior; protected final CAbstractRangedBehavior innerReset(final AbilityTarget target) { return innerReset(target, false); } protected final CAbstractRangedBehavior innerReset(final AbilityTarget target, final boolean disableCollision) { this.target = target; this.wasWithinPropWindow = false; this.wasInRange = false; CBehaviorMove moveBehavior; if (!this.unit.isMovementDisabled()) { moveBehavior = this.unit.getMoveBehavior().reset(this.target, this, disableCollision); } else { moveBehavior = null; } this.moveBehavior = moveBehavior; return this; } protected abstract CBehavior update(CSimulation simulation, boolean withinFacingWindow); protected abstract CBehavior updateOnInvalidTarget(CSimulation simulation); protected abstract boolean checkTargetStillValid(CSimulation simulation); protected abstract void resetBeforeMoving(CSimulation simulation); @Override public final CBehavior update(final CSimulation simulation) { if (!checkTargetStillValid(simulation)) { return updateOnInvalidTarget(simulation); } if (!isWithinRange(simulation)) { if ((this.moveBehavior == null) || this.disableMove) { return this.unit.pollNextOrderBehavior(simulation); } this.wasInRange = false; resetBeforeMoving(simulation); return this.unit.getMoveBehavior(); } this.wasInRange = true; if (!this.unit.isMovementDisabled()) { final float prevX = this.unit.getX(); final float prevY = this.unit.getY(); final float deltaX = this.target.getX() - prevX; final float deltaY = this.target.getY() - prevY; final double goalAngleRad = Math.atan2(deltaY, deltaX); float goalAngle = (float) Math.toDegrees(goalAngleRad); if (goalAngle < 0) { goalAngle += 360; } float facing = this.unit.getFacing(); float delta = goalAngle - facing; final float propulsionWindow = simulation.getGameplayConstants().getAttackHalfAngle(); final float turnRate = simulation.getUnitData().getTurnRate(this.unit.getTypeId()); if (delta < -180) { delta = 360 + delta; } if (delta > 180) { delta = -360 + delta; } final float absDelta = Math.abs(delta); if ((absDelta <= 1.0) && (absDelta != 0)) { this.unit.setFacing(goalAngle); } else { float angleToAdd = Math.signum(delta) * (float) Math.toDegrees(turnRate); if (absDelta < Math.abs(angleToAdd)) { angleToAdd = delta; } facing += angleToAdd; this.unit.setFacing(facing); } if (absDelta < propulsionWindow) { this.wasWithinPropWindow = true; } else { // If this happens, the unit is facing the wrong way, and has to turn before // moving. this.wasWithinPropWindow = false; } } else { this.wasWithinPropWindow = true; } return update(simulation, this.wasWithinPropWindow); } public void setDisableMove(final boolean disableMove) { this.disableMove = disableMove; } }
true
663d94f49819187233dd7aca4db884c690d8b326
Java
allynanelia/IoT
/app/src/main/java/com/walkPark/walkinthepark/activities/SplashActivity.java
UTF-8
1,055
1.9375
2
[]
no_license
package com.walkPark.walkinthepark.activities; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import com.walkPark.walkinthepark.R; import com.walkPark.walkinthepark.WalkInTheParkGson; import com.walkPark.walkinthepark.backend.RouteInterface; import com.walkPark.walkinthepark.backend.WalkInTheParkRetrofit; import com.walkPark.walkinthepark.models.RouteResponse; import org.jetbrains.annotations.Nullable; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Boon Sing on 01-Mar-18. */ public class SplashActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(SplashActivity.this, TransitActivity.class)); finish(); } },1000); } }
true
6667956e8a0ac588bce8861056d7954312f44526
Java
edubossa/gcloud-pubsub
/src/main/java/br/com/hdi/hdipubsub/PubsubController.java
UTF-8
530
1.773438
2
[]
no_license
package br.com.hdi.hdipubsub; 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; @RestController @RequestMapping("/cloudpubsub") public class PubsubController { @Autowired private HDIPubsubRepository repository; @GetMapping public Iterable<HDIPubsub> getAll() { return this.repository.findAll(); } }
true
7a1b22f90af979200d84aaf7c91a2af6bcf277a4
Java
MedaniGunathilaka/Simple_Java_Codes
/Day 11/Calculation.java
UTF-8
604
3.125
3
[]
no_license
package calc; import arithmeticCalculator.*; import java.util.Scanner; public class Calculation{ public static void main(String args[]){ Scanner scan=new Scanner(System.in); System.out.print("Enter first number: "); int num1 = scan.nextInt(); System.out.print("Enter second number: "); int num2 = scan.nextInt(); arithmeticCalculator.SimpleArithmeticCalculator vall=new arithmeticCalculator.SimpleArithmeticCalculator(); vall.add(num1,num2); vall.substract(num1,num2); vall.division(num1,num2); vall.multiplication(num1,num2); } }
true
6a9be1eccd5808eef00b317355c2a16372d78f5f
Java
MarlinMatta/gamify
/src/main/java/edu/uapa/web/app/gamify/controllers/security/ParameterController.java
UTF-8
3,385
2.234375
2
[]
no_license
package edu.uapa.web.app.gamify.controllers.security; import edu.uapa.web.app.gamify.domains.securities.Parameter; import edu.uapa.web.app.gamify.services.securities.ParameterService; import edu.uapa.web.app.gamify.utils.Urls; import edu.utesa.lib.models.dtos.security.ParamDto; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping(value = Urls.APP_PARAMETER) public class ParameterController { private final ParameterService service; public ParameterController(ParameterService service) { this.service = service; } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<ParamDto>> get(@RequestParam String page, @RequestParam String size, @RequestParam String filterValue) { long start = System.currentTimeMillis(); List<ParamDto> result = service.findAll(PageRequest.of(Integer.parseInt(page), Integer.parseInt(size)), "%" + filterValue + "%").stream().map(Parameter::toDto).collect(Collectors.toList()); System.out.println("Parameter Get Total Time: " + (System.currentTimeMillis() - start)); return new ResponseEntity<>(result, HttpStatus.OK); } @RequestMapping(value = Urls.COUNT, method = RequestMethod.GET) public ResponseEntity<Long> count(@RequestParam String filterValue) { long start = System.currentTimeMillis(); Long result = service.count("%" + filterValue + "%"); System.out.println("Parameter Count Total Time: " + (System.currentTimeMillis() - start)); return new ResponseEntity<>(result, HttpStatus.OK); } @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<ParamDto> update(@RequestBody ParamDto paramDto) { long start = System.currentTimeMillis(); if (service.bootStrap(Parameter.toDomain(paramDto)) != null) { return new ResponseEntity<>(HttpStatus.ACCEPTED); } System.out.println("Parameter Update Total Time: " + (System.currentTimeMillis() - start)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<ParamDto> save(@RequestBody ParamDto paramDto) { long start = System.currentTimeMillis(); if (service.bootStrap(Parameter.toDomain(paramDto)) != null) { return new ResponseEntity<>(HttpStatus.CREATED); } System.out.println("Parameter Save Total Time: " + (System.currentTimeMillis() - start)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @RequestMapping(method = RequestMethod.DELETE) public ResponseEntity update(@RequestParam String id) { long start = System.currentTimeMillis(); service.softDelete(Long.parseLong(id)); System.out.println("Parameter Delete Total Time: " + (System.currentTimeMillis() - start)); return new ResponseEntity<>(HttpStatus.OK); } }
true
8e24c5a1ab3b942454be8b81832e303fcd0d3ada
Java
aoyongjx/mscloud
/cloudalibaba-consumer-nacos-order84/src/main/java/com/alen/springcloud/service/PaymentFallbackService.java
UTF-8
544
2.015625
2
[]
no_license
package com.alen.springcloud.service; import com.alen.springcloud.entities.CommonResult; import com.alen.springcloud.entities.Payment; import org.springframework.stereotype.Component; /** * @Description: $ * @Param: $ * @return: $ * @Author: alen.ao * @date: $ */ @Component public class PaymentFallbackService implements PaymentService { @Override public CommonResult<Payment> paymentSQL(Long id) { return new CommonResult<>(44444,"服务降级返回-->PaymentFallbackService",new Payment(id,"errorService")); } }
true
eded8fb7473d2e3e2c9f6e550fbf28dff0fa15ce
Java
Senjoey/Express-Logistics-Information-System
/express-all-1-2-4/model/src/main/java/impl/financeImpl/PaymentFormServiceClientImpl.java
UTF-8
2,896
2.40625
2
[]
no_license
package impl.financeImpl; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import dataservice.financedataservice.PaymentFormdataService; import iohelper.IOHelper; import po.PaymentFormPO; public class PaymentFormServiceClientImpl extends UnicastRemoteObject implements PaymentFormdataService{ /** * */ private static final long serialVersionUID = 1L; FileInputStream inOne; ObjectInputStream inTwo; FileOutputStream outOne; ObjectOutputStream outTwo; @SuppressWarnings("rawtypes") Hashtable allPaymentForm; File file = new File("付款单基本信息.txt"); IOHelper ioHelper; public PaymentFormServiceClientImpl() throws RemoteException { super(); // TODO Auto-generated constructor stub } public PaymentFormPO find(String NO) throws RemoteException { System.out.println("Find PaymentFormPO Start!!"); ioHelper = new IOHelper(); allPaymentForm= ioHelper.readFromFile(file); if(allPaymentForm.containsKey(NO)) { PaymentFormPO po = (PaymentFormPO) allPaymentForm.get(NO); System.out.println(po.getNO()); System.out.println("Find PaymentFormPO Over!!"); return po; }else{ System.out.print("exception"); } return null; } @SuppressWarnings("unchecked") public void insert(PaymentFormPO po) throws RemoteException { System.out.println("Insert ReceiptFormPO Start!!"); ioHelper = new IOHelper(); allPaymentForm = ioHelper.readFromFile(file); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); System.out.println(df.format(new Date())); po.setNO(df.format(new Date())); allPaymentForm.put(po.getNO(), po); System.out.println(po.getNO()); ioHelper.writeToFile(allPaymentForm, file); System.out.println("Add ReceiptFormPO Over!!"); } public void delete(PaymentFormPO po) throws RemoteException { // TODO Auto-generated method stub System.out.println("Delete ReceiptFormPO Start!!"); if(po==null){ throw new IllegalArgumentException(); } ioHelper = new IOHelper(); allPaymentForm = ioHelper.readFromFile(file); System.out.println(po.getNO() ); allPaymentForm.remove(po.getNO()); ioHelper.writeToFile(allPaymentForm, file); } public void update(PaymentFormPO po) throws RemoteException { // TODO Auto-generated method stub System.out.println("Update PaymentFormPO Start!!"); if(po==null){ throw new IllegalArgumentException(); }else{ insert(po); } System.out.println("update over!"); } @Override public ArrayList<PaymentFormPO> findAll() throws RemoteException { // TODO Auto-generated method stub return null; } }
true
d47455be0d8f0f807ef2db242dae42638d734930
Java
Claudiocia/SmartEnem1
/app/src/main/java/br/com/ciadeideias/smartenem/fragments/DisciplinasCardFragment.java
UTF-8
3,281
2.25
2
[]
no_license
package br.com.ciadeideias.smartenem.fragments; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import br.com.ciadeideias.smartenem.DisciplinasCardActivity; import br.com.ciadeideias.smartenem.R; import br.com.ciadeideias.smartenem.adapter.DisciplinasCardAdapter; import br.com.ciadeideias.smartenem.interfaces.RecyclerViewOnClickListenerHack; import br.com.ciadeideias.smartenem.model.NomeDisciplina; public class DisciplinasCardFragment extends Fragment implements RecyclerViewOnClickListenerHack { private RecyclerView mRecyclerView; private List<NomeDisciplina> mList; private int idDiscipli; @SuppressLint("WrongConstant") @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_card_disciplinas, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_card_disciplinas); mRecyclerView.setHasFixedSize(true); mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager(); DisciplinasCardAdapter adapter = (DisciplinasCardAdapter) mRecyclerView.getAdapter(); if (mList.size() == llm.findLastCompletelyVisibleItemPosition() + 1){ List<NomeDisciplina> listAux = ((DisciplinasCardActivity) getActivity()).getListaDisciplinaCard(0); for (int i = 0; i < listAux.size(); i++) { adapter.addListItem(listAux.get(i), mList.size()); } } } }); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(llm); mList = ((DisciplinasCardActivity) getActivity()).getListaDisciplinaCard(3); DisciplinasCardAdapter adapter = new DisciplinasCardAdapter(getActivity(), mList); adapter.setRecyclerViewOnClickListenerHack(this); mRecyclerView.setAdapter(adapter); return view; } @Override public void onClickListener(View view, int position) { idDiscipli = mList.get(position).getIdDisciplina(); Toast.makeText(getActivity(), "Position: "+position+ " O id dela é "+ idDiscipli, Toast.LENGTH_SHORT).show(); } }
true
c53cabe6f547bc2d49167b754459c50d9297af9c
Java
oudaykhaled/iot-pipe-root
/extra/EvalModule.java
UTF-8
3,200
2.265625
2
[]
no_license
package org.hobbit.sdk.iotpipeline_bm.benchmark; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.vocabulary.RDF; import org.hobbit.core.components.AbstractEvaluationModule; import org.hobbit.core.rabbit.RabbitMQUtils; import org.hobbit.sdk.iotpipeline_bm.Constants; import org.hobbit.vocab.HOBBIT; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class EvalModule extends AbstractEvaluationModule { private Property EXECUTION_TIME = null; private Property NUM_OF_TASK_FAILURES = null; private Model model = ModelFactory.createDefaultModel(); private static final Logger logger = LoggerFactory.getLogger(EvalModule.class); @Override protected void evaluateResponse(byte[] expectedData, byte[] receivedData, long taskSentTimestamp, long responseReceivedTimestamp) throws Exception { // evaluate the given response and store the result, e.g., increment internal counters logger.trace("evaluateResponse()"); final String TRUE_RESPONSE = "/correct/"; final String FALSE_RESPONSE = "/wrong/"; Long expectedExecutionTime = RabbitMQUtils.readLong(expectedData); Long receivedExecutionTime = RabbitMQUtils.readLong(receivedData); /* if (receivedScore >= FACTCHECK_THRESHOLD) receivedResponse = TRUE_RESPONSE; else receivedResponse = FALSE_RESPONSE; */ } @Override public void init() throws Exception { super.init(); Map<String, String> env = System.getenv(); if (!env.containsKey(Constants.EXECUTION_TIME)) { throw new IllegalArgumentException("Couldn't get \"" + Constants.EXECUTION_TIME + "\" from the environment. Aborting."); } EXECUTION_TIME = this.model.createProperty(env.get(Constants.EXECUTION_TIME)); if (!env.containsKey(Constants.NUM_OF_TASK_FAILURES)) { throw new IllegalArgumentException("Couldn't get \"" + Constants.NUM_OF_TASK_FAILURES + "\" from the environment. Aborting."); } NUM_OF_TASK_FAILURES = this.model.createProperty(env.get(Constants.NUM_OF_TASK_FAILURES)); } @Override protected Model summarizeEvaluation() throws Exception { logger.debug("summarizeEvaluation()"); // All tasks/responsens have been evaluated. Summarize the results, // write them into a Jena model and send it to the benchmark controller. Model model = createDefaultModel(); Resource experimentResource = model.getResource(experimentUri); model.add(experimentResource , RDF.type, HOBBIT.Experiment); logger.debug("Sending result model: {}", RabbitMQUtils.writeModel2String(model)); return model; } @Override public void close(){ // Free the resources you requested here logger.debug("close()"); // Always close the super class after yours! try { super.close(); } catch (Exception e){ } } }
true
0f87c22ef641fa01d6f57bde81b736596c8a9abe
Java
mixophrygian/Sedgewick-1.3
/Taxi.java
UTF-8
527
3.578125
4
[]
no_license
public class Taxi { public static void main(String[] args) { int n = Integer.parseInt(args[0]); for(int count = 9; count <= n; count++){ int twice = 0; for(int i = 1; i < count; i++){ double firstHalf = Math.pow(i, 3); for(int j = i + 1; j < count; j++){ double secondHalf = Math.pow(j, 3); if(firstHalf + secondHalf == count){ twice++; if(twice == 2) System.out.println(count + " is the sum of two distinct sets of cubes"); } } } } } }
true
eeda6e1ecee9e7ac7482e0592e8d4def1009abfa
Java
reshi2998/Ordering-Pizza
/src/java/proyecto2/modelo/Extras.java
UTF-8
1,676
2.78125
3
[]
no_license
package proyecto2.modelo; import java.io.Serializable; import org.json.JSONObject; // Extras.java // // EIF209 - Programación 4 - Proyecto #2 // Junio 2020 // // Autores: // - 207950788 Sara Moraga Alfaro // - 116980485 Scarleth Villarreal Jímenez // - 117250099 Josué Víquez Campos public class Extras implements Serializable{ public Extras(int idExtras, String nombre, double precio, boolean disponible) { this.idExtras = idExtras; this.nombre = nombre; this.precio = precio; this.disponible = disponible; } public Extras() { this(0, "", 0.0, true); } @Override public String toString() { return toJSON().toString(4); } public JSONObject toJSON() { JSONObject r = new JSONObject(); r.put("idExtras", getIdExtras()); r.put("nombre", getNombre()); r.put("precio", getPrecio()); r.put("disponible", getDisponible()); return r; } public int getIdExtras() { return idExtras; } public void setIdExtras(int idExtras) { this.idExtras = idExtras; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } public boolean getDisponible() { return disponible; } public void setDisponible(boolean disponible) { this.disponible = disponible; } private int idExtras; private String nombre; private double precio; private boolean disponible; }
true
a3f3b4a44268b8dfa916133aae4218d52cb90a40
Java
shiprakumari/JDBC_projects
/New folder/11-Assignment3/src/com/capgemini/ui/FeeDetails.java
UTF-8
1,111
2.328125
2
[]
no_license
package com.capgemini.ui; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class FeeDetails { @Id @Column(name="Fee_ID") @GeneratedValue(strategy=GenerationType.AUTO) private int feeId; @Column(name="Total_Fee") private double totalFee; @Column(name="Installments") private int noOfInstallment; @OneToOne(mappedBy= "feeDetails") private Course course; public int getFeeId() { return feeId; } public void setFeeId(int feeId) { this.feeId = feeId; } public double getTotalFee() { return totalFee; } public void setTotalFee(double totalFee) { this.totalFee = totalFee; } public int getNoOfInstallment() { return noOfInstallment; } public void setNoOfInstallment(int noOfInstallment) { this.noOfInstallment = noOfInstallment; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } }
true
6768c0f259547ca213738dba1c4304643ffe5d48
Java
jwc318/CSE2
/lab12/ArrayMath.java
UTF-8
2,497
3.28125
3
[]
no_license
//Joey Carney //11/12/14 //lab12--ArrayMath public class ArrayMath{ public static void main(String [] arg){ double x[]={2.3, 3, 4, -2.1, 82, 23}, y[]={2.3, 3, 4, -2.1, 82, 23}, z[]={2.3, 13, 14}, w[]={2.3, 13, 14, 12}, v[], u[]={2.3, 12, 14}; v=addArrays(x,y); System.out.println(display(x)+" \n + " + display(y) + "\n = " +display(v)); System.out.println(display(x)+" \n + " + display(z) + "\n = " +display(addArrays(x,z))); System.out.println("It is " + equals(x,y)+" that "+display(x)+ " == "+display(y)); System.out.println("It is " + equals(z,w)+" that "+display(z)+ " == "+display(w)); System.out.println("It is " + equals(u,z)+" that "+display(u)+ " == "+display(z)); } public static String display(double [] x){ String out="{"; for(int j=0;j<x.length;j++){ if(j>0){ out+=", "; } out+=x[j]; } return out+"}"; } public static boolean equals(double [] a, double [] b) { int length_a = a.length; int length_b = b.length; if(length_a == length_b) { for(int i = 0; i < length_a; i++) { if(a[i] == b[i]) { continue; } else { return false; } } return true; } return false; } public static double[] addArrays(double [] a, double [] b) { int length_a = a.length; int length_b = b.length; int max; if(length_a > length_b) { max = length_b; } else { max = length_a; } double [] sum = new double[6]; if(length_a == length_b) { for(int j = 0; j < length_a; j++) { sum[j] = a[j] + b[j]; } } else { for(int k = 0; k < max; k++) { sum[k] = a[k] + b[k]; if(length_b > length_a) { for(int m = length_a; m < length_b; m++) { sum[m] = b[m]; } } else { for(int n = length_b; n < length_a; n++) { sum[n] = a[n]; } } } } return sum; } }
true
ab97dfb56c7d4ebc2bb14208de4a15b9a4927fb2
Java
guoshengli/car-friend
/src/main/java/com/friend/rest/dao/InterestDao.java
UTF-8
225
1.625
2
[]
no_license
package com.friend.rest.dao; import java.util.List; import com.friend.rest.model.Interest; public interface InterestDao extends BaseDao<Interest, Long> { public List<Interest> getInterestListBySequence(); }
true
6686ef50bff67fd38b9e461c2c35affd9c8579ff
Java
jjfiv/coop
/src/main/java/edu/umass/cs/jfoley/coop/index/corpus/AbstractCorpusReader.java
UTF-8
2,424
2.703125
3
[ "BSD-3-Clause" ]
permissive
package edu.umass.cs.jfoley.coop.index.corpus; import ciir.jfoley.chai.collections.Pair; import ciir.jfoley.chai.collections.util.ListFns; import ciir.jfoley.chai.fn.SinkFn; import edu.umass.cs.jfoley.coop.querying.TermSlice; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author jfoley */ public abstract class AbstractCorpusReader implements Closeable { public abstract List<String> pullTokens(int document); /** * Raw access to corpus structure. * @param slice the coordinates of the data to pull. * @return a list of term ids corresponding to the data in the given slice. */ public List<String> pullTokens(TermSlice slice) { // Inefficient if you have a tiled corpus, but a good default impl. return new ArrayList<>( ListFns.slice( pullTokens(slice.document), slice.start, slice.end)); } /** * Only pull each document once. */ public List<Pair<TermSlice, List<String>>> pullTermSlices(List<TermSlice> requests) throws IOException { // sort by document. Collections.sort(requests); // cache a document a time in memory so we don't pull it twice. List<String> currentDocTerms = null; int currentDocId = -1; // slices: List<List<String>> slices = new ArrayList<>(); for (TermSlice request : requests) { if(request.document != currentDocId) { currentDocId = request.document; currentDocTerms = pullTokens(currentDocId); } // make a copy here so that the documents don't end up leaked into memory via subList. slices.add(new ArrayList<>(ListFns.slice(currentDocTerms, request.start, request.end))); } return ListFns.zip(requests, slices); } public void forTermInSlice(List<TermSlice> requests, SinkFn<String> onTerm) { // sort by document. Collections.sort(requests); // cache a document a time in memory so we don't pull it twice. List<String> currentDocTerms = null; int currentDocId = -1; // slices: for (TermSlice request : requests) { if(request.document != currentDocId) { currentDocId = request.document; currentDocTerms = pullTokens(currentDocId); } for (String term : ListFns.slice(currentDocTerms, request.start, request.end)) { onTerm.process(term); } } } }
true
1005ec736ce22bea876a25969bfdf95d5280c556
Java
LoweKumar/Demo-Repo
/composition/src/composition/laptop/components/Processors.java
UTF-8
560
2.453125
2
[]
no_license
package composition.laptop.components; public class Processors { private String brands; private String series; public Processors() { this.brands="HP"; this.series="7th series"; } public Processors(String brands, String series) { //super(); this.brands = brands; this.series = series; } @Override public String toString() { return "Processors [brands=" + brands + ", series=" + series + "]"; } public String getBrands() { return brands; } public String getSeries() { return series; } }
true
c9869e1e892c302c6507a16c8a82c4e527f3a6c5
Java
flipkart-incubator/arts
/component-testing-core/src/main/java/com/flipkart/component/testing/HttpTestOrchestrator.java
UTF-8
2,597
2.53125
3
[ "Apache-2.0" ]
permissive
package com.flipkart.component.testing; import com.fasterxml.jackson.databind.ObjectMapper; import com.flipkart.component.testing.model.Observation; import com.flipkart.component.testing.model.TestSpecification; import java.util.List; /** * Single entry point for the test writer to orchestrate the test set up * and retrieving the observations for Api based test cases. */ class HttpTestOrchestrator extends BaseTestOrchestrator { private final SUT sut; private ObjectMapper objectMapper = new ObjectMapper(); HttpTestOrchestrator(SUT sut) { this.sut = sut; } /** * run the test for the SUT * * @param testSpecification */ @SuppressWarnings("unchecked") public List<Observation> run(TestSpecification testSpecification){ //spawn the services required for the test try { dependencyRegistry.registerDependencies(testSpecification); this.testDataLoader.load(testSpecification.getIndirectInputs()); sut.start(); return this.observationCollector.actualObservations(testSpecification.sanitizeObservations(sut.getUrl())); } catch(Exception e) { throw new RuntimeException(e); }finally { try { dependencyRegistry.shutDown(); } catch (Exception e) { System.out.println("Error in shutting down all dependencies : You may face problems in next run"); } } } /** * A lite weight run of a test case cleaning up the dependency after started. * @param testSpecification * @return * @throws Exception */ @SuppressWarnings("unchecked") public List<Observation> runLite(TestSpecification testSpecification) { try{ dependencyRegistry.registerDependencies(testSpecification); this.testDataLoader.load(testSpecification.getIndirectInputsToBePreLoaded()); sut.start(); this.testDataLoader.load(testSpecification.getIndirectInputsToBePostLoaded()); return this.observationCollector.actualObservations(testSpecification.sanitizeObservations(sut.getUrl())); } catch(Exception e) { throw new RuntimeException(e); } finally { if(testSpecification.getShouldClean()){ try{ dependencyRegistry.clean(); }catch(Exception e){ System.out.println("Exception while cleaning " + e); e.printStackTrace(); } } } } }
true
922415ff226fa4005468514ad2da0f4f010e1e77
Java
sunxuia/spring-security-demo
/c1-method-annotation/src/main/java/net.sunxu.study.c1/AuthorizeController.java
UTF-8
8,449
2.53125
3
[]
no_license
package net.sunxu.study.c1; import net.sunxu.study.c0.CustomUserDetails; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PreAuthorize; 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; /** * 不同的权限可以访问到的方法不同 * 权限控制的相关方法和对象都在 {@link org.springframework.security.access.expression.SecurityExpressionRoot} 中实现 */ @RequestMapping("/authorize") @RestController public class AuthorizeController { /** * 不控制权限 * 登录还是没登录都可以访问 * * @return */ @GetMapping({"/", ""}) public String noAuthority() { return "noAuthority"; } //region hasRole demo 角色判断 // 通过用户是否有相应的角色来判断(输入的字符串会加上ROLE_ 前缀然后判断authorities 中是否包含这个字符串) // 类似的还有 hasAnyRole /** * 角色ANONYMOUS 权限控制 (未登录的用户只有一个ANONYOUS 权限) * * @return */ @GetMapping("/has-role-anonymous") @PreAuthorize("hasRole('ANONYMOUS')") public String hasRoleAnonymous() { return "hasRoleAnonymous"; } /** * 角色ADMIN 权限控制 * 需要登录后访问(登录用户有ADMIN 和NORMAL 的角色) * * @return */ @GetMapping("/has-role-admin") @PreAuthorize("hasRole('ADMIN')") public String hasRoleAdmin() { return "hasRoleAdmin"; } /** * 角色ROOT 权限控制 * 没有人可以访问 (不论匿名用户还是登录用户都没有ROOT 角色) * * @return */ @GetMapping("/has-role-root") @PreAuthorize("hasRole('ROOT')") public String hasRoleRoot() { return "rootAuthority"; } //endregion //region hasAuthority demo 权限验证 // 和hasRole 差不多, 不过不会加上ROLE_ 的前缀 // 类似的还有hasAnyAuthority /** * 权限检查需要有权限名为 ROLE_ADMIN * 登录的用户可以通过 * * @return */ @GetMapping("/has-authority-admin") @PreAuthorize("hasAuthority('ROLE_ADMIN')") public String hasAuthorityAdmin() { return "hasAuthorityAdmin"; } /** * 权限检查需要有权限名为 ROLE_ANONYMOUS * 没登录的用户可以通过, 登录的用户不能通过 * * @return */ @GetMapping("/has-authority-anonymous") @PreAuthorize("hasAuthority('ROLE_ANONYMOUS')") public String hasAuthorityAnonymous() { return "hasAuthorityAnonymous"; } //endregion //region 其它判断 (用户状态相关的) /** * isAnonymous() 限制 * 只有没登录的才可以访问 * * @return */ @GetMapping("/is-anonymous") @PreAuthorize("isAnonymous()") public String isAnonymous() { return "isAnonymous"; } /** * isAutnenticated() 限制 * 只有登录的才能访问 * * @return */ @GetMapping("/is-authenticated") @PreAuthorize("isAuthenticated()") public String isAuthenticated() { return "isAuthenticated"; } /** * isFullyAuthenticated() 限制 * 只有已登录且没有选择"记住我" 选项的用户才能访问 * * @return */ @GetMapping("/is-fully-authenticated") @PreAuthorize("isFullyAuthenticated()") public String isFullyAuthenticated() { return "isFullyAuthenticated"; } /** * isRememberMe() 限制 * 只有已经登录且选择了"记住我" 选项的用户才能访问 * * @return */ @GetMapping("/is-remember-me") @PreAuthorize("isRememberMe()") public String isRememberMe() { return "isRememberMe"; } //endregion //region 对象的使用 在权限控制中可以使用的对象 /** * 当前用户的principal 是字符串 "AnonymousUser" * 只有未登录用户才能访问 * * @return */ @GetMapping("/principal-is-anonymous-user") @PreAuthorize("principal == 'anonymousUser'") public String principalIsAnonymousUser() { return "principalIsAnonymousUser"; } /** * 当前用户是已经登录的用户 ( 通过表单登录的用户的principal 是CustomUserDetails 对象) * * @return */ @GetMapping("/principal-is-custom-user-details") @PreAuthorize("principal instanceof T(net.sunxu.study.c0.CustomUserDetails)") public String principalIsCustomUserDetails() { return "principalIsCustomUserDetails"; } /** * 当前用户的用户名是admin 的才能访问 * * @return */ @GetMapping("/user-name-is-admin") @PreAuthorize("principal instanceof T(org.springframework.security.core.userdetails.UserDetails) " + "and principal.getUsername() == 'admin'") public String userNameIsAdmin() { return "userNameIsAdmin"; } /** * 当前用户已经认证 * 不论是登录用户还是匿名用户, 在经过spring security 的用户认证之前都是false, 之后都是true. * 所以这个不论是登录还是未登录用户都可以访问. * * @return */ @GetMapping("/authentication-is-authenticated") @PreAuthorize("authentication.isAuthenticated()") public String authenticationIsAuthenticated() { return "authenticationIsAuthenticated"; } /** * 判断一下当前用户的ip 地址是什么 * 这个只要通过访问127.0.0.1 就可以, 单元测试的登录的用户 details 是空的, 所以会返回false, 单元测试的匿名登录的details 是有的. * * @return */ @GetMapping("/authentication-details-is-from-127001") @PreAuthorize("authentication.getDetails() != null &&" + " authentication.getDetails().getRemoteAddress() == '127.0.0.1'") public String authenticationDetailsIsFrom127001() { return "authenticationDetailsIsFrom127001"; } /** * hasPermssion 的权限检查. 通过检查认证用户对该对象是否具有相应的权限来判断是否可以访问. * * @return */ @GetMapping("/has-permission-w-2-args") @PreAuthorize("hasPermission('hasPermissionW2Args', 'read')") public String hasPermissionW2Args() { return "hasPermissionW2Args"; } /** * hasPermission 的权限检查. 通过标识符和类型获得对象, 然后检查用户对该对象是否具有权限来判断是否可以访问. * 通过"#参数名" 传入方法的参数. * * @return */ @GetMapping("/has-permission-w-3-args") @PreAuthorize("hasPermission(#number, 'java.lang.String', 'read')") public String hasPermissionW3Args(Long number) { return "hasPermissionW3Args"; } /** * 使用自定义的权限验证方法. 通过"@beanName.methodName(arguments)" 的方式调用方法进行验证. * 通过"#参数名" 传入方法的参数. * * @return */ @GetMapping("/custom-method") @PreAuthorize("@authorizeController.customVerifyMethod(principal, #userName)") public String customMethod(@RequestParam String userName) { return "customMethod"; } // 自定义的验证表达式, 方法返回true 表示权限验证通过, false 表示权限验证失败. public boolean customVerifyMethod(Object principal, String userName) { return principal != null && (principal instanceof String && principal.equals(userName) || (principal instanceof CustomUserDetails && ((CustomUserDetails) principal).getUsername().equals(userName))); } //endregion //region PostAuthorize // 这个在方法执行后才会执行其中的spring el 进行权限判断. /** * 返回这个方法执行的次数. 不论是否通过权限验证这个方法都会被执行. * * @return */ @GetMapping("/post-authorize") @PostAuthorize("principal == 'anonymousUser'") public int postAuthorize() { return ++postAuthorizeVisitCount; } private int postAuthorizeVisitCount = 0; //endregion }
true
90b63e9f8d136d64b7b60791975c108fc9ade357
Java
Hrzug585/HouseHunter
/api/src/main/java/com/example/HouseHunter/model/Home.java
UTF-8
506
2.171875
2
[ "MIT" ]
permissive
package com.example.HouseHunter.model; import lombok.Getter; import lombok.Setter; import org.springframework.data.elasticsearch.annotations.Document; @Getter @Setter @Document(indexName = "house") public class Home { private Long id; private String url; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
true
4fe18e0af0384a53e4b6ffef4e1acda90eeaa953
Java
jasonlee529/spring-cloud-demo
/spring-core/src/main/java/cn/hebut/lee/spring/core/bean/SlayDragonQuest.java
UTF-8
175
1.992188
2
[ "Apache-2.0" ]
permissive
package cn.hebut.lee.spring.core.bean; public class SlayDragonQuest implements Quest { public void embark() { System.out.println(" Any Knight is embarking !!!"); } }
true
555428b367d553567d552b57051c046cf6f6f00e
Java
GheorgheCazacu/PAO
/Laborator-02/src/com/fmi/lab2/animals/Cat.java
UTF-8
884
3.515625
4
[ "MIT" ]
permissive
package com.fmi.lab2.animals; import java.util.Arrays; import java.util.*; public class Cat { protected boolean shortHair; private Integer size; // possible values 1, 2, 3 => small, medium, big - enum in the future Integer propDefault; public void meow() { System.out.println("cat - meow"); } public void doStuff() { Arrays.toString(new Integer[]{1, 2, 3}); } public boolean isShortHair() { return shortHair; } public void setShortHair(boolean shortHair) { this.shortHair = shortHair; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public Integer getPropDefault() { return propDefault; } public void setPropDefault(Integer propDefault) { this.propDefault = propDefault; } }
true
0cf235387010e31bcb3220b27ea76839b097a416
Java
GitHubAlexKir/GSO3-AEXBanner
/src/shared/IListener.java
UTF-8
181
1.796875
2
[]
no_license
package shared; import java.rmi.Remote; import java.rmi.RemoteException; public interface IListener extends Remote { void setKoersen(String fondsen) throws RemoteException; }
true
6f4e0b9a19ea70148e76c7c3c818e56ac91773ba
Java
Gagandeep39/spring-boot-reddit
/src/main/java/com/gagan/redditclone/mapper/SubredditMapper.java
UTF-8
890
2.390625
2
[]
no_license
package com.gagan.redditclone.mapper; import java.util.List; import com.gagan.redditclone.dto.SubredditDto; import com.gagan.redditclone.model.Post; import com.gagan.redditclone.model.Subreddit; import org.mapstruct.InheritInverseConfiguration; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface SubredditMapper { @Mapping(target = "numberOfPosts", expression = "java(mapPosts(subreddit.getPosts()))") SubredditDto mapSubredditToDto(Subreddit subreddit); default Integer mapPosts(List<Post> posts) { return posts.size(); } /** * Implies inverse mapping of another method in this file */ @InheritInverseConfiguration @Mapping(target = "posts", ignore = true) @Mapping(target = "createdDate", expression = "java(java.time.Instant.now())") Subreddit mapDtoToSubreddit(SubredditDto subredditDto); }
true
01039cdbde9beb83f294ae53dd5e27bcd21e7a31
Java
wengyinbing/ChatRoom
/src/main/java/BIO/Server/ChatHandler.java
UTF-8
1,438
3.171875
3
[]
no_license
package BIO.Server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; /** * @author wengyinbing * @data 2021/6/22 21:56 **/ public class ChatHandler implements Runnable{ private ChatServer server; private Socket socket; public ChatHandler(ChatServer server, Socket socket) { this.server = server; this.socket = socket; } @Override public void run() { try{ server.addClient(socket); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = null; while((msg = reader.readLine())!=null){ String sendmsg = "Client[" + socket.getPort() + "]:" + msg; //服务器打印这个消息 System.out.println(sendmsg); //群发这个消息 server.sendMessage(socket,msg); if(msg.equals("quit")){ System.out.println("Client[" + socket.getPort() + "]:Offline"); break; } } } catch (IOException e) { e.printStackTrace(); } finally{ try {//结束或是意外终止记得移除socket server.removeClient(socket); } catch (IOException e) { e.printStackTrace(); } } } }
true
6b55f35d27589a928b26dfff2eb7007d81bd9a02
Java
ma1uta/mxtoot
/src/main/java/io/github/ma1uta/mxtoot/matrix/command/FetchStatuses.java
UTF-8
2,145
1.835938
2
[ "Apache-2.0" ]
permissive
/* * Copyright sablintolya@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ma1uta.mxtoot.matrix.command; import io.github.ma1uta.matrix.Event; import io.github.ma1uta.matrix.bot.Context; import io.github.ma1uta.matrix.bot.command.OwnerCommand; import io.github.ma1uta.mxtoot.mastodon.MxMastodonClient; import io.github.ma1uta.mxtoot.matrix.MxTootConfig; import io.github.ma1uta.mxtoot.matrix.MxTootDao; import io.github.ma1uta.mxtoot.matrix.MxTootPersistentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Enable or disable fetch statuses. */ public class FetchStatuses extends OwnerCommand<MxTootConfig, MxTootDao, MxTootPersistentService<MxTootDao>, MxMastodonClient> { private static final Logger LOGGER = LoggerFactory.getLogger(FetchStatuses.class); @Override public String name() { return "fetch_statuses"; } @Override public boolean ownerInvoke(Context<MxTootConfig, MxTootDao, MxTootPersistentService<MxTootDao>, MxMastodonClient> holder, String roomId, Event event, String arguments) { if (arguments == null || arguments.isEmpty()) { holder.getMatrixClient().event().sendNotice(roomId, "Usage: " + usage()); return true; } holder.getConfig().setFetchMissingStatuses(Boolean.parseBoolean(arguments.trim())); return true; } @Override public String help() { return "should mastodon client fetch statuses by id (for example replies)."; } @Override public String usage() { return "fetch_statuses [true|false]"; } }
true
9bed2068319995467b8052329371a1b874dadae8
Java
BearTiny/UPnP-DLNA-Demo
/app/src/main/java/com/iss/upnptest/server/medialserver/entity/ImageItem.java
UTF-8
3,464
2.203125
2
[]
no_license
package com.iss.upnptest.server.medialserver.entity; import java.util.Arrays; import java.util.List; import org.fourthline.cling.support.model.DIDLObject.Property.DC; import org.fourthline.cling.support.model.DIDLObject.Property.UPNP; import org.fourthline.cling.support.model.Person; import org.fourthline.cling.support.model.Res; import org.fourthline.cling.support.model.StorageMedium; import org.fourthline.cling.support.model.container.Container; /** * @author hubing * @version 1.0.0 2015-5-8 */ public class ImageItem extends MItem { public static final Class CLASS = new Class("object.item.imageItem"); public ImageItem() { setClazz(CLASS); } public ImageItem(MItem other) { super(other); } public ImageItem(String id, Container parent, String title, String creator, String filePath, Res... resource) { this(id, parent.getId(), title, creator, filePath, resource); } public ImageItem(String id, String parentID, String title, String creator, String filePath, Res... resource) { super(id, parentID, title, creator, filePath, CLASS); if (resource != null) { getResources().addAll(Arrays.asList(resource)); } } public String getDescription() { return getFirstPropertyValue(DC.DESCRIPTION.class); } public ImageItem setDescription(String description) { replaceFirstProperty(new DC.DESCRIPTION(description)); return this; } public String getLongDescription() { return getFirstPropertyValue(UPNP.LONG_DESCRIPTION.class); } public ImageItem setLongDescription(String description) { replaceFirstProperty(new UPNP.LONG_DESCRIPTION(description)); return this; } public Person getFirstPublisher() { return getFirstPropertyValue(DC.PUBLISHER.class); } public Person[] getPublishers() { List<Person> list = getPropertyValues(DC.PUBLISHER.class); return list.toArray(new Person[list.size()]); } public ImageItem setPublishers(Person[] publishers) { removeProperties(DC.PUBLISHER.class); for (Person publisher : publishers) { addProperty(new DC.PUBLISHER(publisher)); } return this; } public StorageMedium getStorageMedium() { return getFirstPropertyValue(UPNP.STORAGE_MEDIUM.class); } public ImageItem setStorageMedium(StorageMedium storageMedium) { replaceFirstProperty(new UPNP.STORAGE_MEDIUM(storageMedium)); return this; } public String getRating() { return getFirstPropertyValue(UPNP.RATING.class); } public ImageItem setRating(String rating) { replaceFirstProperty(new UPNP.RATING(rating)); return this; } public String getDate() { return getFirstPropertyValue(DC.DATE.class); } public ImageItem setDate(String date) { replaceFirstProperty(new DC.DATE(date)); return this; } public String getFirstRights() { return getFirstPropertyValue(DC.RIGHTS.class); } public String[] getRights() { List<String> list = getPropertyValues(DC.RIGHTS.class); return list.toArray(new String[list.size()]); } public ImageItem setRights(String[] rights) { removeProperties(DC.RIGHTS.class); for (String right : rights) { addProperty(new DC.RIGHTS(right)); } return this; } }
true
d471aeebf214e029826f3b67dae981e7e42c5efb
Java
benpilcher/TE-Exercises
/1 - Pair Exercise, Week 3/src/test/java/com/techelevator/hr/EmployeeTests.java
UTF-8
2,503
3.53125
4
[]
no_license
package com.techelevator.hr; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class EmployeeTests { @Test public void getFullNameReturnsCorrectFormat() { Employee employee = new Employee("Test", "Testerson"); String fullName = employee.getFullName(); assertEquals("The employee full name is not in the correct format.", "Testerson, Test", fullName); } @Test public void raiseSalaryTest_Positive() { Employee employee = new Employee("Test", "Testerson"); employee.setSalary(100); employee.raiseSalary(5); assertEquals("The employee raise of 5% was not computed correctly.",employee.getSalary(), 100 * 1.05, 0.0); } @Test public void raiseSalaryTest_Negative() { Employee employee = new Employee("Test", "Testerson"); employee.setSalary(100); employee.raiseSalary(-10); //"raise" by negative 10% assertEquals("Salary should remain the same when raise percentage is negative.",100, employee.getSalary(),0.0); } @Test public void balanceShouldBe_Zero() { Employee employee = new Employee("Test", "Testerson"); Map<String, Double> testMap = new HashMap<>(); double testDouble = employee.getBalanceDue(testMap); assertEquals(0.0, testDouble, 0.0); } @Test public void balanceShouldBe_10() { Employee employee = new Employee("Test", "Testerson"); Map<String, Double> testMap = new HashMap<>(); testMap.put("Grooming", 10.0); testMap.put("Sitting", 10.0); double testDouble = employee.getBalanceDue(testMap); assertEquals(10.0, testDouble, 0.0); } @Test public void balanceShouldBe_Five() { Employee employee = new Employee("Test", "Testerson"); Map<String, Double> testMap = new HashMap<>(); testMap.put("Walking", 10.0); double testDouble = employee.getBalanceDue(testMap); assertEquals(5.0, testDouble, 0.0); } @Test public void balanceShouldBe_TenFifty() { Employee employee = new Employee("Test", "Testerson"); Map<String, Double> testMap = new HashMap<>(); testMap.put("Walking", 10.0); testMap.put("Tick treatment", 11.0); double testDouble = employee.getBalanceDue(testMap); assertEquals(10.5, testDouble, 0.0); } }
true
80f18a0d14451680878b6d58b42c6c9b304eaedb
Java
sebaudracco/bubble
/com/elephant/data/p037d/p038b/C1751h.java
UTF-8
316
1.703125
2
[]
no_license
package com.elephant.data.p037d.p038b; import android.content.Context; import android.os.Handler.Callback; import android.os.Message; public final class C1751h implements Callback { public C1751h(Context context) { } public final boolean handleMessage(Message message) { return false; } }
true
87958d1d455262bad164741bc62fff4ae3a797ae
Java
JianpingZeng/clank
/modules/org.llvm.adtsupport/src/org/llvm/adt/iplist.java
UTF-8
55,574
1.765625
2
[]
no_license
/** * This file was converted to Java from the original LLVM source file. The original * source file follows the LLVM Release License, outlined below. * * ============================================================================== * LLVM Release License * ============================================================================== * University of Illinois/NCSA * Open Source License * * Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign. * All rights reserved. * * Developed by: * * LLVM Team * * University of Illinois at Urbana-Champaign * * http://llvm.org * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal with * 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: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimers. * * * Redistributions in binary form must reproduce the above copyright notice * this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * * * Neither the names of the LLVM Team, University of Illinois at * Urbana-Champaign, nor the names of its contributors may be used to * endorse or promote products derived from this Software without specific * prior written permission. * * 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 * CONTRIBUTORS 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 WITH THE * SOFTWARE. * * ============================================================================== * Copyrights and Licenses for Third Party Software Distributed with LLVM: * ============================================================================== * The LLVM software contains code written by third parties. Such software will * have its own individual LICENSE.TXT file in the directory in which it appears. * This file will describe the copyrights, license, and restrictions which apply * to that code. * * The disclaimer of warranty in the University of Illinois Open Source License * applies to all code in the LLVM Distribution, and nothing in any of the * other licenses gives permission to use the names of the LLVM Team or the * University of Illinois to endorse or promote products derived from this * Software. * * The following pieces of software have additional or alternate copyrights, * licenses, and/or restrictions: * * Program Directory * ------- --------- * Autoconf llvm/autoconf * llvm/projects/ModuleMaker/autoconf * Google Test llvm/utils/unittest/googletest * OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex} * pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT} * ARM contributions llvm/lib/Target/ARM/LICENSE.TXT * md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h */ package org.llvm.adt; import static org.clank.support.Native.$Deref; import static org.clank.support.Native.$AddrOf; import org.clank.java.*; import org.clank.support.*; import org.clank.support.Native.NativeIterable; import org.clank.support.aliases.JavaIterator; import org.clank.support.aliases.type$iterator; import org.clank.support.aliases.type$ref; //===----------------------------------------------------------------------===// // /// iplist - The subset of list functionality that can safely be used on nodes /// of polymorphic types, i.e. a heterogeneous list with a common base class that /// holds the next/prev pointers. The only state of the list itself is a single /// pointer to the head of the list. /// /// This list can be in one of three interesting states: /// 1. The list may be completely unconstructed. In this case, the head /// pointer is null. When in this form, any query for an iterator (e.g. /// begin() or end()) causes the list to transparently change to state #2. /// 2. The list may be empty, but contain a sentinel for the end iterator. This /// sentinel is created by the Traits::createSentinel method and is a link /// in the list. When the list is empty, the pointer in the iplist points /// to the sentinel. Once the sentinel is constructed, it /// is not destroyed until the list is. /// 3. The list may contain actual objects in it, which are stored as a doubly /// linked list of nodes. One invariant of the list is that the predecessor /// of the first node in the list always points to the last node in the list, /// and the successor pointer for the sentinel (which always stays at the /// end of the list) is always null. /// /*template <typename NodeTy, typename Traits = ilist_traits<NodeTy>> TEMPLATE*/ //<editor-fold defaultstate="collapsed" desc="llvm::iplist"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 309, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 361, FQN="llvm::iplist", NM="_ZN4llvm6iplistE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplistE") //</editor-fold> public abstract class iplist</*typename*/ NodeTy extends ilist_node<NodeTy>/*, typename Traits = ilist_traits<NodeTy>*/> implements ilist_traits<NodeTy>, NativeIterable<ilist_iterator<? extends NodeTy>>, Iterable<NodeTy>, Destructors.ClassWithDestructor { private /*mutable */NodeTy /*P*/ Head; // Use the prev node pointer of 'head' as the tail pointer. This is really a // circularly linked list where we snip the 'next' link from the sentinel node // back to the first node in the list (to preserve assertions about going off // the end of the list). //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getTail"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 317, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 369, FQN="llvm::iplist::getTail", NM="_ZN4llvm6iplist7getTailEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist7getTailEv") //</editor-fold> private NodeTy /*P*/ getTail() { return ensureHead(Head$ref); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getTail"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 318, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 370, FQN="llvm::iplist::getTail", NM="_ZNK4llvm6iplist7getTailEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist7getTailEv") //</editor-fold> private /*const*/ NodeTy /*P*/ getTail$Const() /*const*/ { return ensureHead(Head$ref); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::setTail"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 319, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 371, FQN="llvm::iplist::setTail", NM="_ZNK4llvm6iplist7setTailEPT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist7setTailEPT_") //</editor-fold> private void setTail(NodeTy /*P*/ N) /*const*/ { noteHead(Head, N); } /// CreateLazySentinel - This method verifies whether the sentinel for the /// list has been created and lazily makes it if not. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::CreateLazySentinel"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 323, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 375, FQN="llvm::iplist::CreateLazySentinel", NM="_ZNK4llvm6iplist18CreateLazySentinelEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist18CreateLazySentinelEv") //</editor-fold> private void CreateLazySentinel() /*const*/ { ensureHead(Head$ref); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::op_less"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 327, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 379, FQN="llvm::iplist::op_less", NM="_ZN4llvm6iplist7op_lessERT_S2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist7op_lessERT_S2_") //</editor-fold> private static </*typename*/ NodeTy, /*typename*/ Traits/* = ilist_traits<NodeTy>*/> boolean op_less(final NodeTy /*&*/ L, final NodeTy /*&*/ R) { return Native.$less(L, R); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::op_equal"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 328, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 380, FQN="llvm::iplist::op_equal", NM="_ZN4llvm6iplist8op_equalERT_S2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist8op_equalERT_S2_") //</editor-fold> private static </*typename*/ NodeTy, /*typename*/ Traits/* = ilist_traits<NodeTy>*/> boolean op_equal(final NodeTy /*&*/ L, final NodeTy /*&*/ R) { return Native.$eq(L, R); } // No fundamental reason why iplist can't be copyable, but the default // copy/copy-assign won't do. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::iplist<NodeTy, Traits>"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 332, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 384, FQN="llvm::iplist::iplist<NodeTy, Traits>", NM="_ZN4llvm6iplistC1ERKNS_6iplistIT_T0_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplistC1ERKNS_6iplistIT_T0_EE") //</editor-fold> protected/*private*/ iplist(final /*const*/ iplist<NodeTy> /*&*/ $Prm0) {throw new UnsupportedOperationException("Deleted");} //<editor-fold defaultstate="collapsed" desc="llvm::iplist::operator="> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 333, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 385, FQN="llvm::iplist::operator=", NM="_ZN4llvm6iplistaSERKNS_6iplistIT_T0_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplistaSERKNS_6iplistIT_T0_EE") //</editor-fold> protected/*private*/ void $assign(final /*const*/ iplist<NodeTy> /*&*/ $Prm0) { throw new UnsupportedOperationException("Deleted");} /*public:*/ // JAVA: typedef NodeTy *pointer // public final class pointer extends NodeTy /*P*/ { }; // JAVA: typedef const NodeTy *const_pointer // public final class const_pointer extends /*const*/ NodeTy /*P*/ { }; // JAVA: typedef NodeTy &reference // public final class reference extends NodeTy /*&*/ { }; // JAVA: typedef const NodeTy &const_reference // public final class const_reference extends /*const*/ NodeTy /*&*/ { }; // JAVA: typedef NodeTy value_type // public final class value_type extends NodeTy{ }; // JAVA: typedef ilist_iterator<NodeTy> iterator // public final class iterator extends ilist_iterator<NodeTy>{ }; // JAVA: typedef ilist_iterator<const NodeTy> const_iterator // public final class const_iterator extends ilist_iterator</*const*/ NodeTy>{ }; // JAVA: typedef size_t size_type; // JAVA: typedef ptrdiff_t difference_type; // JAVA: typedef std::reverse_iterator<const_iterator> const_reverse_iterator // public final class const_reverse_iterator extends std.reverse_iterator<ilist_iterator</*const*/ NodeTy> >{ }; // JAVA: typedef std::reverse_iterator<iterator> reverse_iterator // public final class reverse_iterator extends std.reverse_iterator<ilist_iterator<NodeTy> >{ }; //<editor-fold defaultstate="collapsed" desc="llvm::iplist::iplist<NodeTy, Traits>"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 348, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 400, FQN="llvm::iplist::iplist<NodeTy, Traits>", NM="_ZN4llvm6iplistC1Ev", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplistC1Ev") //</editor-fold> public iplist() { // : Head(this->provideInitialHead()) //START JInit this.Head = /*ParenListExpr*/provideInitialHead(); //END JInit } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::~iplist<NodeTy, Traits>"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 349, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 401, FQN="llvm::iplist::~iplist<NodeTy, Traits>", NM="_ZN4llvm6iplistD0Ev", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplistD0Ev") //</editor-fold> public void $destroy() { if (Native.$not(Head)) { return; } clear(); destroySentinel(getTail()); //super.$destroy(); } // Iterator creation methods. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::begin"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 356, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 408, FQN="llvm::iplist::begin", NM="_ZN4llvm6iplist5beginEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5beginEv") //</editor-fold> public ilist_iterator<NodeTy> begin() { CreateLazySentinel(); return new ilist_iterator<NodeTy>(Head, $traits()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::begin"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 360, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 412, FQN="llvm::iplist::begin", NM="_ZNK4llvm6iplist5beginEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist5beginEv") //</editor-fold> public ilist_iterator</*const*/ NodeTy> begin$Const() /*const*/ { CreateLazySentinel(); return new ilist_iterator</*const*/ NodeTy>(Head, $traits()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::end"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 364, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 416, FQN="llvm::iplist::end", NM="_ZN4llvm6iplist3endEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist3endEv") //</editor-fold> public ilist_iterator<NodeTy> end() { CreateLazySentinel(); return new ilist_iterator<NodeTy>(getTail(), $traits()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::end"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 368, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 420, FQN="llvm::iplist::end", NM="_ZNK4llvm6iplist3endEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist3endEv") //</editor-fold> public ilist_iterator</*const*/ NodeTy> end$Const() /*const*/ { CreateLazySentinel(); return new ilist_iterator</*const*/ NodeTy>(getTail(), $traits()); } // reverse iterator creation methods. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::rbegin"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 374, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 426, FQN="llvm::iplist::rbegin", NM="_ZN4llvm6iplist6rbeginEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6rbeginEv") //</editor-fold> public std.reverse_iterator<NodeTy> rbegin() { return new std.reverse_iterator<NodeTy>(end()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::rbegin"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 375, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 427, FQN="llvm::iplist::rbegin", NM="_ZNK4llvm6iplist6rbeginEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist6rbeginEv") //</editor-fold> public std.reverse_iterator<NodeTy> rbegin$Const() /*const*/ { return new std.reverse_iterator<NodeTy>(end()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::rend"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 376, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 428, FQN="llvm::iplist::rend", NM="_ZN4llvm6iplist4rendEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist4rendEv") //</editor-fold> public std.reverse_iterator<NodeTy> rend() { return new std.reverse_iterator<NodeTy>(begin()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::rend"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 377, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 429, FQN="llvm::iplist::rend", NM="_ZNK4llvm6iplist4rendEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist4rendEv") //</editor-fold> public std.reverse_iterator<NodeTy> rend$Const() /*const*/ { return new std.reverse_iterator<NodeTy>(begin()); } // Miscellaneous inspection routines. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::max_size"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 381, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 433, FQN="llvm::iplist::max_size", NM="_ZNK4llvm6iplist8max_sizeEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist8max_sizeEv") //</editor-fold> public /*size_t*/int max_size() /*const*/ { return ((/*size_t*/int)(-1)); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::empty"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 382, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 434, FQN="llvm::iplist::empty", NM="_ZNK4llvm6iplist5emptyEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist5emptyEv") //</editor-fold> public boolean empty() /*const*//* __attribute__((warn_unused_result))*/ { return Native.$not(Head) || Native.$bool(Native.$eq_ptr(Head, getTail())); } // Front and back accessor functions... //<editor-fold defaultstate="collapsed" desc="llvm::iplist::front"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 387, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 439, FQN="llvm::iplist::front", NM="_ZN4llvm6iplist5frontEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5frontEv") //</editor-fold> public NodeTy /*&*/ front() { assert Native.$bool(Native.$not(empty())) : "Called front() on empty list!"; return $Deref(Head); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::front"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 391, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 443, FQN="llvm::iplist::front", NM="_ZNK4llvm6iplist5frontEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist5frontEv") //</editor-fold> public /*const*/ NodeTy /*&*/ front$Const() /*const*/ { assert Native.$bool(Native.$not(empty())) : "Called front() on empty list!"; return $Deref(Head); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::back"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 395, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 447, FQN="llvm::iplist::back", NM="_ZN4llvm6iplist4backEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist4backEv") //</editor-fold> public NodeTy /*&*/ back() { assert Native.$bool(Native.$not(empty())) : "Called back() on empty list!"; return $Deref(getPrev(getTail())); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::back"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 399, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 451, FQN="llvm::iplist::back", NM="_ZNK4llvm6iplist4backEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist4backEv") //</editor-fold> public /*const*/ NodeTy /*&*/ back$Const() /*const*/ { assert Native.$bool(Native.$not(empty())) : "Called back() on empty list!"; return $Deref(getPrev(getTail())); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::swap"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 404, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 456, FQN="llvm::iplist::swap", NM="_ZN4llvm6iplist4swapERNS_6iplistIT_T0_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist4swapERNS_6iplistIT_T0_EE") //</editor-fold> public void swap(final iplist<NodeTy> /*&*/ RHS) { assert (false) : "Swap does not use list traits callback correctly yet!"; //std.swap(Head, RHS.Head); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::insert"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 409, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 461, FQN="llvm::iplist::insert", NM="_ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EEPS2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EEPS2_") //</editor-fold> public ilist_iterator<NodeTy> insert_ilist_iterator$NodeTy_T$P(ilist_iterator<NodeTy> where, NodeTy /*P*/ New) { NodeTy /*P*/ CurNode = where.getNodePtrUnchecked(); NodeTy /*P*/ PrevNode = getPrev(CurNode); setNext(New, CurNode); setPrev(New, PrevNode); if (Native.$noteq_ptr(CurNode, Head)) { // Is PrevNode off the beginning of the list? setNext(PrevNode, New); } else { Head = New; } setPrev(CurNode, New); this.addNodeToList(this, New); // Notify traits that we added a node... return new ilist_iterator<NodeTy>(New, $traits()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::insert"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 425, FQN="llvm::iplist::insert", NM="_ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EERKS2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EERKS2_") //</editor-fold> public ilist_iterator<NodeTy> insert_ilist_iterator$NodeTy_T$C$R(ilist_iterator<NodeTy> where, final /*const*/ NodeTy /*&*/ New) { return insert_ilist_iterator$NodeTy_T$P(where, New);//new NodeTy(( New ))); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::insertAfter"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 429, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 477, FQN="llvm::iplist::insertAfter", NM="_ZN4llvm6iplist11insertAfterENS_14ilist_iteratorIT_EEPS2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist11insertAfterENS_14ilist_iteratorIT_EEPS2_") //</editor-fold> public ilist_iterator<NodeTy> insertAfter(ilist_iterator<NodeTy> where, NodeTy /*P*/ New) { if (empty()) { return insert_ilist_iterator$NodeTy_T$C$R(begin(), New); } else { return insert_ilist_iterator$NodeTy_T$C$R(where.$preInc(), New); } } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::remove"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 436, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 484, FQN="llvm::iplist::remove", NM="_ZN4llvm6iplist6removeERNS_14ilist_iteratorIT_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6removeERNS_14ilist_iteratorIT_EE") //</editor-fold> public NodeTy /*P*/ remove_ilist_iterator$NodeTy(final ilist_iterator<NodeTy> /*&*/ IT) { assert Native.$bool(Native.$noteq_iter(IT, end())) : "Cannot remove end of list!"; NodeTy /*P*/ Node = $AddrOf($Deref(IT.$star())); NodeTy /*P*/ NextNode = getNext(Node); NodeTy /*P*/ PrevNode = getPrev(Node); if (Native.$noteq_ptr(Node, Head)) { // Is PrevNode off the beginning of the list? setNext(PrevNode, NextNode); } else { Head = NextNode; } setPrev(NextNode, PrevNode); IT.reset(NextNode); this.removeNodeFromList(this, Node); // Notify traits that we removed a node... // Set the next/prev pointers of the current node to null. This isn't // strictly required, but this catches errors where a node is removed from // an ilist (and potentially deleted) with iterators still pointing at it. // When those iterators are incremented or decremented, they will assert on // the null next/prev pointer instead of "usually working". setNext(Node, null); setPrev(Node, null); return Node; } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::remove"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 460, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 508, FQN="llvm::iplist::remove", NM="_ZN4llvm6iplist6removeERKNS_14ilist_iteratorIT_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6removeERKNS_14ilist_iteratorIT_EE") //</editor-fold> public NodeTy /*P*/ remove_ilist_iterator$NodeTy$C(final /*const*/ ilist_iterator<NodeTy> /*&*/ IT) { ilist_iterator<NodeTy> MutIt = IT; return remove_ilist_iterator$NodeTy(MutIt); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::remove"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 465, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 513, FQN="llvm::iplist::remove", NM="_ZN4llvm6iplist6removeEPT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6removeEPT_") //</editor-fold> public NodeTy /*P*/ remove_T$P(NodeTy /*P*/ IT) { return remove_ilist_iterator$NodeTy$C(new ilist_iterator<NodeTy>(IT, $traits())); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::remove"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 466, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 514, FQN="llvm::iplist::remove", NM="_ZN4llvm6iplist6removeERT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6removeERT_") //</editor-fold> public NodeTy /*P*/ remove_T$R(final NodeTy /*&*/ IT) { return remove_ilist_iterator$NodeTy$C(new ilist_iterator<NodeTy>(IT, $traits())); } // erase - remove a node from the controlled sequence... and delete it. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::erase"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 469, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 517, FQN="llvm::iplist::erase", NM="_ZN4llvm6iplist5eraseENS_14ilist_iteratorIT_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5eraseENS_14ilist_iteratorIT_EE") //</editor-fold> public ilist_iterator<NodeTy> erase(ilist_iterator<NodeTy> where) { deleteNode(this, remove_ilist_iterator$NodeTy(where)); return where; } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::erase"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 474, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 522, FQN="llvm::iplist::erase", NM="_ZN4llvm6iplist5eraseEPT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5eraseEPT_") //</editor-fold> public ilist_iterator<NodeTy> erase_T$P(NodeTy /*P*/ IT) { return erase(new ilist_iterator<NodeTy>(IT, $traits())); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::erase"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 475, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 523, FQN="llvm::iplist::erase", NM="_ZN4llvm6iplist5eraseERT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5eraseERT_") //</editor-fold> public ilist_iterator<NodeTy> erase_T$R(final NodeTy /*&*/ IT) { return erase(new ilist_iterator<NodeTy>(IT, $traits())); } /// Remove all nodes from the list like clear(), but do not call /// removeNodeFromList() or deleteNode(). /// /// This should only be used immediately before freeing nodes in bulk to /// avoid traversing the list and bringing all the nodes into cache. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::clearAndLeakNodesUnsafely"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 482, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 530, FQN="llvm::iplist::clearAndLeakNodesUnsafely", NM="_ZN4llvm6iplist25clearAndLeakNodesUnsafelyEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist25clearAndLeakNodesUnsafelyEv") //</editor-fold> public void clearAndLeakNodesUnsafely() { if (Head != null) { Head = getTail(); setPrev(Head, Head); } } /*private:*/ // transfer - The heart of the splice function. Move linked list nodes from // [first, last) into position. // //<editor-fold defaultstate="collapsed" desc="llvm::iplist::transfer"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 493, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 541, FQN="llvm::iplist::transfer", NM="_ZN4llvm6iplist8transferENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_S3_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist8transferENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_S3_") //</editor-fold> private void transfer(ilist_iterator<NodeTy> position, final iplist<NodeTy> /*&*/ L2, ilist_iterator<NodeTy> first, ilist_iterator<NodeTy> last) { assert Native.$bool(Native.$noteq_iter(first, last)) : "Should be checked by callers"; // Position cannot be contained in the range to be transferred. // Check for the most common mistake. assert Native.$bool(Native.$noteq_iter(position, first)) : "Insertion point can't be one of the transferred nodes"; if (Native.$noteq_iter(position, last)) { // Note: we have to be careful about the case when we move the first node // in the list. This node is the list sentinel node and we can't move it. NodeTy /*P*/ ThisSentinel = getTail(); setTail(null); NodeTy /*P*/ L2Sentinel = L2.getTail(); L2.setTail(null); // Remove [first, last) from its old position. NodeTy /*P*/ First = $AddrOf($Deref(first.$star())); NodeTy /*P*/ Prev = getPrev(First); NodeTy /*P*/ Next = last.getNodePtrUnchecked(); NodeTy /*P*/ Last = getPrev(Next); if (Prev != null) { setNext(Prev, Next); } else { L2.Head = Next; } setPrev(Next, Prev); // Splice [first, last) into its new position. NodeTy /*P*/ PosNext = position.getNodePtrUnchecked(); NodeTy /*P*/ PosPrev = getPrev(PosNext); // Fix head of list... if (PosPrev != null) { setNext(PosPrev, First); } else { Head = First; } setPrev(First, PosPrev); // Fix end of list... setNext(Last, PosNext); setPrev(PosNext, Last); this.transferNodesFromList(L2, new ilist_iterator<NodeTy>(First, $traits()), new ilist_iterator<NodeTy>(PosNext, $traits())); // Now that everything is set, restore the pointers to the list sentinels. L2.setTail(L2Sentinel); setTail(ThisSentinel); } } /*public:*/ //===----------------------------------------------------------------------=== // Functionality derived from other functions defined above... // //<editor-fold defaultstate="collapsed" desc="llvm::iplist::size"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 546, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 594, FQN="llvm::iplist::size", NM="_ZNK4llvm6iplist4sizeEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist4sizeEv") //</editor-fold> public /*size_t*/int size() /*const*//* __attribute__((warn_unused_result))*/ { if (Native.$not(Head)) { return 0; // Don't require construction of sentinel if empty. } return std.distance(begin(), end()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::erase"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 551, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 599, FQN="llvm::iplist::erase", NM="_ZN4llvm6iplist5eraseENS_14ilist_iteratorIT_EES3_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5eraseENS_14ilist_iteratorIT_EES3_") //</editor-fold> public ilist_iterator<NodeTy> erase(ilist_iterator<NodeTy> first, ilist_iterator<NodeTy> last) { while (Native.$noteq_iter(first, last)) { first = erase(first); } return last; } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::clear"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 557, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 605, FQN="llvm::iplist::clear", NM="_ZN4llvm6iplist5clearEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5clearEv") //</editor-fold> public void clear() { if (Head != null) { erase(begin(), end()); } } // Front and back inserters... //<editor-fold defaultstate="collapsed" desc="llvm::iplist::push_front"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 560, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 608, FQN="llvm::iplist::push_front", NM="_ZN4llvm6iplist10push_frontEPT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist10push_frontEPT_") //</editor-fold> public void push_front(NodeTy /*P*/ val) { insert_ilist_iterator$NodeTy_T$C$R(begin(), val); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::push_back"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 561, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 609, FQN="llvm::iplist::push_back", NM="_ZN4llvm6iplist9push_backEPT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist9push_backEPT_") //</editor-fold> public void push_back(NodeTy /*P*/ val) { insert_ilist_iterator$NodeTy_T$C$R(end(), val); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::pop_front"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 562, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 610, FQN="llvm::iplist::pop_front", NM="_ZN4llvm6iplist9pop_frontEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist9pop_frontEv") //</editor-fold> public void pop_front() { assert Native.$bool(Native.$not(empty())) : "pop_front() on empty list!"; erase(begin()); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::pop_back"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 566, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 614, FQN="llvm::iplist::pop_back", NM="_ZN4llvm6iplist8pop_backEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist8pop_backEv") //</editor-fold> public void pop_back() { assert Native.$bool(Native.$not(empty())) : "pop_back() on empty list!"; ilist_iterator<NodeTy> t = end(); erase(t.$preDec()); } // Special forms of insert... /*template <class InIt> TEMPLATE*/ //<editor-fold defaultstate="collapsed" desc="llvm::iplist::insert"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 572, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 620, FQN="llvm::iplist::insert", NM="Tpl__ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EET_S4_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=Tpl__ZN4llvm6iplist6insertENS_14ilist_iteratorIT_EET_S4_") //</editor-fold> public </*class*/ InIt extends type$iterator<?, NodeTy>> void insert$T(ilist_iterator<NodeTy> where, InIt first, InIt last) { for (; Native.$noteq_iter(first, last); first.$preInc()) { insert_ilist_iterator$NodeTy_T$P(where, $Deref(first.$star())); } } // Splice members - defined in terms of transfer... //<editor-fold defaultstate="collapsed" desc="llvm::iplist::splice"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 577, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 625, FQN="llvm::iplist::splice", NM="_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EE") //</editor-fold> public void splice(ilist_iterator<NodeTy> where, final iplist<NodeTy> /*&*/ L2) { if (Native.$not(L2.empty())) { transfer(where, L2, L2.begin(), L2.end()); } } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::splice"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 581, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 629, FQN="llvm::iplist::splice", NM="_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_") //</editor-fold> public void splice(ilist_iterator<NodeTy> where, final iplist<NodeTy> /*&*/ L2, ilist_iterator<NodeTy> first) { ilist_iterator<NodeTy> last = first; last.$preInc(); if (Native.$bool(Native.$eq_iter(where, first)) || Native.$bool(Native.$eq_iter(where, last))) { return; // No change } transfer(where, L2, first, last); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::splice"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 586, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 634, FQN="llvm::iplist::splice", NM="_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_S3_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EES3_S3_") //</editor-fold> public void splice(ilist_iterator<NodeTy> where, final iplist<NodeTy> /*&*/ L2, ilist_iterator<NodeTy> first, ilist_iterator<NodeTy> last) { if (Native.$noteq_iter(first, last)) { transfer(where, L2, first, last); } } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::splice"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 589, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 637, FQN="llvm::iplist::splice", NM="_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EERS2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EERS2_") //</editor-fold> public void splice_ilist_iterator$NodeTy_iplist$NodeTy$Traits_T$R(ilist_iterator<NodeTy> where, final iplist<NodeTy> /*&*/ L2, final NodeTy /*&*/ N) { splice(where, L2, new ilist_iterator<NodeTy>(N, $traits())); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::splice"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 592, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 640, FQN="llvm::iplist::splice", NM="_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EEPS2_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist6spliceENS_14ilist_iteratorIT_EERNS_6iplistIS2_T0_EEPS2_") //</editor-fold> public void splice_ilist_iterator$NodeTy_iplist$NodeTy$Traits_T$P(ilist_iterator<NodeTy> where, final iplist<NodeTy> /*&*/ L2, NodeTy /*P*/ N) { splice(where, L2, new ilist_iterator<NodeTy>(N, $traits())); } /*template <class Compare> TEMPLATE*/ //<editor-fold defaultstate="collapsed" desc="llvm::iplist::merge"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 597, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 644, FQN="llvm::iplist::merge", NM="Tpl__ZN4llvm6iplist5mergeERNS_6iplistIT_T0_EET_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=Tpl__ZN4llvm6iplist5mergeERNS_6iplistIT_T0_EET_") //</editor-fold> public </*class*/ Compare> void merge$T(iplist<NodeTy/*, Traits*/> /*&*/ Right, Compare comp) { throw new UnsupportedOperationException("EmptyBody"); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::merge"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 614, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 662, FQN="llvm::iplist::merge", NM="_ZN4llvm6iplist5mergeERNS_6iplistIT_T0_EE", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist5mergeERNS_6iplistIT_T0_EE") //</editor-fold> public void merge(iplist<NodeTy/*, Traits*/> /*&*/ Right) { throw new UnsupportedOperationException("EmptyBody"); } /*template <class Compare> TEMPLATE*/ //<editor-fold defaultstate="collapsed" desc="llvm::iplist::sort"> @Converted(kind = Converted.Kind.AUTO_NO_BODY, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 617, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 664, FQN="llvm::iplist::sort", NM="Tpl__ZN4llvm6iplist4sortET_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=Tpl__ZN4llvm6iplist4sortET_") //</editor-fold> public </*class*/ Compare> void sort$T(Compare comp) { throw new UnsupportedOperationException("EmptyBody"); } //<editor-fold defaultstate="collapsed" desc="llvm::iplist::sort"> @Converted(kind = Converted.Kind.AUTO_NO_BODY, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 641, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 689, FQN="llvm::iplist::sort", NM="_ZN4llvm6iplist4sortEv", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZN4llvm6iplist4sortEv") //</editor-fold> public void sort() { throw new UnsupportedOperationException("EmptyBody"); } /// \brief Get the previous node, or \c nullptr for the list head. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getPrevNode"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 644, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 692, FQN="llvm::iplist::getPrevNode", NM="_ZNK4llvm6iplist11getPrevNodeERT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist11getPrevNodeERT_") //</editor-fold> public NodeTy /*P*/ getPrevNode_T$R(final NodeTy /*&*/ N) /*const*/ { ilist_iterator<NodeTy> I = N.getIterator(); if (Native.$eq_iter(I, begin())) { return null; } return /*$AddrOf($Deref(*/ std.prev(I).$star(); } /// \brief Get the previous node, or \c nullptr for the list head. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getPrevNode"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 651, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 699, FQN="llvm::iplist::getPrevNode", NM="_ZNK4llvm6iplist11getPrevNodeERKT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist11getPrevNodeERKT_") //</editor-fold> public /*const*/ NodeTy /*P*/ getPrevNode_T$C$R(final /*const*/ NodeTy /*&*/ N) /*const*/ { return getPrevNode_T$R(((/*const_cast*/NodeTy /*&*/ )(N))); } /// \brief Get the next node, or \c nullptr for the list tail. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getNextNode"> @Converted(kind = Converted.Kind.AUTO, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 656, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 704, FQN="llvm::iplist::getNextNode", NM="_ZNK4llvm6iplist11getNextNodeERT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist11getNextNodeERT_") //</editor-fold> public NodeTy /*P*/ getNextNode_T$R(final NodeTy /*&*/ N) /*const*/ { /*<dependent type>*/ilist_iterator<NodeTy> Next = std.next(N.getIterator()); if (Native.$eq_iter(Next, end())) { return null; } return /*$AddrOf($Deref(*/ Next.$star(); } /// \brief Get the next node, or \c nullptr for the list tail. //<editor-fold defaultstate="collapsed" desc="llvm::iplist::getNextNode"> @Converted(kind = Converted.Kind.MANUAL_COMPILATION, source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", line = 663, old_source = "${LLVM_SRC}/llvm/include/llvm/ADT/ilist.h", old_line = 711, FQN="llvm::iplist::getNextNode", NM="_ZNK4llvm6iplist11getNextNodeERKT_", cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/Transforms/Scalar/DCE.cpp -nm=_ZNK4llvm6iplist11getNextNodeERKT_") //</editor-fold> public /*const*/ NodeTy /*P*/ getNextNode_T$C$R(final /*const*/ NodeTy /*&*/ N) /*const*/ { return getNextNode_T$R(((/*const_cast*/NodeTy /*&*/ )(N))); } ////////////////////////////////////////////////////////////// // EXTRA MEMBERS: BEGIN @Override public java.util.Iterator<NodeTy> iterator() { return new JavaIterator<>(begin(), end()); } protected final ilist_traits<NodeTy> $traits() { return $traits; } protected abstract ilist_traits<NodeTy> $createTraits(); private final ilist_traits<NodeTy> $traits; { ilist_traits<NodeTy> Traits = $createTraits(); assert Traits != $createTraits() : "must return different instances, because requested Sentinels will be mutable object"; $traits = Traits; } private final type$ref<NodeTy> Head$ref = new type$ref<NodeTy>() { public @Override NodeTy $deref() { return Head; } public @Override NodeTy $set(NodeTy value) { Head = value; return Head; } }; @Override public NodeTy createNode(NodeTy V) { return $traits().createNode(V); } @Override public void deleteNode(iplist</*typename*/ NodeTy> list, NodeTy V) { assert list == this; $traits().deleteNode(list, V); } @Override public void addNodeToList(iplist</*typename*/ NodeTy> list, NodeTy $Prm0) { assert list == this; $traits().addNodeToList(list, $Prm0); } @Override public void removeNodeFromList(iplist</*typename*/ NodeTy> list, NodeTy $Prm0) { assert list == this; $traits().removeNodeFromList(list, $Prm0); } @Override public void transferNodesFromList(ilist_node_traits<NodeTy> $Prm0, ilist_iterator<NodeTy> $Prm1, ilist_iterator<NodeTy> $Prm2) { $traits().transferNodesFromList($Prm0, $Prm1, $Prm2); } @Override public NodeTy createSentinel() { return $traits().createSentinel(); } @Override public void destroySentinel(NodeTy N) { $traits().destroySentinel(N); } @Override public NodeTy provideInitialHead() { return $traits().provideInitialHead(); } @Override public NodeTy ensureHead(type$ref<NodeTy> Head) { return $traits().ensureHead(Head$ref); } @Override public void noteHead(NodeTy NewHead, NodeTy Sentinel) { $traits().noteHead(NewHead, Sentinel); } @Override public NodeTy getPrev(NodeTy N) { return $traits().getPrev(N); } @Override public NodeTy getNext(NodeTy N) { return $traits().getNext(N); } @Override public void setPrev(NodeTy N, NodeTy Prev) { $traits().setPrev(N, Prev); } @Override public void setNext(NodeTy N, NodeTy Next) { $traits().setNext(N, Next); } // EXTRA MEMBERS: END ////////////////////////////////////////////////////////////// @Override public String toString() { return "" + "Head=" + NativeTrace.getIdentityStr(Head); } }
true
9041e84e19cdee2d565647a3f865199cf2a686c4
Java
openanthem-admin/prev-nimbus-core
/nimbus-test/src/main/java/com/antheminc/oss/nimbus/test/domain/support/utils/ParamUtils.java
UTF-8
5,302
2.25
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Copyright 2016-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.antheminc.oss.nimbus.test.domain.support.utils; import java.util.Locale; import com.antheminc.oss.nimbus.domain.cmd.exec.CommandExecution.MultiOutput; import com.antheminc.oss.nimbus.domain.cmd.exec.CommandExecution.Output; import com.antheminc.oss.nimbus.domain.model.state.EntityState.Param; import com.antheminc.oss.nimbus.domain.model.state.EntityState.Param.LabelState; import com.antheminc.oss.nimbus.support.Holder; /** * @author Tony Lopez * */ public class ParamUtils { /** * <p> Given a framework response object, {@code response}, this method * deciphers and attempts to locate a value from each of the * {@link MultiOutput}'s {@link Output#getValue()} values that has is of * type {@code clazz}. If multiple params are found, only the first will be * returned. * * @param response the response received as a result of the framework * request * @param clazz the expected type to identify and return * @return the param identified within the response of the expected type */ @SuppressWarnings("unchecked") public static <T> T extractResponseByClass(Object response, Class<T> clazz) { if (null == response) { throw new RuntimeException("response must not be null"); } if (null == clazz) { throw new RuntimeException("clazz must not be null"); } Holder<MultiOutput> resp = (Holder<MultiOutput>) response; MultiOutput multiOutput = resp.getState(); for (Output<?> output : multiOutput.getOutputs()) { if (output.getValue().getClass().isAssignableFrom(clazz)) { return (T) output.getValue(); } } throw new RuntimeException("Unable to locate param in response having class'" + clazz.getSimpleName() + "."); } /** * <p> Given a framework response object, {@code response}, this method * deciphers and attempts to locate a param from each of the * {@link MultiOutput}'s {@link Output#getValue()} values that has a URI * path ending with {@code paramPathEndsWith}. If multiple params are found, * only the first will be returned. <p> If {@code paramPathEndsWith} is * {@code null} this method will return the result of * {@link MultiOutput#getSingleResult()}. * * @throws RuntimeException if {@code paramPathEndsWith} is provided and not * contained by any of the outputs deciphered in * {@code response} * @param response the response received as a result of the framework * request * @param paramPathEndsWith the ending path of the param to identify, from * the set of params received in the {@code response} * @return the param identified within the response ending with * {@code paramPathEndsWith} */ @SuppressWarnings("unchecked") public static <T> Param<T> extractResponseByParamPath(Object response, String paramPathEndsWith) { if (null == response) { throw new RuntimeException("response must not be null"); } Holder<MultiOutput> resp = (Holder<MultiOutput>) response; MultiOutput multiOutput = resp.getState(); if (null == paramPathEndsWith) { return (Param<T>) multiOutput.getSingleResult(); } for (Output<?> output : multiOutput.getOutputs()) { if (output.getValue() instanceof Param) { Param<?> param = (Param<?>) output.getValue(); if (param.getPath().endsWith(paramPathEndsWith)) { return (Param<T>) param; } } } throw new RuntimeException("Unable to locate param in response ending with '" + paramPathEndsWith + "."); } /** * <p>Find label text associated with {@code param} by the system default * locale. <p>This method will search the underlying label state by * inspecting all labels within the state and returning only the text of the * found label. If unable to be found, {@code null} will be returned. * @param param the param instance to search within * @return the text of the found label */ public static <T> String getLabelText(Param<T> param) { return getLabelText(param, Locale.getDefault().toLanguageTag()); } /** * <p>Find label text associated with {@code param} by a given * {@code localeLanguageTag} <p>This method will search the underlying label * state by inspecting all labels within the state and returning only the * text of the found label. If unable to be found, {@code null} will be * returned. * @param param the param instance to search within * @param localeLanguageTag the locale to search for * @return the text of the found label */ public static <T> String getLabelText(Param<T> param, String localeLanguageTag) { LabelState labelState = param.getLabel(localeLanguageTag); return null != labelState ? labelState.getText() : null; } }
true
993d8c0b12743038b2e7bca218ae2384fbfb7289
Java
vran-dev/PrettyZoo
/app/gen/main/java/cc/cc1234/antlr4/properties/PropertiesParser.java
UTF-8
12,806
1.757813
2
[ "Apache-2.0" ]
permissive
package cc.cc1234.antlr4.properties;// Generated from ..\resources\grammars\Properties.g4 by ANTLR 4.9 import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import java.util.List; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class PropertiesParser extends Parser { static { RuntimeMetaData.checkVersion("4.9", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, TEXT=2, STRING=3, COMMENT=4, TERMINATOR=5; public static final int RULE_propertiesFile = 0, RULE_row = 1, RULE_decl = 2, RULE_key = 3, RULE_value = 4, RULE_comment = 5; private static String[] makeRuleNames() { return new String[] { "propertiesFile", "row", "decl", "key", "value", "comment" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'='" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, null, "TEXT", "STRING", "COMMENT", "TERMINATOR" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "Properties.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public PropertiesParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class PropertiesFileContext extends ParserRuleContext { public List<RowContext> row() { return getRuleContexts(RowContext.class); } public RowContext row(int i) { return getRuleContext(RowContext.class,i); } public PropertiesFileContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_propertiesFile; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterPropertiesFile(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitPropertiesFile(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitPropertiesFile(this); else return visitor.visitChildren(this); } } public final PropertiesFileContext propertiesFile() throws RecognitionException { PropertiesFileContext _localctx = new PropertiesFileContext(_ctx, getState()); enterRule(_localctx, 0, RULE_propertiesFile); int _la; try { enterOuterAlt(_localctx, 1); { setState(13); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(12); row(); } } setState(15); _errHandler.sync(this); _la = _input.LA(1); } while ( _la==TEXT || _la==COMMENT ); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class RowContext extends ParserRuleContext { public CommentContext comment() { return getRuleContext(CommentContext.class,0); } public DeclContext decl() { return getRuleContext(DeclContext.class,0); } public RowContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_row; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterRow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitRow(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitRow(this); else return visitor.visitChildren(this); } } public final RowContext row() throws RecognitionException { RowContext _localctx = new RowContext(_ctx, getState()); enterRule(_localctx, 2, RULE_row); try { enterOuterAlt(_localctx, 1); { setState(19); _errHandler.sync(this); switch (_input.LA(1)) { case COMMENT: { setState(17); comment(); } break; case TEXT: { setState(18); decl(); } break; default: throw new NoViableAltException(this); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class DeclContext extends ParserRuleContext { public KeyContext key() { return getRuleContext(KeyContext.class,0); } public ValueContext value() { return getRuleContext(ValueContext.class,0); } public DeclContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_decl; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterDecl(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitDecl(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitDecl(this); else return visitor.visitChildren(this); } } public final DeclContext decl() throws RecognitionException { DeclContext _localctx = new DeclContext(_ctx, getState()); enterRule(_localctx, 4, RULE_decl); try { enterOuterAlt(_localctx, 1); { setState(21); key(); setState(22); match(T__0); setState(24); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,2,_ctx) ) { case 1: { setState(23); value(); } break; } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class KeyContext extends ParserRuleContext { public TerminalNode TEXT() { return getToken(PropertiesParser.TEXT, 0); } public KeyContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_key; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterKey(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitKey(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitKey(this); else return visitor.visitChildren(this); } } public final KeyContext key() throws RecognitionException { KeyContext _localctx = new KeyContext(_ctx, getState()); enterRule(_localctx, 6, RULE_key); try { enterOuterAlt(_localctx, 1); { setState(26); match(TEXT); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ValueContext extends ParserRuleContext { public TerminalNode TEXT() { return getToken(PropertiesParser.TEXT, 0); } public TerminalNode STRING() { return getToken(PropertiesParser.STRING, 0); } public ValueContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_value; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterValue(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitValue(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitValue(this); else return visitor.visitChildren(this); } } public final ValueContext value() throws RecognitionException { ValueContext _localctx = new ValueContext(_ctx, getState()); enterRule(_localctx, 8, RULE_value); int _la; try { enterOuterAlt(_localctx, 1); { setState(28); _la = _input.LA(1); if ( !(_la==TEXT || _la==STRING) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CommentContext extends ParserRuleContext { public TerminalNode COMMENT() { return getToken(PropertiesParser.COMMENT, 0); } public CommentContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_comment; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).enterComment(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PropertiesListener ) ((PropertiesListener)listener).exitComment(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PropertiesVisitor ) return ((PropertiesVisitor<? extends T>)visitor).visitComment(this); else return visitor.visitChildren(this); } } public final CommentContext comment() throws RecognitionException { CommentContext _localctx = new CommentContext(_ctx, getState()); enterRule(_localctx, 10, RULE_comment); try { enterOuterAlt(_localctx, 1); { setState(30); match(COMMENT); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\7#\4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\3\2\6\2\20\n\2\r\2\16\2\21\3\3\3\3"+ "\5\3\26\n\3\3\4\3\4\3\4\5\4\33\n\4\3\5\3\5\3\6\3\6\3\7\3\7\3\7\2\2\b\2"+ "\4\6\b\n\f\2\3\3\2\4\5\2\37\2\17\3\2\2\2\4\25\3\2\2\2\6\27\3\2\2\2\b\34"+ "\3\2\2\2\n\36\3\2\2\2\f \3\2\2\2\16\20\5\4\3\2\17\16\3\2\2\2\20\21\3\2"+ "\2\2\21\17\3\2\2\2\21\22\3\2\2\2\22\3\3\2\2\2\23\26\5\f\7\2\24\26\5\6"+ "\4\2\25\23\3\2\2\2\25\24\3\2\2\2\26\5\3\2\2\2\27\30\5\b\5\2\30\32\7\3"+ "\2\2\31\33\5\n\6\2\32\31\3\2\2\2\32\33\3\2\2\2\33\7\3\2\2\2\34\35\7\4"+ "\2\2\35\t\3\2\2\2\36\37\t\2\2\2\37\13\3\2\2\2 !\7\6\2\2!\r\3\2\2\2\5\21"+ "\25\32"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
true
a2f93cf31fed9fbc69172fdda36708d07705a77d
Java
amymaries/C195AmySaunders
/src/Model/First_Level_Division.java
UTF-8
1,158
3.09375
3
[]
no_license
package Model; /** * @author ASaunders */ import java.sql.Timestamp; import java.time.LocalDateTime; /** * This class models state/province (first-level-division) objects from the DB. */ public class First_Level_Division { private int divisionID; private String division; private LocalDateTime createDate; private String createdBy; private Timestamp lastUpdate; private String lastUpdatedBy; private int countryID; /** * FLD constructor creates new FLD objects. * @param countryID int country id * @param division string division name */ public First_Level_Division(int countryID, String division) { this.countryID = countryID; this.division = division; } /** * @return division name as string */ public String getDivision() { return this.division; } /** * @return int country id */ public int getCountryID() { return countryID; } /** * Overrides toString method for better formatting * @return division name */ @Override public String toString() { return division; } }
true
e8750559219e79d720312b314f15ea4afdfeb63c
Java
frle10/java-course-homeworks
/hw10-0036506288/src/main/java/hr/fer/zemris/java/gui/layouts/package-info.java
UTF-8
261
1.898438
2
[]
no_license
/** * This package contains classes that together implement a custom * layout manager for Java Swing GUI. This layout manager will be * used to implement a calculator with GUI for problem 2 of the * 10th homework. */ package hr.fer.zemris.java.gui.layouts;
true
3ed145c4418ef6a8c0691936df3ba1d9ebe6a735
Java
AlexMalei/MPP.Java.SchoolJournal
/server/src/main/java/school/journal/repository/specification/subject/SubjectSpecification.java
UTF-8
237
1.632813
2
[]
no_license
package school.journal.repository.specification.subject; import school.journal.entity.Subject; import school.journal.repository.specification.Specification; public abstract class SubjectSpecification extends Specification<Subject> { }
true
89e04ea0e50af154d7a22090737d42e12fdbf2d6
Java
Cesaramello/progmobile-android
/app/src/main/java/com/example/progmobile_android/model/dao/UserDAO.java
UTF-8
5,299
2.28125
2
[]
no_license
package com.example.progmobile_android.model.dao; import android.content.Context; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.toolbox.StringRequest; import com.example.progmobile_android.model.entity.CreateError; import com.example.progmobile_android.model.entity.User; import com.example.progmobile_android.model.entity.UserToken; import com.example.progmobile_android.model.util.Constants; import com.example.progmobile_android.model.util.ServerCallback; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class UserDAO { private Gson gson; private Context context; private String url = Constants.URL; private UserToken userToken; public UserDAO(Context context) { this.context = context; this.gson = new Gson(); } public void login(String login, String password, final ServerCallback serverCallback) { final String endPoint = url + "/authentication"; StringRequest stringRequest = new StringRequest(Request.Method.POST, endPoint, response -> { Log.d("login", response); try { JSONObject jsonFromResponse = new JSONObject(response); JSONObject jsonUser = jsonFromResponse.getJSONObject("user"); String token = jsonFromResponse.getString("token"); User user = gson.fromJson(jsonUser.toString(), User.class); this.userToken = new UserToken(user, token); serverCallback.onSuccess(userToken); } catch (JSONException e) { e.printStackTrace(); serverCallback.onError(null); } }, error -> { Log.d("login", error.toString()); serverCallback.onError(null); }) { @Override public byte[] getBody() { HashMap<String, String> params = new HashMap<>(); params.put("login", login); params.put("password", password); return new JSONObject(params).toString().getBytes(); } @Override public String getBodyContentType() { return "application/json"; } }; Repository.getInstance(context).addToRequestQueue(stringRequest); } public void logout(final ServerCallback serverCallback) { final String endPoint = url + "/authentication"; StringRequest stringRequest = new StringRequest(Request.Method.DELETE, endPoint, response -> { userToken = null; serverCallback.onSuccess(true); }, error -> { Log.d("logout", error.toString()); serverCallback.onError(false); }) { @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("userId", String.valueOf(userToken.getUser().getId())); headers.put("token", userToken.getToken()); return headers; } }; Repository.getInstance(context).addToRequestQueue(stringRequest); } public void createUser(String login, String name, String password, String email, final ServerCallback serverCallback) { final String endPoint = url + "/user"; StringRequest stringRequest = new StringRequest(Request.Method.POST, endPoint, response -> { Log.d("createUser", response); User user = gson.fromJson(response, User.class); serverCallback.onSuccess(user); }, error -> { Log.d("createUser", error.toString()); String s = new String(error.networkResponse.data, StandardCharsets.UTF_8); CreateError strings = gson.fromJson(s, CreateError.class); serverCallback.onError(strings); }) { @Override public byte[] getBody() { HashMap<String, String> params = new HashMap<>(); params.put("login", login); params.put("password", password); params.put("name", name); params.put("email", email); return new JSONObject(params).toString().getBytes(); } @Override public String getBodyContentType() { return "application/json"; } }; Repository.getInstance(context).addToRequestQueue(stringRequest); } public void getUser(ServerCallback serverCallback) { if (userToken != null) serverCallback.onSuccess(userToken); else serverCallback.onError(null); } }
true
96d9f158b87192ba7f12ea64c3203872fb7d5348
Java
dlxotn216/demo-ojt-api
/src/test/java/ojt/crscube/board/interfaces/dto/BoardDtoTest.java
UTF-8
705
2.28125
2
[]
no_license
package ojt.crscube.board.interfaces.dto; import org.junit.Test; import java.lang.reflect.Constructor; import java.time.LocalDate; /** * Created by Lee Tae Su on 2019-04-25. */ public class BoardDtoTest { @Test public void 생성자_테스트() throws Exception { for (Constructor<?> constructor : BoardDto.class.getDeclaredConstructors()) { constructor.setAccessible(true); constructor.newInstance(); } new BoardDto.BoardCreateRequest("awefwaf", "Awefawf"); new BoardDto.BoardsSearchResponse(1L, "awet", LocalDate.now(), "awef", false); new BoardDto.BoardsSearchResponse(1L, 2L, "Awef", LocalDate.now(), "awef", false); } }
true