hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
31190e574385361041d29511e0652b06be36710b
148
package org.twak.utils.ui; public class Cancellable { public boolean cancelled = false; public void cancel() { this.cancelled = true; } }
13.454545
34
0.695946
b801249aa438e26a463406d1acd594f677015174
798
/** * Created by geron on 23.04.2017. */ public class GraphMain { public static void main(String[] args) { BST bt = FileReader.readProfiles("profiles.txt"); Graph g = FileReader.readFriends("friends.txt", bt); System.out.println("Common friends of Freddie Mercury and Friendly" + " Ghost Casper are: "); g.commonFriends(bt.find("Freddie Mercury"), bt.find("Friendly Ghost Casper")).printAlphabetical(); System.out.println("-------------------------------------------------"); System.out.println("Common friends of Andy Warhol and Friendly" + " Ghost Casper are: "); g.commonFriends(bt.find("Andy Warhol"), bt.find("Friendly Ghost Casper")).printAlphabetical(); } }
36.272727
80
0.565163
9620fc4cc48bdbd1389b8ac03837dfb90997b732
132
package xp.kdm.build; import lombok.NoArgsConstructor; @NoArgsConstructor() public class BuildComponent extends BuildResource { }
16.5
51
0.818182
cc023fe0c6640295e5e0ff359c4bd439901e7341
1,751
package org.apereo.cas.adaptors.radius.server; import org.apereo.cas.adaptors.radius.RadiusClientFactory; import org.apereo.cas.adaptors.radius.RadiusProtocol; import lombok.Setter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import net.jradius.client.RadiusClient; import net.jradius.packet.AccessRequest; import net.jradius.packet.RadiusResponse; /** * Implementation of a RadiusServer that utilizes the JRadius packages available * at <a href="http://jradius.sf.net">http://jradius.sf.net</a>. * * @author Scott Battaglia * @author Marvin S. Addison * @author Misagh Moayyed * @since 6.0.0 */ @Slf4j @ToString @Setter public class BlockingRadiusServer extends AbstractRadiusServer { private static final long serialVersionUID = -2567137135937670129L; public BlockingRadiusServer(final RadiusProtocol protocol, final RadiusClientFactory radiusClientFactory) { super(protocol, radiusClientFactory, 1, null, null, -1, -1, null, -1, -1); } public BlockingRadiusServer(final RadiusProtocol protocol, final RadiusClientFactory clientFactory, final int retries, final String nasIpAddress, final String nasIpv6Address, final long nasPort, final long nasPortId, final String nasIdentifier, final long nasRealPort, final long nasPortType) { super(protocol, clientFactory, retries, nasIpAddress, nasIpv6Address, nasPort, nasPortId, nasIdentifier, nasRealPort, nasPortType); } @Override protected RadiusResponse authenticateRequest(final RadiusClient client, final AccessRequest accessRequest) throws Exception { return client.authenticate(accessRequest, getRadiusAuthenticator(), getRetries()); } }
39.795455
139
0.748715
87f1d8a80128c5d5603ca27bbef76a530367c2b8
418
package com.github.instagram4j.instagram4j.responses.commerce; import com.github.instagram4j.instagram4j.models.commerce.Product; import com.github.instagram4j.instagram4j.models.user.Profile; import com.github.instagram4j.instagram4j.responses.IGResponse; import lombok.Data; @Data public class CommerceProductsDetailsResponse extends IGResponse { private Profile merchant; private Product product_item; }
29.857143
66
0.837321
57a1996d5e0ee9b26ee2e0bf596b5bd9e6d1213b
363
package com.phm.comp.distance; import com.phm.core.ParametersContainer; import org.apache.commons.math3.linear.RealVector; /** * * @author phm */ public class BlankDistanceMeasure implements DistanceMeasure { @Override public DistanceInfo measure(RealVector sc1, RealVector sc2, ParametersContainer pc) { return new DistanceInfo (); } }
21.352941
89
0.741047
37c4072fcd2f32f126869ae959b5a4d3a3dd0894
778
package com.zero.hycache.tests; import com.zero.hycache.enhance.HyCacheEnhancer; import com.zero.hycache.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StopWatch; /** * @author zero * @date Create on 2022/2/17 * @description */ public class PerformanceTestsMain { private static final Logger logger = LoggerFactory.getLogger(PerformanceTestsMain.class); public static void main(String[] args) { HyCacheEnhancer.start(); UserService userService = new UserService(); StopWatch stopWatch=new StopWatch(); stopWatch.start(); for(int i=0;i<10000000;i++){ userService.getUser(); } stopWatch.stop(); logger.info("结束测试"); } }
25.096774
93
0.682519
3bb6a0e55a3d59eb5173eff1c7961b6aa949a350
7,242
package org.openrepose.components.apivalidator.filter; import com.rackspace.com.papi.components.checker.Validator; import com.rackspace.papi.commons.util.http.HttpStatusCode; import com.rackspace.papi.commons.util.http.OpenStackServiceHeader; import com.rackspace.papi.commons.util.http.header.HeaderValue; import com.rackspace.papi.commons.util.http.header.HeaderValueImpl; import com.rackspace.papi.commons.util.servlet.http.MutableHttpServletRequest; import com.rackspace.papi.commons.util.servlet.http.MutableHttpServletResponse; import com.rackspace.papi.filter.logic.FilterDirector; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import javax.servlet.FilterChain; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; @RunWith(Enclosed.class) public class ApiValidatorHandlerTest { public static class WhenApplyingValidators { private ValidatorInfo defaultValidatorInfo; private ValidatorInfo role1ValidatorInfo; private ValidatorInfo role2ValidatorInfo; private Validator defaultValidator; private Validator role1Validator; private Validator role2Validator; private ApiValidatorHandler instance; private FilterChain chain; private MutableHttpServletRequest request; private MutableHttpServletResponse response; private ValidatorInfo nullValidatorInfo; private ValidatorInfo blowupValidatorInfo; private Validator blowupValidator; @Before public void setup() { chain = mock(FilterChain.class); request = mock(MutableHttpServletRequest.class); response = mock(MutableHttpServletResponse.class); defaultValidator = mock(Validator.class); defaultValidatorInfo = new ValidatorInfo(Arrays.asList("defaultrole"), "defaultwadl", null, null); defaultValidatorInfo.setValidator(defaultValidator); role1Validator = mock(Validator.class); role1ValidatorInfo = new ValidatorInfo(Arrays.asList("role1"), "role1wadl", null, null); role1ValidatorInfo.setValidator(role1Validator); role2Validator = mock(Validator.class); role2ValidatorInfo = new ValidatorInfo(Arrays.asList("role2"), "role2wadl", null, null); role2ValidatorInfo.setValidator(role2Validator); nullValidatorInfo = mock(ValidatorInfo.class); when(nullValidatorInfo.getRoles()).thenReturn(Arrays.asList("nullValidator")); when(nullValidatorInfo.getValidator()).thenReturn(null); blowupValidator = mock(Validator.class); when(blowupValidator.validate(request, response, chain)).thenThrow(new RuntimeException("Test")); blowupValidatorInfo = new ValidatorInfo(Arrays.asList("blowupValidator"), "blowupWadl", null, null); blowupValidatorInfo.setValidator(blowupValidator); List<ValidatorInfo> validators = new ArrayList<ValidatorInfo>(); validators.add(defaultValidatorInfo); validators.add(role1ValidatorInfo); validators.add(role2ValidatorInfo); validators.add(nullValidatorInfo); validators.add(blowupValidatorInfo); instance = new ApiValidatorHandler(defaultValidatorInfo, validators, false, null); instance.setFilterChain(chain); } @Test public void shouldCallDefaultValidatorWhenNoRoleMatch() { instance.handleRequest(request, response); verify(defaultValidator).validate(request, response, chain); } @Test public void shouldCallValidatorForRole() { List<HeaderValue> roles = new ArrayList<HeaderValue>(); roles.add(new HeaderValueImpl("role1")); when(request.getPreferredHeaderValues(eq(OpenStackServiceHeader.ROLES.toString()), any(HeaderValueImpl.class))).thenReturn(roles); instance.handleRequest(request, response); verify(role1Validator).validate(request, response, chain); } @Test public void shouldHandleNullValidators() { List<HeaderValue> roles = new ArrayList<HeaderValue>(); roles.add(new HeaderValueImpl("nullValidator")); when(request.getPreferredHeaderValues(eq(OpenStackServiceHeader.ROLES.toString()), any(HeaderValueImpl.class))).thenReturn(roles); FilterDirector director = instance.handleRequest(request, response); verify(nullValidatorInfo).getValidator(); assertEquals(HttpStatusCode.BAD_GATEWAY, director.getResponseStatus()); } @Test public void shouldHandleExceptionsInValidators() { List<HeaderValue> roles = new ArrayList<HeaderValue>(); roles.add(new HeaderValueImpl("blowupValidator")); when(request.getPreferredHeaderValues(eq(OpenStackServiceHeader.ROLES.toString()), any(HeaderValueImpl.class))).thenReturn(roles); FilterDirector director = instance.handleRequest(request, response); verify(blowupValidator).validate(request, response, chain); assertEquals(HttpStatusCode.BAD_GATEWAY, director.getResponseStatus()); } @Test public void shouldAddDefaultValidatorAsLeastPriorityWhenMultiMatch() { List<HeaderValue> roles = new ArrayList<HeaderValue>(); roles.add(new HeaderValueImpl("role1")); List<ValidatorInfo> validators = new ArrayList<ValidatorInfo>(); validators.add(role1ValidatorInfo); validators.add(role2ValidatorInfo); instance = new ApiValidatorHandler(defaultValidatorInfo, validators, true, null); List<ValidatorInfo> validatorsForRole = instance.getValidatorsForRole(roles); assertEquals(validatorsForRole.get(0), defaultValidatorInfo); assertEquals(validatorsForRole.get(1), role1ValidatorInfo); } @Test public void shouldRetainValidatorOrderWhenMultiMatchAndHasDefaultRole() { List<HeaderValue> roles = new ArrayList<HeaderValue>(); roles.add(new HeaderValueImpl("role1")); roles.add(new HeaderValueImpl("role2")); roles.add(new HeaderValueImpl("defaultrole")); List<ValidatorInfo> validators = new ArrayList<ValidatorInfo>(); validators.add(role1ValidatorInfo); validators.add(defaultValidatorInfo); validators.add(role2ValidatorInfo); instance = new ApiValidatorHandler(defaultValidatorInfo, validators, true, null); List<ValidatorInfo> validatorsForRole = instance.getValidatorsForRole(roles); assertEquals(validatorsForRole.get(0), role1ValidatorInfo); assertEquals(validatorsForRole.get(1), defaultValidatorInfo); assertEquals(validatorsForRole.get(2), role2ValidatorInfo); } } }
44.981366
142
0.687379
835c98a83097b3b9859a91735b139c0205b7da4a
2,769
package com.cv.projects; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Farm { byte farmland[][]; Farm (int rows, int cols, String[] barrens) { farmland = new byte[rows][cols]; ArrayList<int[]> barrenRects = new ArrayList<>(); for (int i=0; i<barrens.length; i++) { String[] splitVertices = barrens[i].split(" "); barrenRects.add(new int[splitVertices.length]); for (int j=0; j<splitVertices.length; j++) { barrenRects.get(i)[j] = Integer.parseInt(splitVertices[j]); } // System.out.println("***** barrenRects[" + i + "]:" + Arrays.toString(barrenRects.get(i))); //Mark barren land-units as 1 for (int k = barrenRects.get(i)[0]; k<=barrenRects.get(i)[2]; k++) for (int l = barrenRects.get(i)[1]; l<=barrenRects.get(i)[3]; l++) farmland[k][l] = 1; } // System.out.println("***** Initial farm *****"); // printFarm(); // System.out.println("***** ============ *****"); } List<Integer> getAllFertileAreas() { List<Integer> fertileAreaSizes = new ArrayList<>(); for (int i=0; i<farmland.length; i++) { for(int j=0; j<farmland[0].length; j++) { if (farmland[i][j] == 0) { // System.out.println("***** Computing area of land at i="+i+" and j="+j); fertileAreaSizes.add(getFertileAreaSizeDFS(i, j)); // System.out.println("***** Farm for row:" + i + " and col:" + j); // System.out.println("***** ============= *****"); // printFarm(); } } } Collections.sort(fertileAreaSizes); // System.out.println("***** fertileAreaSizes: " + fertileAreaSizes); return fertileAreaSizes; } private int getFertileAreaSizeDFS(int row, int col) { if (row<0 || row>=farmland.length || col<0 || col>=farmland[0].length || farmland[row][col]==1) return 0; int size = 1; farmland[row][col] = 1; //mark visited by marking barren. other numbers than the 1 or 0 can be used if distinction was needed for keeping the farmland for any further processing. Here we do not need so marking 1 is sufficient. if (isValid(row+1, col)) size+=getFertileAreaSizeDFS(row+1, col); if (isValid(row, col+1)) size+=getFertileAreaSizeDFS(row, col+1); if (isValid(row-1, col)) size+=getFertileAreaSizeDFS(row-1, col); if (isValid(row, col-1)) size+=getFertileAreaSizeDFS(row, col-1); // System.out.println ("***** size = "+size); return size; } boolean isValid(int row, int col) { if (row<0 || row>=farmland.length || col<0 || col>=farmland[row].length || farmland[row][col]==1) return false; return true; } void printFarm() { System.out.println("["); for(byte[] arr:farmland) { System.out.println(Arrays.toString(arr)); } System.out.println("]"); System.out.println(); } }
29.457447
228
0.625135
76d2ee39e9c9de6123cccf29b0e7cec2a3810849
11,306
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataplex/v1/resources.proto package com.google.cloud.dataplex.v1; public interface ZoneOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dataplex.v1.Zone) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Output only. The relative resource name of the zone, of the form: * `projects/{project_number}/locations/{location_id}/lakes/{lake_id}/zones/{zone_id}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Output only. The relative resource name of the zone, of the form: * `projects/{project_number}/locations/{location_id}/lakes/{lake_id}/zones/{zone_id}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * Optional. User friendly display name. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The displayName. */ java.lang.String getDisplayName(); /** * * * <pre> * Optional. User friendly display name. * </pre> * * <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for displayName. */ com.google.protobuf.ByteString getDisplayNameBytes(); /** * * * <pre> * Output only. System generated globally unique ID for the zone. This ID will be * different if the zone is deleted and re-created with the same name. * </pre> * * <code>string uid = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The uid. */ java.lang.String getUid(); /** * * * <pre> * Output only. System generated globally unique ID for the zone. This ID will be * different if the zone is deleted and re-created with the same name. * </pre> * * <code>string uid = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for uid. */ com.google.protobuf.ByteString getUidBytes(); /** * * * <pre> * Output only. The time when the zone was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ boolean hasCreateTime(); /** * * * <pre> * Output only. The time when the zone was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ com.google.protobuf.Timestamp getCreateTime(); /** * * * <pre> * Output only. The time when the zone was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder(); /** * * * <pre> * Output only. The time when the zone was last updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the updateTime field is set. */ boolean hasUpdateTime(); /** * * * <pre> * Output only. The time when the zone was last updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The updateTime. */ com.google.protobuf.Timestamp getUpdateTime(); /** * * * <pre> * Output only. The time when the zone was last updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder(); /** * * * <pre> * Optional. User defined labels for the zone. * </pre> * * <code>map&lt;string, string&gt; labels = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ int getLabelsCount(); /** * * * <pre> * Optional. User defined labels for the zone. * </pre> * * <code>map&lt;string, string&gt; labels = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ boolean containsLabels(java.lang.String key); /** Use {@link #getLabelsMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getLabels(); /** * * * <pre> * Optional. User defined labels for the zone. * </pre> * * <code>map&lt;string, string&gt; labels = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.util.Map<java.lang.String, java.lang.String> getLabelsMap(); /** * * * <pre> * Optional. User defined labels for the zone. * </pre> * * <code>map&lt;string, string&gt; labels = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ /* nullable */ java.lang.String getLabelsOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue); /** * * * <pre> * Optional. User defined labels for the zone. * </pre> * * <code>map&lt;string, string&gt; labels = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.lang.String getLabelsOrThrow(java.lang.String key); /** * * * <pre> * Optional. Description of the zone. * </pre> * * <code>string description = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The description. */ java.lang.String getDescription(); /** * * * <pre> * Optional. Description of the zone. * </pre> * * <code>string description = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for description. */ com.google.protobuf.ByteString getDescriptionBytes(); /** * * * <pre> * Output only. Current state of the zone. * </pre> * * <code>.google.cloud.dataplex.v1.State state = 8 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The enum numeric value on the wire for state. */ int getStateValue(); /** * * * <pre> * Output only. Current state of the zone. * </pre> * * <code>.google.cloud.dataplex.v1.State state = 8 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The state. */ com.google.cloud.dataplex.v1.State getState(); /** * * * <pre> * Required. Immutable. The type of the zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.Type type = 9 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The enum numeric value on the wire for type. */ int getTypeValue(); /** * * * <pre> * Required. Immutable. The type of the zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.Type type = 9 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The type. */ com.google.cloud.dataplex.v1.Zone.Type getType(); /** * * * <pre> * Optional. Specification of the discovery feature applied to data in this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.DiscoverySpec discovery_spec = 103 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the discoverySpec field is set. */ boolean hasDiscoverySpec(); /** * * * <pre> * Optional. Specification of the discovery feature applied to data in this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.DiscoverySpec discovery_spec = 103 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The discoverySpec. */ com.google.cloud.dataplex.v1.Zone.DiscoverySpec getDiscoverySpec(); /** * * * <pre> * Optional. Specification of the discovery feature applied to data in this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.DiscoverySpec discovery_spec = 103 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ com.google.cloud.dataplex.v1.Zone.DiscoverySpecOrBuilder getDiscoverySpecOrBuilder(); /** * * * <pre> * Required. Specification of the resources that are referenced by the assets within * this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.ResourceSpec resource_spec = 104 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the resourceSpec field is set. */ boolean hasResourceSpec(); /** * * * <pre> * Required. Specification of the resources that are referenced by the assets within * this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.ResourceSpec resource_spec = 104 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The resourceSpec. */ com.google.cloud.dataplex.v1.Zone.ResourceSpec getResourceSpec(); /** * * * <pre> * Required. Specification of the resources that are referenced by the assets within * this zone. * </pre> * * <code> * .google.cloud.dataplex.v1.Zone.ResourceSpec resource_spec = 104 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.cloud.dataplex.v1.Zone.ResourceSpecOrBuilder getResourceSpecOrBuilder(); /** * * * <pre> * Output only. Aggregated status of the underlying assets of the zone. * </pre> * * <code> * .google.cloud.dataplex.v1.AssetStatus asset_status = 105 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the assetStatus field is set. */ boolean hasAssetStatus(); /** * * * <pre> * Output only. Aggregated status of the underlying assets of the zone. * </pre> * * <code> * .google.cloud.dataplex.v1.AssetStatus asset_status = 105 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The assetStatus. */ com.google.cloud.dataplex.v1.AssetStatus getAssetStatus(); /** * * * <pre> * Output only. Aggregated status of the underlying assets of the zone. * </pre> * * <code> * .google.cloud.dataplex.v1.AssetStatus asset_status = 105 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ com.google.cloud.dataplex.v1.AssetStatusOrBuilder getAssetStatusOrBuilder(); }
25.068736
134
0.619936
a453c36a9eed08e88184d5aeca784ddbf27629e4
40,315
/* * Copyright (c) 2022, Thomas Meaney * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ package com.eintosti.buildsystem.manager; import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; import com.cryptomorin.xseries.messages.Titles; import com.eintosti.buildsystem.BuildSystem; import com.eintosti.buildsystem.config.ConfigValues; import com.eintosti.buildsystem.config.WorldConfig; import com.eintosti.buildsystem.object.world.BuildWorld; import com.eintosti.buildsystem.object.world.Builder; import com.eintosti.buildsystem.object.world.data.WorldStatus; import com.eintosti.buildsystem.object.world.data.WorldType; import com.eintosti.buildsystem.object.world.generator.DeprecatedVoidGenerator; import com.eintosti.buildsystem.object.world.generator.Generator; import com.eintosti.buildsystem.object.world.generator.ModernVoidGenerator; import com.eintosti.buildsystem.util.FileUtils; import com.eintosti.buildsystem.util.UUIDFetcher; import com.eintosti.buildsystem.util.external.PlayerChatInput; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldCreator; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * @author einTosti */ public class WorldManager { private final BuildSystem plugin; private final ConfigValues configValues; private final WorldConfig worldConfig; private final List<BuildWorld> buildWorlds; public WorldManager(BuildSystem plugin) { this.plugin = plugin; this.configValues = plugin.getConfigValues(); this.worldConfig = new WorldConfig(plugin); this.buildWorlds = new ArrayList<>(); } /** * Gets the {@link BuildWorld} by the given name. * * @param worldName The name of the world * @return The world object if one was found, {@code null} otherwise */ public BuildWorld getBuildWorld(String worldName) { return this.buildWorlds.stream() .filter(buildWorld -> buildWorld.getName().equalsIgnoreCase(worldName)) .findFirst() .orElse(null); } /** * Gets the {@link BuildWorld} by the given {@link World}. * * @param world The bukkit world object * @return The world object if one was found, {@code null} otherwise */ public BuildWorld getBuildWorld(World world) { return getBuildWorld(world.getName()); } /** * Gets a list of all {@link BuildWorld}s. * * @return A list of all worlds */ public List<BuildWorld> getBuildWorlds() { return buildWorlds; } /** * Gets a list of all {@link BuildWorld}s created by the given player. * * @param player The player who created the world * @return A list of all worlds created by the given player. */ public List<BuildWorld> getBuildWorldsCreatedByPlayer(Player player) { return getBuildWorlds().stream() .filter(buildWorld -> buildWorld.isCreator(player)) .collect(Collectors.toList()); } /** * Gets a list of all {@link BuildWorld}s created by the given player. * * @param player The player who created the world * @param privateWorld {@code true} if to return private worlds, otherwise {@code false} * @return A list of all worlds created by the given player. */ public List<BuildWorld> getBuildWorldsCreatedByPlayer(Player player, boolean privateWorld) { return getBuildWorldsCreatedByPlayer(player).stream() .filter(buildWorld -> isCorrectVisibility(buildWorld, privateWorld)) .collect(Collectors.toList()); } /** * Gets if a {@link BuildWorld}'s visibility is equal to the given visibility. * * @param buildWorld The world object * @param privateWorld Should the world's visibility be equal to private? * @return {@code true} if the world's visibility is equal to the given visibility, otherwise {@code false} */ public boolean isCorrectVisibility(BuildWorld buildWorld, boolean privateWorld) { if (privateWorld) { return buildWorld.isPrivate(); } else { return !buildWorld.isPrivate(); } } /** * Gets the name (and in doing so removes all illegal characters) of the {@link BuildWorld} the player is trying to create. * If the world is going to be a private world, its name will be equal to the player's name. * * @param player The player who is creating the world * @param worldType The world type * @param template The name of the template world, if any, otherwise {@code null} * @param privateWorld Is world going to be a private world? */ public void startWorldNameInput(Player player, WorldType worldType, @Nullable String template, boolean privateWorld) { if (privateWorld && getBuildWorld(player.getName()) == null) { player.closeInventory(); manageWorldType(player, player.getName(), worldType, template, true); return; } new PlayerChatInput(plugin, player, "enter_world_name", input -> { for (String charString : input.split("")) { if (charString.matches("[^A-Za-z0-9/_-]")) { player.sendMessage(plugin.getString("worlds_world_creation_invalid_characters")); break; } } String worldName = input.replaceAll("[^A-Za-z0-9/_-]", "").replace(" ", "_").trim(); if (worldName.isEmpty()) { player.sendMessage(plugin.getString("worlds_world_creation_name_bank")); return; } player.closeInventory(); manageWorldType(player, worldName, worldType, template, privateWorld); }); } /** * Depending on the {@link BuildWorld}'s {@link WorldType}, the corresponding {@link World} will be generated in a different way. * Then, if the creation of the world was successful and the config is set accordingly, the player is teleported to the world. * * @param player The player who is creating the world * @param worldName The name of the world * @param worldType The world type * @param template The name of the template world. Only if the world is being created with a template, otherwise {@code null} * @param privateWorld Is world going to be a private world? */ private void manageWorldType(Player player, String worldName, WorldType worldType, @Nullable String template, boolean privateWorld) { switch (worldType) { default: if (!createWorld(player, worldName, worldType, privateWorld)) { return; } break; case CUSTOM: if (!createCustomWorld(player, worldName, privateWorld)) { return; } break; case TEMPLATE: if (!createTemplateWorld(player, worldName, ChatColor.stripColor(template), privateWorld)) { return; } break; } if (configValues.isTeleportAfterCreation()) { BuildWorld buildWorld = getBuildWorld(worldName); if (buildWorld == null) { return; } buildWorld.manageUnload(); teleport(player, buildWorld); } } /** * Checks if a world with the given name already exists. * * @param player The player who is creating the world * @param worldName The name of the world * @return Whether if a world with the given name already exists */ private boolean worldExists(Player player, String worldName) { boolean worldExists = getBuildWorld(worldName) != null; File worldFile = new File(Bukkit.getWorldContainer(), worldName); if (worldExists || worldFile.exists()) { player.sendMessage(plugin.getString("worlds_world_exists")); XSound.ENTITY_ITEM_BREAK.play(player); return true; } return false; } /** * Generate a {@link BuildWorld} with a predefined generator. * * @param player The player who is creating the world * @param worldName The name of the world * @param worldType The world type * @param privateWorld Is world going to be a private world? * @return {@code true} if the world was successfully created, {@code false otherwise} */ public boolean createWorld(Player player, String worldName, WorldType worldType, boolean privateWorld) { if (worldExists(player, worldName)) { return false; } BuildWorld buildWorld = new BuildWorld( plugin, worldName, player.getName(), player.getUniqueId(), worldType, System.currentTimeMillis(), privateWorld ); buildWorlds.add(buildWorld); player.sendMessage(plugin.getString("worlds_world_creation_started") .replace("%world%", worldName) .replace("%type%", buildWorld.getType().getName()) ); finishPreparationsAndGenerate(buildWorld); player.sendMessage(plugin.getString("worlds_creation_finished")); return true; } /** * Generate a {@link BuildWorld} with a custom generator. * * @param player The player who is creating the world * @param worldName The name of the world * @param privateWorld Is world going to be a private world? * @return {@code true} if the world was successfully created, {@code false otherwise} * @author Ein_Jojo */ public boolean createCustomWorld(Player player, String worldName, boolean privateWorld) { if (worldExists(player, worldName)) { return false; } new PlayerChatInput(plugin, player, "enter_generator_name", input -> { List<String> genArray; if (input.contains(":")) { genArray = Arrays.asList(input.split(":")); } else { genArray = Arrays.asList(input, input); } ChunkGenerator chunkGenerator = getChunkGenerator(genArray.get(0), genArray.get(1), worldName); if (chunkGenerator == null) { player.sendMessage(plugin.getString("worlds_import_unknown_generator")); XSound.ENTITY_ITEM_BREAK.play(player); return; } else { plugin.getLogger().info("Using custom world generator: " + input); } BuildWorld buildWorld = new BuildWorld(plugin, worldName, player.getName(), player.getUniqueId(), WorldType.CUSTOM, System.currentTimeMillis(), privateWorld, input); buildWorlds.add(buildWorld); player.sendMessage(plugin.getString("worlds_world_creation_started") .replace("%world%", buildWorld.getName()) .replace("%type%", buildWorld.getType().getName())); generateBukkitWorld(worldName, buildWorld.getType(), buildWorld.getDifficulty(), chunkGenerator); player.sendMessage(plugin.getString("worlds_creation_finished")); }); return true; } /** * Generate a {@link BuildWorld} with a template. * * @param player The player who is creating the world * @param worldName The name of the world * @param template The name of the template world * @param privateWorld Is world going to be a private world? * @return {@code true} if the world was successfully created, {@code false otherwise} */ private boolean createTemplateWorld(Player player, String worldName, String template, boolean privateWorld) { boolean worldExists = getBuildWorld(worldName) != null; File worldFile = new File(Bukkit.getWorldContainer(), worldName); if (worldExists || worldFile.exists()) { player.sendMessage(plugin.getString("worlds_world_exists")); return false; } File templateFile = new File(plugin.getDataFolder() + File.separator + "templates" + File.separator + template); if (!templateFile.exists()) { player.sendMessage(plugin.getString("worlds_template_does_not_exist")); return false; } BuildWorld buildWorld = new BuildWorld(plugin, worldName, player.getName(), player.getUniqueId(), WorldType.TEMPLATE, System.currentTimeMillis(), privateWorld); buildWorlds.add(buildWorld); player.sendMessage(plugin.getString("worlds_template_creation_started") .replace("%world%", buildWorld.getName()) .replace("%template%", template)); FileUtils.copy(templateFile, worldFile); Bukkit.createWorld(WorldCreator.name(worldName) .type(org.bukkit.WorldType.FLAT) .generateStructures(false)); player.sendMessage(plugin.getString("worlds_creation_finished")); return true; } /** * Certain {@link WorldType}s require modifications to the world after its generation. * * @param buildWorld The build world object */ private void finishPreparationsAndGenerate(BuildWorld buildWorld) { WorldType worldType = buildWorld.getType(); World bukkitWorld = generateBukkitWorld(buildWorld.getName(), worldType, buildWorld.getDifficulty(), buildWorld.getChunkGenerator()); switch (worldType) { case VOID: if (configValues.isVoidBlock()) { bukkitWorld.getBlockAt(0, 64, 0).setType(Material.GOLD_BLOCK); } bukkitWorld.setSpawnLocation(0, 65, 0); break; case FLAT: int y = XMaterial.supports(18) ? -60 : 4; bukkitWorld.setSpawnLocation(0, y, 0); break; default: break; } } /** * Generate the {@link World} linked to a {@link BuildWorld}. * * @param worldName The name of the world * @param worldType The world type * @param difficulty The world's difficulty * @param chunkGenerators Custom chunk generator to be used, if any * @return The world object */ public World generateBukkitWorld(String worldName, WorldType worldType, Difficulty difficulty, ChunkGenerator... chunkGenerators) { WorldCreator worldCreator = new WorldCreator(worldName); org.bukkit.WorldType bukkitWorldType; switch (worldType) { case VOID: worldCreator.generateStructures(false); bukkitWorldType = org.bukkit.WorldType.FLAT; if (XMaterial.supports(17)) { worldCreator.generator(new ModernVoidGenerator()); } else if (XMaterial.supports(13)) { worldCreator.generator(new DeprecatedVoidGenerator()); } else { worldCreator.generatorSettings("2;0;1"); } break; case FLAT: case PRIVATE: worldCreator.generateStructures(false); bukkitWorldType = org.bukkit.WorldType.FLAT; break; case NETHER: worldCreator.generateStructures(true); bukkitWorldType = org.bukkit.WorldType.NORMAL; worldCreator.environment(Environment.NETHER); break; case END: worldCreator.generateStructures(true); bukkitWorldType = org.bukkit.WorldType.NORMAL; worldCreator.environment(Environment.THE_END); break; case CUSTOM: if (chunkGenerators != null && chunkGenerators.length > 0) { worldCreator.generator(chunkGenerators[0]); } default: worldCreator.generateStructures(true); bukkitWorldType = org.bukkit.WorldType.NORMAL; worldCreator.environment(Environment.NORMAL); break; } worldCreator.type(bukkitWorldType); World bukkitWorld = Bukkit.createWorld(worldCreator); if (bukkitWorld != null) { bukkitWorld.setDifficulty(difficulty); bukkitWorld.setTime(configValues.getNoonTime()); bukkitWorld.getWorldBorder().setSize(configValues.getWorldBorderSize()); bukkitWorld.setKeepSpawnInMemory(configValues.isTeleportAfterCreation()); configValues.getDefaultGameRules().forEach(bukkitWorld::setGameRuleValue); } return bukkitWorld; } /** * Parse the {@link ChunkGenerator} for the generation of a {@link BuildWorld} with {@link WorldType#CUSTOM} * * @param generator The plugin's (generator) name * @param generatorId Unique ID, if any, that was specified to indicate which generator was requested * @param worldName Name of the world that the chunk generator should be applied to. */ public ChunkGenerator getChunkGenerator(String generator, String generatorId, String worldName) { if (generator == null) { return null; } Plugin plugin = this.plugin.getServer().getPluginManager().getPlugin(generator); if (plugin == null) { return null; } else { return plugin.getDefaultWorldGenerator(worldName, generatorId); } } /** * Import a {@link BuildWorld} from a world directory. * * @param player The player who is creating the world * @param worldName Name of the world that the chunk generator should be applied to. * @param generator The generator type used by the world * @param generatorName The name of the custom generator if generator type is {@link Generator#CUSTOM} */ public void importWorld(Player player, String worldName, Generator generator, String... generatorName) { for (String charString : worldName.split("")) { if (charString.matches("[^A-Za-z0-9/_-]")) { player.sendMessage(plugin.getString("worlds_import_invalid_character") .replace("%world%", worldName) .replace("%char%", charString) ); return; } } File file = new File(Bukkit.getWorldContainer(), worldName); if (!file.exists() || !file.isDirectory()) { player.sendMessage(plugin.getString("worlds_import_unknown_world")); return; } ChunkGenerator chunkGenerator = null; if (generator == Generator.CUSTOM) { List<String> genArray; if (generatorName[0].contains(":")) { genArray = Arrays.asList(generatorName[0].split(":")); } else { genArray = Arrays.asList(generatorName[0], generatorName[0]); } chunkGenerator = getChunkGenerator(genArray.get(0), genArray.get(1), worldName); if (chunkGenerator == null) { player.sendMessage(plugin.getString("worlds_import_unknown_generator")); return; } } player.sendMessage(plugin.getString("worlds_import_started").replace("%world%", worldName)); BuildWorld buildWorld = new BuildWorld( plugin, worldName, "-", null, WorldType.IMPORTED, FileUtils.getDirectoryCreation(file), false ); buildWorlds.add(buildWorld); generateBukkitWorld(worldName, generator.getWorldType(), buildWorld.getDifficulty(), chunkGenerator); player.sendMessage(plugin.getString("worlds_import_finished")); if (configValues.isTeleportAfterCreation()) { teleport(player, buildWorld); } } /** * Import all {@link BuildWorld} from a given list of world names. * * @param player The player who is creating the world * @param worldList The list of world to be imported */ public void importWorlds(Player player, String[] worldList) { int worlds = worldList.length; int delay = configValues.getImportDelay(); player.sendMessage(plugin.getString("worlds_importall_started").replace("%amount%", String.valueOf(worlds))); player.sendMessage(plugin.getString("worlds_importall_delay").replace("%delay%", String.valueOf(delay))); AtomicInteger worldsImported = new AtomicInteger(0); new BukkitRunnable() { @Override public void run() { int i = worldsImported.getAndIncrement(); String worldName = worldList[i]; for (String charString : worldName.split("")) { if (charString.matches("[^A-Za-z0-9/_-]")) { player.sendMessage(plugin.getString("worlds_importall_invalid_character").replace("%world%", worldName).replace("%char%", charString)); return; } } long creation = FileUtils.getDirectoryCreation(new File(Bukkit.getWorldContainer(), worldName)); BuildWorld buildWorld = new BuildWorld(plugin, worldName, "-", null, WorldType.IMPORTED, creation, false); buildWorlds.add(buildWorld); generateBukkitWorld(worldName, WorldType.VOID, buildWorld.getDifficulty()); player.sendMessage(plugin.getString("worlds_importall_world_imported").replace("%world%", worldName)); if (!(worldsImported.get() < worlds)) { this.cancel(); player.sendMessage(plugin.getString("worlds_importall_finished")); } } }.runTaskTimer(plugin, 0, 20L * delay); } /** * Delete an existing {@link BuildWorld}. * In comparison to {@link #unimportWorld(BuildWorld, boolean)}, deleting a world deletes the world's directory. * * @param player The player who issued the deletion * @param buildWorld The world to be deleted */ public void deleteWorld(Player player, BuildWorld buildWorld) { if (!buildWorlds.contains(buildWorld)) { player.sendMessage(plugin.getString("worlds_delete_unknown_world")); return; } String worldName = buildWorld.getName(); File deleteFolder = new File(Bukkit.getWorldContainer(), worldName); if (!deleteFolder.exists()) { player.sendMessage(plugin.getString("worlds_delete_unknown_directory")); return; } player.sendMessage(plugin.getString("worlds_delete_started").replace("%world%", worldName)); removePlayersFromWorld(worldName, plugin.getString("worlds_delete_players_world")); Bukkit.getScheduler().runTaskLater(plugin, () -> { unimportWorld(buildWorld, false); FileUtils.deleteDirectory(deleteFolder); player.sendMessage(plugin.getString("worlds_delete_finished")); }, 20L); } /** * Unimport an existing {@link BuildWorld}. * In comparison to {@link #deleteWorld(Player, BuildWorld)}, unimporting a world does not delete the world's directory. * * @param buildWorld The build world object * @param save Should the world be saved before unimporting */ public void unimportWorld(BuildWorld buildWorld, boolean save) { buildWorld.forceUnload(save); this.buildWorlds.remove(buildWorld); removePlayersFromWorld(buildWorld.getName(), plugin.getString("worlds_unimport_players_world")); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { this.worldConfig.getFile().set("worlds." + buildWorld.getName(), null); this.worldConfig.saveFile(); }); } /** * In order to properly unload/rename/delete a world, no players may be present in the {@link World}. * Removes all player's from the world to insure proper manipulation. * * @param worldName The name of the world * @param message The message sent to a player when they are removed from the world * @return A list of all players who were teleported out of the world */ private List<Player> removePlayersFromWorld(String worldName, String message) { List<Player> players = new ArrayList<>(); World bukkitWorld = Bukkit.getWorld(worldName); if (bukkitWorld == null) { return players; } SpawnManager spawnManager = plugin.getSpawnManager(); Location spawnLocation = Bukkit.getWorlds().get(0).getSpawnLocation().add(0.5, 0, 0.5); Bukkit.getOnlinePlayers().forEach(player -> { World playerWorld = player.getWorld(); if (!playerWorld.equals(bukkitWorld)) { return; } if (spawnManager.spawnExists()) { if (!spawnManager.getSpawnWorld().equals(playerWorld)) { spawnManager.teleport(player); } else { player.teleport(spawnLocation); spawnManager.remove(); } } else { player.teleport(spawnLocation); } player.sendMessage(message); players.add(player); }); return players; } /** * Change the name of a {@link BuildWorld} to a given name. * * @param player The player who issued the world rename * @param buildWorld The build world object * @param newName The name the world should be renamed to */ public void renameWorld(Player player, BuildWorld buildWorld, String newName) { String oldName = buildWorld.getName(); if (oldName.equalsIgnoreCase(newName)) { player.sendMessage(plugin.getString("worlds_rename_same_name")); return; } for (String charString : newName.split("")) { if (charString.matches("[^A-Za-z0-9/_-]")) { player.sendMessage(plugin.getString("worlds_world_creation_invalid_characters")); break; } } player.closeInventory(); String parsedNewName = newName.replaceAll("[^A-Za-z0-9/_-]", "").replace(" ", "_").trim(); if (parsedNewName.isEmpty()) { player.sendMessage(plugin.getString("worlds_world_creation_name_bank")); return; } if (Bukkit.getWorld(oldName) == null && !buildWorld.isLoaded()) { buildWorld.load(); } World oldWorld = Bukkit.getWorld(oldName); if (oldWorld == null) { player.sendMessage(plugin.getString("worlds_rename_unknown_world")); return; } List<Player> removedPlayers = removePlayersFromWorld(oldName, plugin.getString("worlds_rename_players_world")); Bukkit.getScheduler().runTaskLater(plugin, () -> { oldWorld.save(); Bukkit.getServer().unloadWorld(oldWorld, true); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { worldConfig.getFile().set("worlds." + parsedNewName, worldConfig.getFile().getConfigurationSection("worlds." + buildWorld.getName())); worldConfig.getFile().set("worlds." + oldName, null); }); File oldWorldFile = new File(Bukkit.getWorldContainer(), oldName); File newWorldFile = new File(Bukkit.getWorldContainer(), parsedNewName); FileUtils.copy(oldWorldFile, newWorldFile); FileUtils.deleteDirectory(oldWorldFile); buildWorld.setName(parsedNewName); World newWorld = generateBukkitWorld(buildWorld.getName(), buildWorld.getType(), buildWorld.getDifficulty(), buildWorld.getChunkGenerator()); Location spawnLocation = oldWorld.getSpawnLocation(); spawnLocation.setWorld(newWorld); removedPlayers.stream() .filter(Objects::nonNull) .forEach(pl -> pl.teleport(spawnLocation.add(0.5, 0, 0.5))); removedPlayers.clear(); SpawnManager spawnManager = plugin.getSpawnManager(); if (spawnManager.spawnExists() && Objects.equals(spawnManager.getSpawnWorld(), oldWorld)) { Location oldSpawn = spawnManager.getSpawn(); Location newSpawn = new Location(spawnLocation.getWorld(), oldSpawn.getX(), oldSpawn.getY(), oldSpawn.getZ(), oldSpawn.getYaw(), oldSpawn.getPitch()); spawnManager.set(newSpawn, newSpawn.getWorld().getName()); } player.sendMessage(plugin.getString("worlds_rename_set") .replace("%oldName%", oldName) .replace("%newName%", parsedNewName) ); }, 20L); } /** * Teleport a player to a {@link BuildWorld}. * * @param player The player to be teleported * @param buildWorld The build world object */ public void teleport(Player player, BuildWorld buildWorld) { boolean hadToLoad = false; if (configValues.isUnloadWorlds() && !buildWorld.isLoaded()) { buildWorld.load(player); hadToLoad = true; } World bukkitWorld = Bukkit.getServer().getWorld(buildWorld.getName()); if (bukkitWorld == null) { player.sendMessage(plugin.getString("worlds_tp_unknown_world")); return; } Location location = bukkitWorld.getSpawnLocation().add(0.5, 0, 0.5); if (buildWorld.getCustomSpawn() == null) { switch (buildWorld.getType()) { case NETHER: case END: Location blockLocation = null; for (int y = 0; y < bukkitWorld.getMaxHeight(); y++) { Block block = bukkitWorld.getBlockAt(location.getBlockX(), y, location.getBlockZ()); if (isSafeLocation(block.getLocation())) { blockLocation = block.getLocation(); break; } } if (blockLocation != null) { location = new Location(bukkitWorld, blockLocation.getBlockX() + 0.5, blockLocation.getBlockY() + 1, blockLocation.getBlockZ() + 0.5); } break; default: break; } } else { String[] spawnString = buildWorld.getCustomSpawn().split(";"); location = new Location(bukkitWorld, Double.parseDouble(spawnString[0]), Double.parseDouble(spawnString[1]), Double.parseDouble(spawnString[2]), Float.parseFloat(spawnString[3]), Float.parseFloat(spawnString[4])); } Location finalLocation = location; Bukkit.getScheduler().runTaskLater(plugin, () -> { player.teleport(finalLocation); Titles.clearTitle(player); XSound.ENTITY_ENDERMAN_TELEPORT.play(player); }, hadToLoad ? 20L : 0L); } /** * In order to correctly teleport a player to a {@link Location}, the block underneath the player's feet must be solid. * * @param location The location the player will be teleported to */ public boolean isSafeLocation(Location location) { Block feet = location.getBlock(); if (feet.getType() != Material.AIR && feet.getLocation().add(0, 1, 0).getBlock().getType() != Material.AIR) { return false; } Block head = feet.getRelative(BlockFace.UP); if (head.getType() != Material.AIR) { return false; } Block ground = feet.getRelative(BlockFace.DOWN); return ground.getType().isSolid(); } public void save() { buildWorlds.forEach(worldConfig::saveWorld); } public void load() { FileConfiguration configuration = worldConfig.getFile(); if (configuration == null) { return; } ConfigurationSection configurationSection = configuration.getConfigurationSection("worlds"); if (configurationSection == null) { return; } Set<String> worlds = configurationSection.getKeys(false); if (worlds.isEmpty()) { return; } worlds.forEach(this::loadWorld); worldConfig.loadWorlds(this); } public BuildWorld loadWorld(String worldName) { FileConfiguration configuration = worldConfig.getFile(); if (configuration == null) { return null; } String creator = configuration.isString("worlds." + worldName + ".creator") ? configuration.getString("worlds." + worldName + ".creator") : "-"; UUID creatorId = parseCreatorId(configuration, worldName, creator); WorldType worldType = configuration.isString("worlds." + worldName + ".type") ? WorldType.valueOf(configuration.getString("worlds." + worldName + ".type")) : WorldType.UNKNOWN; boolean privateWorld = configuration.isBoolean("worlds." + worldName + ".private") && configuration.getBoolean("worlds." + worldName + ".private"); XMaterial material = parseMaterial(configuration, worldName); WorldStatus worldStatus = WorldStatus.valueOf(configuration.getString("worlds." + worldName + ".status")); String project = configuration.getString("worlds." + worldName + ".project"); String permission = configuration.getString("worlds." + worldName + ".permission"); long date = configuration.isLong("worlds." + worldName + ".date") ? configuration.getLong("worlds." + worldName + ".date") : -1; boolean physics = configuration.getBoolean("worlds." + worldName + ".physics"); boolean explosions = !configuration.isBoolean("worlds." + worldName + ".explosions") || configuration.getBoolean("worlds." + worldName + ".explosions"); boolean mobAI = !configuration.isBoolean("worlds." + worldName + ".mobai") || configuration.getBoolean("worlds." + worldName + ".mobai"); String customSpawn = configuration.getString("worlds." + worldName + ".spawn"); boolean blockBreaking = !configuration.isBoolean("worlds." + worldName + ".block-breaking") || configuration.getBoolean("worlds." + worldName + ".block-breaking"); boolean blockPlacement = !configuration.isBoolean("worlds." + worldName + ".block-placement") || configuration.getBoolean("worlds." + worldName + ".block-placement"); boolean blockInteractions = !configuration.isBoolean("worlds." + worldName + ".block-interactions") || configuration.getBoolean("worlds." + worldName + ".block-interactions"); boolean buildersEnabled = configuration.isBoolean("worlds." + worldName + ".builders-enabled") && configuration.getBoolean("worlds." + worldName + ".builders-enabled"); Difficulty difficulty = Difficulty.valueOf(configuration.getString("worlds." + worldName + ".difficulty", "PEACEFUL").toUpperCase()); List<Builder> builders = parseBuilders(configuration, worldName); String chunkGeneratorString = configuration.getString("worlds." + worldName + ".chunk-generator"); ChunkGenerator chunkGenerator = parseChunkGenerator(configuration, worldName); BuildWorld buildWorld = new BuildWorld( plugin, worldName, creator, creatorId, worldType, privateWorld, material, worldStatus, project, permission, date, physics, explosions, mobAI, customSpawn, blockBreaking, blockPlacement, blockInteractions, buildersEnabled, difficulty, builders, chunkGenerator, chunkGeneratorString ); buildWorlds.add(buildWorld); return buildWorld; } private XMaterial parseMaterial(FileConfiguration configuration, String worldName) { String itemString = configuration.getString("worlds." + worldName + ".item"); if (itemString == null) { itemString = XMaterial.BEDROCK.name(); plugin.getLogger().warning("Could not find Material for \"" + worldName + "\"."); plugin.getLogger().warning("Material changed to BEDROCK."); } Optional<XMaterial> xMaterial = XMaterial.matchXMaterial(itemString); if (xMaterial.isPresent()) { return xMaterial.get(); } else { plugin.getLogger().warning("Unknown material found for \"" + worldName + "\" (" + itemString + ")."); plugin.getLogger().warning("Material changed to BEDROCK."); return XMaterial.BEDROCK; } } private UUID parseCreatorId(FileConfiguration configuration, String worldName, String creator) { String path = "worlds." + worldName + ".creator-id"; String id = configuration.isString(path) ? configuration.getString(path) : null; if (id == null || id.equalsIgnoreCase("null")) { if (!creator.equals("-")) { return UUIDFetcher.getUUID(creator); } else { return null; } } else { return UUID.fromString(id); } } private List<Builder> parseBuilders(FileConfiguration configuration, String worldName) { List<Builder> builders = new ArrayList<>(); if (configuration.isString("worlds." + worldName + ".builders")) { String buildersString = configuration.getString("worlds." + worldName + ".builders"); if (buildersString != null && !buildersString.isEmpty()) { String[] splitBuilders = buildersString.split(";"); for (String builder : splitBuilders) { String[] information = builder.split(","); builders.add(new Builder(UUID.fromString(information[0]), information[1])); } } } return builders; } /** * @author Ein_Jojo */ private ChunkGenerator parseChunkGenerator(FileConfiguration configuration, String worldName) { ChunkGenerator chunkGenerator = null; if (configuration.isString("worlds." + worldName + ".chunk-generator")) { String generator = configuration.getString("worlds." + worldName + ".chunk-generator"); if (generator != null && !generator.isEmpty()) { List<String> genArray; if (generator.contains(":")) { genArray = Arrays.asList(generator.split(":")); } else { genArray = Arrays.asList(generator, generator); } chunkGenerator = getChunkGenerator(genArray.get(0), genArray.get(1), worldName); } } return chunkGenerator; } }
41.951093
225
0.61275
537614bd1d76b511c8adc5b5f123f67775c41e3a
1,679
/* Copyright © 2019 Pasqual K. | All rights reserved */ package systems.reformcloud.commands.ingame.command; import systems.reformcloud.commands.ingame.sender.IngameCommandSender; import java.io.Serializable; /** * @author _Klaro | Pasqual K. / created on 19.03.2019 */ public abstract class IngameCommand implements Serializable { /** * The name of the ingame command */ private String name; /** * The permission which is needed to use the command */ private String permission; /** * The aliases of the command */ private String[] aliases; /** * Creates a new ingame command * * @param name The name of the command */ public IngameCommand(String name) { this.name = name; this.aliases = new String[0]; } /** * Creates a new ingame command * * @param name The name of the command * @param permission The permission of the command * @param aliases The aliases of the command */ public IngameCommand(String name, String permission, String[] aliases) { this.name = name; this.permission = permission; this.aliases = aliases; } /** * Handles the command * * @param commandSender The command sender who send the command * @param args The arguments provided with the command */ public abstract void handle(IngameCommandSender commandSender, String[] args); public String getName() { return this.name; } public String getPermission() { return this.permission; } public String[] getAliases() { return this.aliases; } }
22.386667
82
0.628946
9aa8a5e5d4ff9b27133f61848e5d011a347f06e8
8,359
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.smartnsoft.logentries; import java.io.IOException; import android.content.Context; import com.smartnsoft.droid4me.log.AndroidLogger; /** * An implementation of logger which is able to log to <a href="http://logentries.com">Logentries</a>. * * @author Ludovic Roland * @since 2014.03.14 */ public class LogentriesLogger extends AndroidLogger { private static String logPrefix; /** * Enables to set up a prefix for all Logentries logs. By default, no log prefix is set up. The prefix starts to be working as soon as this method * returns. * * @param prefix if {@code null}, no prefix will be used ; otherwise, each log will be prefixed with this provided string */ public static void setLogPrefix(String prefix) { LogentriesLogger.logPrefix = prefix; } private final com.logentries.logger.AndroidLogger log; /** * Exceptions are generate where mutually exclusive settings collide - these are: "useHttpPost" and "useSsl" cannot be both true - HTTP is not available * with TLS/SSL "useHttpPost" and "isUsingDataHub" cannot be both true - use one or the other only * * @param theClass * @param context for example, if in an Activity class, use getApplicationContext(), or if in an Application class, use getBaseContext(). * @param useHttpPost if set true, use HTTP (cannot be used with TLS/SSL or the Datahub) * @param useSsl if set true, the data sent using the default TCP Token, will be done over an SSL Socket. * The library itself does not validate or manage TLS/SSL certificates - it will use the default TrustManager and KeyManager used by the application or host. * @param isUsingDataHub if set true, library will forward log events to a Datahub (requires Datahub IP Address and Port) * @param dataHubAddr is a String of the IP Address of your DataHub machine. * @param dataHubPort is an int of the port number of your incoming connection on your DataHub machine. * The default is port 10000, but this can be changed to any port by altering the /etc/leproxy/leproxyLocal.config file on your DataHub * machine and restarting the leproxy daemon using "sudo service leproxy restart". * @param token the Token UUID, this is unique to the log to which the log events are sent This can be copied from the log in the the Logentries Account * @param logHostName if set true will return host name in log event * @throws IOException */ public LogentriesLogger(Class<?> theClass, Context context, boolean useHttpPost, boolean useSsl, boolean isUsingDataHub, String dataHubAddr, int dataHubPort, String token, boolean logHostName) throws IOException { this(theClass.getSimpleName(), context, useHttpPost, useSsl, isUsingDataHub, dataHubAddr, dataHubPort, token, logHostName); } /** * Exceptions are generate where mutually exclusive settings collide - these are: "useHttpPost" and "useSsl" cannot be both true - HTTP is not available * with TLS/SSL "useHttpPost" and "isUsingDataHub" cannot be both true - use one or the other only * * @param category * @param context for example, if in an Activity class, use getApplicationContext(), or if in an Application class, use getBaseContext(). * @param useHttpPost if set true, use HTTP (cannot be used with TLS/SSL or the Datahub) * @param useSsl if set true, the data sent using the default TCP Token, will be done over an SSL Socket. * The library itself does not validate or manage TLS/SSL certificates - it will use the default TrustManager and KeyManager used by the application or host. * @param isUsingDataHub if set true, library will forward log events to a Datahub (requires Datahub IP Address and Port) * @param dataHubAddr is a String of the IP Address of your DataHub machine. * @param dataHubPort is an int of the port number of your incoming connection on your DataHub machine. * The default is port 10000, but this can be changed to any port by altering the /etc/leproxy/leproxyLocal.config file on your DataHub * machine and restarting the leproxy daemon using "sudo service leproxy restart". * @param token the Token UUID, this is unique to the log to which the log events are sent This can be copied from the log in the the Logentries Account * @param logHostName if set true will return host name in log event * @throws IOException */ public LogentriesLogger(String category, Context context, boolean useHttpPost, boolean useSsl, boolean isUsingDataHub, String dataHubAddr, int dataHubPort, String token, boolean logHostName) throws IOException { super(category); log = com.logentries.logger.AndroidLogger.createInstance(context, useHttpPost, useSsl, isUsingDataHub, dataHubAddr, dataHubPort, token, logHostName); } @Override public void debug(String message) { super.debug(message); log.log(computeMessage(message, null)); } @Override public void error(String message, Throwable throwable) { super.error(message, throwable); log.log(computeMessage(message, throwable)); } @Override public void error(String message) { super.error(message); log.log(computeMessage(message, null)); } @Override public void error(StringBuffer message, Throwable throwable) { super.error(message, throwable); log.log(computeMessage(message, throwable)); } @Override public void fatal(String message, Throwable throwable) { super.fatal(message, throwable); log.log(computeMessage(message, throwable)); } @Override public void fatal(String message) { super.fatal(message); log.log(computeMessage(message, null)); } @Override public void info(String message) { super.info(message); log.log(computeMessage(message, null)); } @Override public void warn(String message, Throwable throwable) { super.warn(message, throwable); log.log(computeMessage(message, throwable)); } @Override public void warn(String message) { super.warn(message); log.log(computeMessage(message, null)); } @Override public void warn(StringBuffer message, Throwable throwable) { super.warn(message, throwable); log.log(computeMessage(message, throwable)); } @Override public boolean isDebugEnabled() { return true; } @Override public boolean isInfoEnabled() { return true; } @Override public boolean isWarnEnabled() { return true; } @Override public boolean isErrorEnabled() { return true; } @Override public boolean isFatalEnabled() { return true; } protected String computeMessage(String message, Throwable throwable) { return (LogentriesLogger.logPrefix != null ? LogentriesLogger.logPrefix : "") + message + (throwable == null ? "" : (": reason is '" + throwable.getMessage() + "'")); } protected final String computeMessage(StringBuffer message, Throwable throwable) { return computeMessage(message.toString(), throwable); } }
37.995455
181
0.714081
6e35f2d0545e5603f09ce8e8a21ab05205917032
1,994
/* * Copyright (c) 2014 ProSyst Software GmbH. All Rights Reserved. * * This CODE is owned by ProSyst Software GmbH, * and is being distributed to OSGi PARTICIPANTS as MATERIALS * under the terms of section 1 of the OSGi Alliance Inc. Intellectual Property Rights Policy, * Amended and Restated as of May 23, 2011. */ package org.osgi.test.cases.dal.functions; import org.osgi.service.dal.DeviceException; import org.osgi.service.dal.Function; import org.osgi.service.dal.functions.MultiLevelSensor; import org.osgi.service.dal.functions.data.LevelData; import org.osgi.test.cases.dal.functions.step.FunctionsTestSteps; /** * Validates the {@code MultiLevelSensor} functions. */ public final class MultiLevelSensorTest extends AbstractFunctionTest { /** * Checks {@link MultiLevelSensor#getData()} getter functionality. * * @throws DeviceException If operation error is available. */ public void testGetData() throws DeviceException { super.testStepProxy.execute( FunctionsTestSteps.STEP_ID_AVAILABLE_MLS, FunctionsTestSteps.STEP_MESSAGE_AVAILABLE_MLS); Function[] multiLevelSensors = super.getFunctions(MultiLevelSensor.class.getName()); for (int i = 0; i < multiLevelSensors.length; i++) { MultiLevelSensor currentSensor = (MultiLevelSensor) multiLevelSensors[i]; LevelData currentData = currentSensor.getData(); assertNotNull("The level data cannot be null!", currentData); super.assertEquals( currentSensor.getPropertyMetadata(MultiLevelSensor.PROPERTY_DATA), currentData.getLevel(), currentData); } } /** * Checks {@code MultiLevelSensor} function events. */ public void testPropertyEvent() { super.testStepProxy.execute( FunctionsTestSteps.STEP_ID_AVAILABLE_MLS, FunctionsTestSteps.STEP_MESSAGE_AVAILABLE_MLS); super.checkPropertyEvent( MultiLevelSensor.class.getName(), MultiLevelSensor.PROPERTY_DATA, FunctionsTestSteps.STEP_ID_EVENT_MLS, FunctionsTestSteps.STEP_MESSAGE_EVENT_MLS); } }
34.982456
94
0.772818
03796ab207883a99e59ce7264631664de8cd8c60
1,903
package net.runelite.client.plugins.custommenuswapper; import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigItem; @ConfigGroup("custommenuentryswapper") public interface CustomMenuSwapperConfig extends Config { @ConfigItem( position = 1, keyName = "swapTar", name = "Swap tar", description = "Swap tar option wield -> use and salamander wield -> release for Hunter." ) default boolean swapTar() { return false; } @ConfigItem( position = 2, keyName = "woodDrop", name = "Drop wood", description = "Left click dropping logs when woodcutting." ) default boolean dropLogs() { return false; } @ConfigItem( position = 3, keyName = "fishDrop", name = "Drop fish", description = "Left click dropping fish when fishing." ) default boolean dropFish() { return false; } @ConfigItem( position = 4, keyName = "disableHerbClean", name = "Disable clean herb", description = "Disable accidental left click herb cleaning." ) default boolean disableHerbClean() { return true; } @ConfigItem( position = 5, keyName = "disableFarmFruitEat", name = "Disable eating farming payment", description = "Disable accidental eating of Papaya fruit for Farming." ) default boolean disableFruitEat() { return true; } @ConfigItem( position = 6, keyName = "dropFarmingShit", name = "Drop empty farming shit", description = "Drop buckets and empty pots for Farming." ) default boolean dropFarmingShit() { return true; } }
27.57971
100
0.581713
42e2249712ee8b064de1496ab11fd650c5d23016
2,846
package mage.cards.t; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ReplacementEffectImpl; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.Game; import mage.game.events.GameEvent; import mage.players.Player; import mage.watchers.common.CardsDrawnDuringDrawStepWatcher; import java.util.UUID; /** * @author TheElk801 */ public final class TeferisAgelessInsight extends CardImpl { public TeferisAgelessInsight(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}{U}"); this.addSuperType(SuperType.LEGENDARY); // If you would draw a card except the first one you draw in each of your draw steps, draw two cards instead. this.addAbility(new SimpleStaticAbility(new TeferisAgelessInsightEffect()), new CardsDrawnDuringDrawStepWatcher()); } private TeferisAgelessInsight(final TeferisAgelessInsight card) { super(card); } @Override public TeferisAgelessInsight copy() { return new TeferisAgelessInsight(this); } } class TeferisAgelessInsightEffect extends ReplacementEffectImpl { TeferisAgelessInsightEffect() { super(Duration.WhileOnBattlefield, Outcome.Neutral); staticText = "If you would draw a card except the first one you draw in each of your draw steps, draw two cards instead"; } private TeferisAgelessInsightEffect(final TeferisAgelessInsightEffect effect) { super(effect); } @Override public TeferisAgelessInsightEffect copy() { return new TeferisAgelessInsightEffect(this); } @Override public boolean apply(Game game, Ability source) { return true; } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { controller.drawCards(2, event.getSourceId(), game, event.getAppliedEffects()); } return true; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DRAW_CARD; } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (!event.getPlayerId().equals(source.getControllerId())) { return false; } if (!game.isActivePlayer(event.getPlayerId()) || game.getPhase().getStep().getType() != PhaseStep.DRAW) { return true; } CardsDrawnDuringDrawStepWatcher watcher = game.getState().getWatcher(CardsDrawnDuringDrawStepWatcher.class); return watcher != null && watcher.getAmountCardsDrawn(event.getPlayerId()) > 0; } }
32.712644
129
0.701335
2887e23c217df9547dd985d0f093cbccd1dec666
710
package io.miret.etienne.gradle.sass; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.Property; import org.gradle.workers.WorkParameters; public interface CompileSassWorkParameters extends WorkParameters { RegularFileProperty getExecutable(); ConfigurableFileCollection getLoadPaths(); RegularFileProperty getOutputDir(); RegularFileProperty getSourceDir(); Property<CompileSass.Style> getStyle(); Property<CompileSass.SourceMap> getSourceMap(); Property<CompileSass.SourceMapUrls> getSourceMapUrls(); Property<Boolean> getWatch(); Property<Boolean> getCharset(); Property<Boolean> getErrorCss(); }
30.869565
67
0.812676
5a6aef7a03fc00eb268496d8b810bae0d9fd126e
5,504
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.refactoring.java.plugins; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import java.util.logging.Logger; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.modules.refactoring.java.RefactoringUtils; import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor; import org.netbeans.modules.refactoring.java.spi.ToPhaseException; import org.openide.util.Exceptions; /** * * @author Jan Becicka */ public class CopyTransformer extends RefactoringVisitor { private String newName; private boolean insertImport; private String oldPackage; private String oldName; private String newPackage; public CopyTransformer(WorkingCopy workingCopy, String oldName, String newName, boolean insertImport, String oldPackage) { try { setWorkingCopy(workingCopy); this.newName = newName; this.insertImport = insertImport; this.oldPackage = oldPackage; this.oldName = oldName; this.newPackage = RefactoringUtils.getPackageName(workingCopy.getFileObject().getParent()); } catch (ToPhaseException ex) { Exceptions.printStackTrace(ex); } } @Override public Tree visitCompilationUnit(CompilationUnitTree tree, Element p) { if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) { CompilationUnitTree cut = tree; if (cut.getPackageName() != null && !"".equals(newPackage) && !newPackage.equals(cut.getPackageName().toString())) { // NOI18N rewrite(cut.getPackageName(), make.Identifier(newPackage)); } else { // in order to handle default package, we have to rewrite whole // compilation unit: cut = make.CompilationUnit( cut.getPackageAnnotations(), "".equals(newPackage) ? null : make.Identifier(newPackage), // NOI18N cut.getImports(), cut.getTypeDecls(), cut.getSourceFile() ); rewrite(tree, cut); } if (insertImport && !"package-info".equals(newName)) { //NOI18N Tree tree2 = make.insertCompUnitImport(cut, 0, make.Import(make.Identifier(oldPackage + ".*"), false)); // NOI18N rewrite(tree, tree2); } } return super.visitCompilationUnit(tree, p); } @Override public Tree visitClass(ClassTree tree, Element p) { if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) { TypeElement currentClass = (TypeElement) workingCopy.getTrees().getElement(getCurrentPath()); if (currentClass == null) { Logger.getLogger("org.netbeans.modules.refactoring.java").severe("Cannot resolve tree " + tree + "\n file: " + workingCopy.getFileObject().getPath()); // NOI18N } else { if (!currentClass.getNestingKind().isNested() && ( tree.getSimpleName().toString().equals(oldName) || tree.getSimpleName().toString().equals(oldName + "_1") ) ) { Tree nju = make.setLabel(tree, newName); rewrite(tree, nju); } } } return super.visitClass(tree, p); } @Override public Tree visitIdentifier(IdentifierTree node, Element p) { renameUsageIfMatch(getCurrentPath(), node,p); return super.visitIdentifier(node, p); } @Override public Tree visitMemberSelect(MemberSelectTree node, Element p) { renameUsageIfMatch(getCurrentPath(), node,p); return super.visitMemberSelect(node, p); } private void renameUsageIfMatch(TreePath path, Tree tree, Element elementToFind) { if (JavaPluginUtils.isSyntheticPath(workingCopy, path)) { return; } Element el = workingCopy.getTrees().getElement(path); if (el==null) { return; } if ((el.getKind().isClass() || el.getKind().isInterface()) && (((TypeElement) el).getQualifiedName().toString().equals(newPackage+"."+oldName) || ((TypeElement) el).getQualifiedName().toString().equals(oldPackage+"."+oldName))){ // NOI18N Tree nju = make.setLabel(tree, newName); rewrite(tree, nju); } } }
41.383459
176
0.619004
99cc51672c4e4b7870c18e68535703226854fff3
1,081
package com.espressif.iot.base.net.rest2; import java.net.URI; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; class EspHttpRequest extends HttpEntityEnclosingRequestBase { final static String METHOD_POST = "POST"; final static String METHOD_GET = "GET"; final static String ESP_INSTANTLY = "ESP_INSTANTLY"; // dummy runnable do nothing, it is used by post instantly final static Runnable ESP_DUMMY_RUNNABLE = new Runnable() { @Override public void run() { } }; private final String METHOD_NAME; EspHttpRequest(String method) { super(); METHOD_NAME = method; } EspHttpRequest(final URI uri, String method) { super(); setURI(uri); METHOD_NAME = method; } EspHttpRequest(final String uri, String method) { super(); setURI(URI.create(uri)); METHOD_NAME = method; } @Override public String getMethod() { return METHOD_NAME; } }
20.788462
69
0.608696
3387952f6af96d83f83658c3eccbdab40b20bc08
556
package slieb.blendercss.configuration; import com.google.inject.AbstractModule; public class InterfaceModule<A> extends AbstractModule { private final Class<A> interfaceClass; private final Class<? extends A> implementationClass; public InterfaceModule(Class<A> interfaceClass, Class<? extends A> implementationClass) { this.interfaceClass = interfaceClass; this.implementationClass = implementationClass; } @Override protected void configure() { bind(interfaceClass).to(implementationClass); } }
26.47619
93
0.73741
7bf11d667ab4c8c82d23b45ba3b93655ea021a88
614
/* * 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 modelo.livroautor; /** * * @author creuma */ public class LivroAutor { private int fkAutor; private int fkLivro; public int getFkAutor() { return fkAutor; } public void setFkAutor(int fkAutor) { this.fkAutor = fkAutor; } public int getFkLivro() { return fkLivro; } public void setFkLivro(int fkLivro) { this.fkLivro = fkLivro; } }
18.058824
79
0.630293
a44b4f13215a543cc829768a18f163f2892226c3
18,244
package com.sdsmdg.harjot.vectormaster; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import com.sdsmdg.harjot.vectormaster.models.ClipPathModel; import com.sdsmdg.harjot.vectormaster.models.GroupModel; import com.sdsmdg.harjot.vectormaster.models.PathModel; import com.sdsmdg.harjot.vectormaster.models.VectorModel; import com.sdsmdg.harjot.vectormaster.utilities.Utils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.Stack; public class VectorMasterDrawable extends Drawable { private VectorModel vectorModel; private Context context; private Resources resources; private int resID = -1; private boolean useLegacyParser = true; private float offsetX = 0.0f, offsetY = 0.0f; private float scaleX = 1.0f, scaleY = 1.0f; private XmlPullParser xpp; String TAG = "VECTOR_MASTER"; private Matrix scaleMatrix; private int width = -1, height = -1; private float scaleRatio, strokeRatio; private int left = 0, top = 0; private int tempSaveCount; public VectorMasterDrawable(Context context, int resID) { this.context = context; this.resID = resID; init(); } public VectorMasterDrawable(Context context, int resID, float offsetX, float offsetY) { this.context = context; this.resID = resID; this.offsetX = offsetX; this.offsetY = offsetY; init(); } public VectorMasterDrawable(Context context, int resID, float offsetX, float offsetY, float scaleX, float scaleY) { this.context = context; this.resID = resID; this.offsetX = offsetX; this.offsetY = offsetY; this.scaleX = scaleX; this.scaleY = scaleY; init(); } private void init() { resources = context.getResources(); buildVectorModel(); } private void buildVectorModel() { if (resID == -1) { vectorModel = null; return; } xpp = resources.getXml(resID); int tempPosition; PathModel pathModel = new PathModel(); vectorModel = new VectorModel(); GroupModel groupModel = new GroupModel(); ClipPathModel clipPathModel = new ClipPathModel(); Stack<GroupModel> groupModelStack = new Stack<>(); try { int event = xpp.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name = xpp.getName(); switch (event) { case XmlPullParser.START_TAG: if (name.equals("vector")) { tempPosition = getAttrPosition(xpp, "viewportWidth"); vectorModel.setViewportWidth((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_VIEWPORT_WIDTH); tempPosition = getAttrPosition(xpp, "viewportHeight"); vectorModel.setViewportHeight((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_VIEWPORT_HEIGHT); tempPosition = getAttrPosition(xpp, "alpha"); vectorModel.setAlpha((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_ALPHA); tempPosition = getAttrPosition(xpp, "name"); vectorModel.setName((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(xpp, "width"); vectorModel.setWidth((tempPosition != -1) ? Utils.getFloatFromDimensionString(xpp.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_WIDTH); tempPosition = getAttrPosition(xpp, "height"); vectorModel.setHeight((tempPosition != -1) ? Utils.getFloatFromDimensionString(xpp.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_HEIGHT); } else if (name.equals("path")) { pathModel = new PathModel(); tempPosition = getAttrPosition(xpp, "name"); pathModel.setName((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(xpp, "fillAlpha"); pathModel.setFillAlpha((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_FILL_ALPHA); tempPosition = getAttrPosition(xpp, "fillColor"); pathModel.setFillColor((tempPosition != -1) ? Utils.getColorFromString(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_FILL_COLOR); tempPosition = getAttrPosition(xpp, "fillType"); pathModel.setFillType((tempPosition != -1) ? Utils.getFillTypeFromString(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_FILL_TYPE); tempPosition = getAttrPosition(xpp, "pathData"); pathModel.setPathData((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(xpp, "strokeAlpha"); pathModel.setStrokeAlpha((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_ALPHA); tempPosition = getAttrPosition(xpp, "strokeColor"); pathModel.setStrokeColor((tempPosition != -1) ? Utils.getColorFromString(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_COLOR); tempPosition = getAttrPosition(xpp, "strokeLineCap"); pathModel.setStrokeLineCap((tempPosition != -1) ? Utils.getLineCapFromString(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_LINE_CAP); tempPosition = getAttrPosition(xpp, "strokeLineJoin"); pathModel.setStrokeLineJoin((tempPosition != -1) ? Utils.getLineJoinFromString(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_LINE_JOIN); tempPosition = getAttrPosition(xpp, "strokeMiterLimit"); pathModel.setStrokeMiterLimit((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_MITER_LIMIT); tempPosition = getAttrPosition(xpp, "strokeWidth"); pathModel.setStrokeWidth((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_WIDTH); tempPosition = getAttrPosition(xpp, "trimPathEnd"); pathModel.setTrimPathEnd((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_END); tempPosition = getAttrPosition(xpp, "trimPathOffset"); pathModel.setTrimPathOffset((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_OFFSET); tempPosition = getAttrPosition(xpp, "trimPathStart"); pathModel.setTrimPathStart((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_START); pathModel.buildPath(useLegacyParser); } else if (name.equals("group")) { groupModel = new GroupModel(); tempPosition = getAttrPosition(xpp, "name"); groupModel.setName((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(xpp, "pivotX"); groupModel.setPivotX((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_PIVOT_X); tempPosition = getAttrPosition(xpp, "pivotY"); groupModel.setPivotY((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_PIVOT_Y); tempPosition = getAttrPosition(xpp, "rotation"); groupModel.setRotation((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_ROTATION); tempPosition = getAttrPosition(xpp, "scaleX"); groupModel.setScaleX((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_SCALE_X); tempPosition = getAttrPosition(xpp, "scaleY"); groupModel.setScaleY((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_SCALE_Y); tempPosition = getAttrPosition(xpp, "translateX"); groupModel.setTranslateX((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_TRANSLATE_X); tempPosition = getAttrPosition(xpp, "translateY"); groupModel.setTranslateY((tempPosition != -1) ? Float.parseFloat(xpp.getAttributeValue(tempPosition)) : DefaultValues.GROUP_TRANSLATE_Y); groupModelStack.push(groupModel); } else if (name.equals("clip-path")) { clipPathModel = new ClipPathModel(); tempPosition = getAttrPosition(xpp, "name"); clipPathModel.setName((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(xpp, "pathData"); clipPathModel.setPathData((tempPosition != -1) ? xpp.getAttributeValue(tempPosition) : null); clipPathModel.buildPath(useLegacyParser); } break; case XmlPullParser.END_TAG: if (name.equals("path")) { if (groupModelStack.size() == 0) { vectorModel.addPathModel(pathModel); } else { groupModelStack.peek().addPathModel(pathModel); } vectorModel.getFullpath().addPath(pathModel.getPath()); } else if (name.equals("clip-path")) { if (groupModelStack.size() == 0) { vectorModel.addClipPathModel(clipPathModel); } else { groupModelStack.peek().addClipPathModel(clipPathModel); } } else if (name.equals("group")) { GroupModel topGroupModel = groupModelStack.pop(); if (groupModelStack.size() == 0) { topGroupModel.setParent(null); vectorModel.addGroupModel(topGroupModel); } else { topGroupModel.setParent(groupModelStack.peek()); groupModelStack.peek().addGroupModel(topGroupModel); } } else if (name.equals("vector")) { vectorModel.buildTransformMatrices(); } break; } event = xpp.next(); } } catch (XmlPullParserException | IOException e) { e.printStackTrace(); } } private int getAttrPosition(XmlPullParser xpp, String attrName) { for (int i = 0; i < xpp.getAttributeCount(); i++) { if (xpp.getAttributeName(i).equals(attrName)) { return i; } } return -1; } public int getResID() { return resID; } public void setResID(int resID) { this.resID = resID; buildVectorModel(); scaleMatrix = null; } public boolean isUseLegacyParser() { return useLegacyParser; } public void setUseLegacyParser(boolean useLegacyParser) { this.useLegacyParser = useLegacyParser; buildVectorModel(); scaleMatrix = null; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); if (bounds.width() != 0 && bounds.height() != 0) { left = bounds.left; top = bounds.top; width = bounds.width(); height = bounds.height(); buildScaleMatrix(); scaleAllPaths(); scaleAllStrokes(); } } @Override public void draw(Canvas canvas) { if (vectorModel == null) { return; } if (scaleMatrix == null) { int temp1 = Utils.dpToPx((int) vectorModel.getWidth()); int temp2 = Utils.dpToPx((int) vectorModel.getHeight()); setBounds(0, 0, temp1, temp2); } setAlpha(Utils.getAlphaFromFloat(vectorModel.getAlpha())); if (left != 0 || top != 0) { tempSaveCount = canvas.save(); canvas.translate(left, top); vectorModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); canvas.restoreToCount(tempSaveCount); } else { vectorModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); } } @Override public void setAlpha(int i) { vectorModel.setAlpha(Utils.getAlphaFromInt(i)); } @Override public void setColorFilter(ColorFilter colorFilter) { } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public int getIntrinsicWidth() { return Utils.dpToPx((int) vectorModel.getWidth()); } @Override public int getIntrinsicHeight() { return Utils.dpToPx((int) vectorModel.getHeight()); } private void buildScaleMatrix() { scaleMatrix = new Matrix(); scaleMatrix.postTranslate(width / 2 - vectorModel.getViewportWidth() / 2, height / 2 - vectorModel.getViewportHeight() / 2); float widthRatio = width / vectorModel.getViewportWidth(); float heightRatio = height / vectorModel.getViewportHeight(); float ratio = Math.min(widthRatio, heightRatio); scaleRatio = ratio; scaleMatrix.postScale(ratio, ratio, width / 2, height / 2); } private void scaleAllPaths() { vectorModel.scaleAllPaths(scaleMatrix); } private void scaleAllStrokes() { strokeRatio = Math.min(width / vectorModel.getWidth(), height / vectorModel.getHeight()); vectorModel.scaleAllStrokeWidth(strokeRatio); } public Path getFullPath() { if (vectorModel != null) { return vectorModel.getFullpath(); } return null; } public GroupModel getGroupModelByName(String name) { GroupModel gModel; for (GroupModel groupModel : vectorModel.getGroupModels()) { if (groupModel.getName().equals(name)) { return groupModel; } else { gModel = groupModel.getGroupModelByName(name); if (gModel != null) return gModel; } } return null; } public PathModel getPathModelByName(String name) { PathModel pModel = null; for (PathModel pathModel : vectorModel.getPathModels()) { if (pathModel.getName().equals(name)) { return pathModel; } } for (GroupModel groupModel : vectorModel.getGroupModels()) { pModel = groupModel.getPathModelByName(name); if (pModel != null && pModel.getName().equals(name)) return pModel; } return pModel; } public ClipPathModel getClipPathModelByName(String name) { ClipPathModel cModel = null; for (ClipPathModel clipPathModel : vectorModel.getClipPathModels()) { if (clipPathModel.getName().equals(name)) { return clipPathModel; } } for (GroupModel groupModel : vectorModel.getGroupModels()) { cModel = groupModel.getClipPathModelByName(name); if (cModel != null && cModel.getName().equals(name)) return cModel; } return cModel; } public void update() { invalidateSelf(); } public float getScaleRatio() { return scaleRatio; } public float getStrokeRatio() { return strokeRatio; } public Matrix getScaleMatrix() { return scaleMatrix; } public float getOffsetX() { return offsetX; } public void setOffsetX(float offsetX) { this.offsetX = offsetX; invalidateSelf(); } public float getOffsetY() { return offsetY; } public void setOffsetY(float offsetY) { this.offsetY = offsetY; invalidateSelf(); } public float getScaleX() { return scaleX; } public void setScaleX(float scaleX) { this.scaleX = scaleX; invalidateSelf(); } public float getScaleY() { return scaleY; } public void setScaleY(float scaleY) { this.scaleY = scaleY; invalidateSelf(); } }
38.982906
183
0.57893
36ebf9f7a9ab35a21da5763acfb53079f1acf7bd
6,482
package com.github.funnyzak.onekey.biz.service.impl; import com.github.funnyzak.onekey.biz.service.GeneralService; import com.github.funnyzak.onekey.biz.service.TypeRelationService; import org.nutz.dao.Cnd; import org.nutz.dao.Condition; import org.nutz.dao.Sqls; import org.nutz.dao.pager.Pager; import org.nutz.dao.sql.Sql; import org.nutz.lang.util.NutMap; import org.nutz.plugin.spring.boot.service.entity.PageredData; import com.github.funnyzak.onekey.bean.enums.TypeRelationEnums; import com.github.funnyzak.onekey.bean.relation.TypeRelation; import com.github.funnyzak.onekey.common.utils.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; /** * @author Potato (silenceace@gmail.com) * @date 2020/2/3 4:22 下午 * @description CollectionRelationService */ @Service public class TypeRelationServiceImpl extends GeneralService<TypeRelation> implements TypeRelationService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired public TypeRelationServiceImpl() { } @Override public <T> PageredData<T> pagerByRelation(String listSqlName, String countSqlName, Class<T> tClass, TypeRelationEnums relationType, Cnd condition, Long typeId, Integer pageNumber, Integer pageSize) { List<T> list = listByCondition(listSqlName, tClass, relationType, condition, typeId, (pageNumber - 1) * pageSize, pageSize); Integer recordCount = countByRelation(countSqlName, condition, tClass, relationType, typeId); PageredData<T> pager = new PageredData<>(); Pager page = new Pager(); page.setRecordCount(recordCount); page.setPageSize(pageSize); page.setPageNumber(pageNumber); pager.setPager(page); pager.setDataList(list); return pager; } @Override public <T> List<T> listByCondition(String sqlName, Class<T> tClass, TypeRelationEnums relationType, Cnd condition, Long typeId, Integer start, Integer count) { Sql sql = dao().sqls().create(sqlName) .setParam("relation_type", relationType) .setParam("relation_type_id", typeId) .setParam("start", start) .setParam("count", count) .setCondition(condition) .setEntity(dao().getEntity(tClass)) .setCallback(Sqls.callback.entities()); dao().execute(sql); return sql.getList(tClass); } @Override public <T> Integer countByRelation(String sqlName, Condition cnd, Class<T> tClass, TypeRelationEnums relationType, Long relationTypeId) { Sql sql = dao().sqls().create(sqlName) .setParam("relation_type", relationType) .setParam("relation_type_id", relationTypeId) .setCondition(cnd) .setEntity(dao().getEntity(tClass)) .setCallback(Sqls.callback.integer()); dao().execute(sql); return sql.getInt(); } @Override public Integer countByRelation(TypeRelationEnums relationType, Long typeId, Long relationId) { return super.count(Cnd.NEW().andEX("type", "=", relationType).andEX("typeId", "=", typeId).andEX("relationId", "=", relationId)); } @Override public TypeRelation exist(TypeRelationEnums relationType, Long typeId, Long relationId) { return super.fetch(Cnd.NEW().andEX("type", "=", relationType).andEX("typeId", "=", typeId).andEX("relationId", "=", relationId)); } @Override public <T> List<NutMap> nutMapByRelation(String sqlName, Condition cnd, Class<T> tClass, TypeRelationEnums relationType, Long relationTypeId) { Sql sql = dao().sqls().create(sqlName) .setParam("relation_type", relationType) .setParam("relation_type_id", relationTypeId) .setCondition(cnd) .setEntity(dao().getEntity(tClass)) .setCallback(Sqls.callback.maps()); dao().execute(sql); return sql.getList(NutMap.class); } @Override public Integer setRelation(TypeRelationEnums relationType, Long typeId, List<Long> relationIdList, Boolean reset) { if (relationType == null || typeId == null || relationIdList == null) { return 0; } if (reset) { removeRelation(relationType, typeId, null); } Integer passCount = 0; if (relationIdList != null && relationIdList.size() > 0) { for (Long relationId : relationIdList) { passCount = setRelation(relationType, typeId, relationId) ? 1 : 0; } } return passCount; } @Override public Boolean setRelation(TypeRelationEnums relationType, Long typeId, Long relationId) { try { save(new TypeRelation(relationId, relationType, typeId, DateUtils.getTS(), DateUtils.getTS())); return true; } catch (Exception ex) { logger.error("设置业务关系数据操作失败==>", ex); return false; } } @Override public Integer setRelation(TypeRelationEnums relationType, List<Long> typeIdList, Long relationId, Boolean reset) { if (relationType == null || relationId == null) { return 0; } if (reset) { removeRelation(relationType, null, relationId); } Integer passCount = 0; if (typeIdList != null && typeIdList.size() > 0) { for (Long typeId : typeIdList) { passCount = setRelation(relationType, typeId, relationId) ? 1 : 0; } } return passCount; } @Override public List<Long> relationIdListByType(TypeRelationEnums relationType, Long typeId) { List<TypeRelation> list = query(Cnd.where("typeId", "=", typeId).and("type", "=", relationType)); if (list == null || list.size() == 0) { return null; } return list.stream().map(v -> v.getRelationId()).collect(Collectors.toList()); } @Override public boolean removeRelation(TypeRelationEnums relationType, Long typeId, Long relationId) { return dao().clear(TypeRelation.class, Cnd.NEW().andEX("typeId", "=", typeId) .andEX("type", "=", relationType) .andEX("relationId", "=", relationId)) > 0; } }
39.52439
203
0.645788
99d31c26c9aba72964aaa9863da1fe58a218d031
3,957
/* * Copyright (c) 2016 Hugo Matalonga & João Paulo Fernandes * * 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.hmatalonga.greenhub.receivers; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.hmatalonga.greenhub.events.RefreshEvent; import com.hmatalonga.greenhub.network.CommunicationManager; import com.hmatalonga.greenhub.tasks.CheckNewMessagesTask; import com.hmatalonga.greenhub.tasks.ServerStatusTask; import com.hmatalonga.greenhub.util.SettingsUtils; import org.greenrobot.eventbus.EventBus; /** * ConnectivityReceiver. */ public class ConnectivityReceiver extends BroadcastReceiver { /** * Used to start update network status. * * @param context the context * @param intent the intent */ @Override public void onReceive(Context context, Intent intent) { int state; String action = intent.getAction(); if (action == null) return; switch (action) { case ConnectivityManager.CONNECTIVITY_ACTION: ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); if (connectivityManager == null) return; NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (!isConnected) { EventBus.getDefault().post(new RefreshEvent("wifi", false)); EventBus.getDefault().post(new RefreshEvent("mobile", false)); return; } // Reset upload uploadAttempts counter on network state change CommunicationManager.uploadAttempts = 0; // Update Server Status new ServerStatusTask().execute(context); if (SettingsUtils.isDeviceRegistered(context)) { new CheckNewMessagesTask().execute(context); } if (CommunicationManager.isQueued && SettingsUtils.isServerUrlPresent(context)) { CommunicationManager manager = new CommunicationManager(context, true); manager.sendSamples(); CommunicationManager.isQueued = false; } if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { EventBus.getDefault().post(new RefreshEvent("wifi", true)); } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { EventBus.getDefault().post(new RefreshEvent("mobile", true)); } break; case BluetoothAdapter.ACTION_STATE_CHANGED: state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); if (state == BluetoothAdapter.STATE_ON) { EventBus.getDefault().post(new RefreshEvent("bluetooth", true)); } else { EventBus.getDefault().post(new RefreshEvent("bluetooth", false)); } break; } } }
38.048077
97
0.628506
2c893ccbfe6a96ed8c0dd5764fed5743adb8fbb6
800
package conf_5_2_1; import java.net.UnknownHostException; import org.esfinge.querybuilder.annotation.ServicePriority; import org.esfinge.querybuilder.mongodb.DatastoreProvider; import com.google.code.morphia.Datastore; import com.mongodb.Mongo; import com.mongodb.MongoException; @ServicePriority(1) public class MongoDBDatastoreProvider extends DatastoreProvider{ public MongoDBDatastoreProvider() { try{ mongo = new Mongo("localhost", 27017); }catch(UnknownHostException e){ e.printStackTrace(); }catch(MongoException e){ e.printStackTrace(); } getMorphia().map(Cachorro.class); getMorphia().map(Cliente.class); getMorphia().map(Pagamento.class); } @Override public Datastore getDatastore() { return getMorphia().createDatastore(mongo, "testdb"); } }
22.857143
64
0.76125
0c35e037587d001b97787059ec9a3697157187e6
1,574
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.dsl.parser.elements; import java.util.Map; import java.util.Map.Entry; import org.jetbrains.annotations.NotNull; public class GradleDslElementEnum extends GradlePropertiesDslElement { private GradleDslElementEnum(@NotNull GradleDslElement parent, @NotNull GradleNameElement name) { super(parent, null, name); } public GradleDslElementEnum(@NotNull GradleDslElement parent, @NotNull GradleNameElement name, Map<String,String> values) { this(parent, name); for (Entry<String, String> entry : values.entrySet()) { GradleDslGlobalValue element = new GradleDslGlobalValue(this, new EnumValue(entry.getValue()), entry.getKey()); addDefaultProperty(element); } } public static class EnumValue { @NotNull private final String myValue; private EnumValue(@NotNull String value) { myValue = value; } public String getValue() { return myValue; } } }
33.489362
125
0.73507
4c0d5f1fdc50728ec48bbad2d47b300c978f75d8
2,400
package org.folio.services; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.folio.invoices.utils.HelperUtils.buildIdsChunks; import static org.folio.invoices.utils.HelperUtils.collectResultsOnSuccess; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import org.folio.rest.acq.model.Organization; import org.folio.rest.acq.model.OrganizationCollection; import org.folio.rest.impl.VendorHelper; import org.folio.rest.jaxrs.model.Invoice; import io.vertx.core.Context; public class VendorRetrieveService { static final int MAX_IDS_FOR_GET_RQ = 15; private final VendorHelper vendorHelper; public VendorRetrieveService(Map<String, String> okapiHeaders, Context ctx, String lang) { this.vendorHelper = new VendorHelper(okapiHeaders, ctx, lang); } public CompletableFuture<Map<String, Organization>> getVendorsMap(List<Invoice> invoices) { CompletableFuture<Map<String, Organization>> future = new CompletableFuture<>(); getVendorsByChunks(invoices, MAX_IDS_FOR_GET_RQ) .thenApply(organizationCollections -> organizationCollections.stream() .map(OrganizationCollection::getOrganizations) .collect(toList()).stream() .flatMap(List::stream) .collect(Collectors.toList())) .thenAccept(organizations -> future.complete(organizations.stream().collect(toMap(Organization::getId, Function.identity())))) .thenAccept(v -> vendorHelper.closeHttpClient()) .exceptionally(t -> { future.completeExceptionally(t); vendorHelper.closeHttpClient(); return null; }); return future; } public CompletableFuture<List<OrganizationCollection>> getVendorsByChunks(List<Invoice> invoices, int maxRecordsPerGet) { List<CompletableFuture<OrganizationCollection>> invoiceFutureList = buildIdsChunks(invoices, maxRecordsPerGet).values() .stream() .map(this::getVendorIds) .map(vendorHelper::getVendors) .collect(Collectors.toList()); return collectResultsOnSuccess(invoiceFutureList); } private Set<String> getVendorIds(List<Invoice> invoices) { return invoices.stream() .map(Invoice::getVendorId) .collect(Collectors.toSet()); } }
36.923077
132
0.750833
1be303e9c9132501769e32e57124031804461cdf
305
package com.motodb.controller; import com.motodb.view.GUI; public class Main { private final GUI firstFrame; public Main() { this.firstFrame = new GUI(); this.firstFrame.launcher(new String[] {}); } public static void main(String[] args) { new Main(); } }
16.944444
50
0.609836
ddb99411b17789d8305c30a44ef6a442f44cc94a
2,584
package com.qugengting.videoplay; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class BitmapSizeUtils { private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // 源图片的高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // 计算出实际宽高和目标宽高的比率 final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高 // 一定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } public static Bitmap decodeSampledBitmapFromResource(String filePath, int reqWidth, int reqHeight) { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static void compressSize(Bitmap bitmap, String toFile, int targetWidth, int quality) { try { int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int targetHeight = bitmapHeight * targetWidth / bitmapWidth; Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true); File myCaptureFile = new File(toFile); FileOutputStream out = new FileOutputStream(myCaptureFile); if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) { out.flush(); out.close(); } if (!bitmap.isRecycled()) { bitmap.recycle(); } if (!resizeBitmap.isRecycled()) { resizeBitmap.recycle(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
39.753846
106
0.642415
f332098ab39fdff5964c5592d2113ce76bd83b68
5,117
package com.actian.ilabs.dataflow.cassandra.reader; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.actian.ilabs.dataflow.cassandra.connection.ClusterSession; import com.actian.ilabs.dataflow.cassandra.getter.GetterFactory; import com.actian.ilabs.dataflow.cassandra.query.Query; import com.actian.ilabs.dataflow.cassandra.setter.Setter; import com.actian.ilabs.dataflow.cassandra.setter.Setters; import com.pervasive.datarush.operators.ExecutableOperator; import com.pervasive.datarush.operators.ExecutionContext; import com.pervasive.datarush.operators.ParallelismStrategy; import com.pervasive.datarush.operators.StreamingMetadataContext; import com.pervasive.datarush.ports.physical.ObjectInputField; import com.pervasive.datarush.ports.physical.RecordInput; import com.pervasive.datarush.ports.physical.RecordOutput; import com.pervasive.datarush.ports.record.FullDataDistribution; import com.pervasive.datarush.ports.record.RecordPort; import com.pervasive.datarush.types.Field; import com.pervasive.datarush.types.ScalarTokenType; import java.util.ArrayList; import java.util.List; import static com.actian.ilabs.dataflow.cassandra.query.Queries.query; public class ReadSplits extends ExecutableOperator { private final RecordPort input = newRecordInput("input"); private final RecordPort output = newRecordOutput("output"); private String splitsFieldName; private Query query; private String[] nodes; private String user; private String password; public RecordPort getInput() { return input; } public RecordPort getOutput() { return output; } public String getSplitsFieldName() { return splitsFieldName; } public void setSplitsFieldName(String splitsFieldName) { this.splitsFieldName = splitsFieldName; } public Query getQuery() { return query; } public void setQuery(Query queryMetadata) { this.query = queryMetadata; } public String[] getNodes() { return nodes; } public void setNodes(String... nodes) { this.nodes = nodes; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override protected void computeMetadata(StreamingMetadataContext context) { output.setType(context, query.getOutputType()); input.setRequiredDataDistribution(context, FullDataDistribution.INSTANCE); context.parallelize(ParallelismStrategy.CONFIGURED); } @Override protected void execute(ExecutionContext context) { RecordOutput recordOutput = output.getOutput(context); RecordInput recordInput = input.getInput(context); @SuppressWarnings("unchecked") ObjectInputField<Split> parameterField = (ObjectInputField<Split>)recordInput.getField(splitsFieldName); String originalNode = context.getPartitionInfo().getAssignment().getOriginalNodeID().toString(); ClusterSession session = null; try { session = new ClusterSession(nodes, user, password); Setter[] setters = setters(session, recordOutput); while (recordInput.stepNext()) { Split split = parameterField.asObject(); if (split.getNode().equals(originalNode)) { ResultSet result = session.execute(query.getQueryString(), split.getParameters()); for (Row row : result) { for (Setter decoder : setters) { decoder.set(row); } recordOutput.push(); } } } } finally { if (session != null) { session.close(); } } recordOutput.pushEndOfData(); } /** * Compare the column definitions with the expected output type * and create appropriate decoders. Filter out fields, that * changed incompatibly (removed, renamed or changed the type to * an incompatible type) between the the computeMetadata phase * and the execution phase. Their value will be set to null. */ private Setter[] setters(ClusterSession session, RecordOutput recordOutput) { Query originalQuery = this.query; Query currentQuery = query(session, query.getQueryString()); if (originalQuery.getOutputType().equals(currentQuery.getOutputType())) { return Setters.setters(recordOutput, originalQuery.getOutputNames(), originalQuery.getJavaOutputTypes()); } else { List<String> outputFieldNames = new ArrayList<String>(); List<Class<?>> outputFieldJavaTypes = new ArrayList<Class<?>>(); for (String name : currentQuery.getOutputNames()) { Field originalField = originalQuery.getOutputType().get(name); if (originalField != null) { ScalarTokenType originalFieldType = originalField.getType(); Class<?> currentFieldJavaType = currentQuery.javaOuputType(name); if (GetterFactory.targetJavaTypes(originalFieldType).contains(currentFieldJavaType)) { outputFieldNames.add(name); outputFieldJavaTypes.add(currentFieldJavaType); } } } return Setters.setters(recordOutput, outputFieldNames.toArray(new String[outputFieldNames.size()]), outputFieldJavaTypes.toArray(new Class<?>[outputFieldJavaTypes.size()])); } } }
31.782609
108
0.756107
64ba037621e923f04f344e588dfd22ad177e03c3
16,916
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.parser; import org.eclipse.jdt.core.compiler.*; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; public class RecoveredBlock extends RecoveredStatement implements TerminalTokens { public Block blockDeclaration; public RecoveredStatement[] statements; public int statementCount; public boolean preserveContent = false; public RecoveredLocalVariable pendingArgument; int pendingModifiers; int pendingModifersSourceStart = -1; RecoveredAnnotation[] pendingAnnotations; int pendingAnnotationCount; public RecoveredBlock(Block block, RecoveredElement parent, int bracketBalance){ super(block, parent, bracketBalance); this.blockDeclaration = block; this.foundOpeningBrace = true; this.preserveContent = parser().methodRecoveryActivated || parser().statementRecoveryActivated; } public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) { if (this.parent != null && this.parent instanceof RecoveredMethod) { RecoveredMethod enclosingRecoveredMethod = (RecoveredMethod) this.parent; if (enclosingRecoveredMethod.methodBody == this && enclosingRecoveredMethod.parent == null) { resetPendingModifiers(); // the element cannot be added because we are in the body of a top level method return this; // ignore this element } } return super.add(methodDeclaration, bracketBalanceValue); } /* * Record a nested block declaration */ public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) { resetPendingModifiers(); /* do not consider a nested block starting passed the block end (if set) it must be belonging to an enclosing block */ if (this.blockDeclaration.sourceEnd != 0 && nestedBlockDeclaration.sourceStart > this.blockDeclaration.sourceEnd){ return this.parent.add(nestedBlockDeclaration, bracketBalanceValue); } RecoveredBlock element = new RecoveredBlock(nestedBlockDeclaration, this, bracketBalanceValue); // if we have a pending Argument, promote it into the new block if (this.pendingArgument != null){ element.attach(this.pendingArgument); this.pendingArgument = null; } if(parser().statementRecoveryActivated) { addBlockStatement(element); } attach(element); if (nestedBlockDeclaration.sourceEnd == 0) return element; return this; } /* * Record a local declaration */ public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) { return this.add(localDeclaration, bracketBalanceValue, false); } /* * Record a local declaration */ public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue, boolean delegatedByParent) { /* local variables inside method can only be final and non void */ /* char[][] localTypeName; if ((localDeclaration.modifiers & ~AccFinal) != 0 // local var can only be final || (localDeclaration.type == null) // initializer || ((localTypeName = localDeclaration.type.getTypeName()).length == 1 // non void && CharOperation.equals(localTypeName[0], VoidBinding.sourceName()))){ if (delegatedByParent){ return this; //ignore } else { this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart - 1)); return this.parent.add(localDeclaration, bracketBalance); } } */ /* do not consider a local variable starting passed the block end (if set) it must be belonging to an enclosing block */ if (this.blockDeclaration.sourceEnd != 0 && localDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){ resetPendingModifiers(); if (delegatedByParent) return this; //ignore return this.parent.add(localDeclaration, bracketBalanceValue); } RecoveredLocalVariable element = new RecoveredLocalVariable(localDeclaration, this, bracketBalanceValue); if(this.pendingAnnotationCount > 0) { element.attach( this.pendingAnnotations, this.pendingAnnotationCount, this.pendingModifiers, this.pendingModifersSourceStart); } resetPendingModifiers(); if (localDeclaration instanceof Argument){ this.pendingArgument = element; return this; } attach(element); if (localDeclaration.declarationSourceEnd == 0) return element; return this; } /* * Record a statement declaration */ public RecoveredElement add(Statement stmt, int bracketBalanceValue) { return this.add(stmt, bracketBalanceValue, false); } /* * Record a statement declaration */ public RecoveredElement add(Statement stmt, int bracketBalanceValue, boolean delegatedByParent) { resetPendingModifiers(); /* do not consider a nested block starting passed the block end (if set) it must be belonging to an enclosing block */ if (this.blockDeclaration.sourceEnd != 0 && stmt.sourceStart > this.blockDeclaration.sourceEnd){ if (delegatedByParent) return this; //ignore return this.parent.add(stmt, bracketBalanceValue); } RecoveredStatement element = new RecoveredStatement(stmt, this, bracketBalanceValue); attach(element); if (stmt.sourceEnd == 0) return element; return this; } /* * Addition of a type to an initializer (act like inside method body) */ public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) { return this.add(typeDeclaration, bracketBalanceValue, false); } /* * Addition of a type to an initializer (act like inside method body) */ public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue, boolean delegatedByParent) { /* do not consider a type starting passed the block end (if set) it must be belonging to an enclosing block */ if (this.blockDeclaration.sourceEnd != 0 && typeDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){ resetPendingModifiers(); if (delegatedByParent) return this; //ignore return this.parent.add(typeDeclaration, bracketBalanceValue); } RecoveredType element = new RecoveredType(typeDeclaration, this, bracketBalanceValue); if(this.pendingAnnotationCount > 0) { element.attach( this.pendingAnnotations, this.pendingAnnotationCount, this.pendingModifiers, this.pendingModifersSourceStart); } resetPendingModifiers(); attach(element); if (typeDeclaration.declarationSourceEnd == 0) return element; return this; } public RecoveredElement addAnnotationName(int identifierPtr, int identifierLengthPtr, int annotationStart, int bracketBalanceValue) { if (this.pendingAnnotations == null) { this.pendingAnnotations = new RecoveredAnnotation[5]; this.pendingAnnotationCount = 0; } else { if (this.pendingAnnotationCount == this.pendingAnnotations.length) { System.arraycopy( this.pendingAnnotations, 0, (this.pendingAnnotations = new RecoveredAnnotation[2 * this.pendingAnnotationCount]), 0, this.pendingAnnotationCount); } } RecoveredAnnotation element = new RecoveredAnnotation(identifierPtr, identifierLengthPtr, annotationStart, this, bracketBalanceValue); this.pendingAnnotations[this.pendingAnnotationCount++] = element; return element; } public void addModifier(int flag, int modifiersSourceStart) { this.pendingModifiers |= flag; if (this.pendingModifersSourceStart < 0) { this.pendingModifersSourceStart = modifiersSourceStart; } } /* * Attach a recovered statement */ void attach(RecoveredStatement recoveredStatement) { if (this.statements == null) { this.statements = new RecoveredStatement[5]; this.statementCount = 0; } else { if (this.statementCount == this.statements.length) { System.arraycopy( this.statements, 0, (this.statements = new RecoveredStatement[2 * this.statementCount]), 0, this.statementCount); } } this.statements[this.statementCount++] = recoveredStatement; } void attachPendingModifiers(RecoveredAnnotation[] pendingAnnots, int pendingAnnotCount, int pendingMods, int pendingModsSourceStart) { this.pendingAnnotations = pendingAnnots; this.pendingAnnotationCount = pendingAnnotCount; this.pendingModifiers = pendingMods; this.pendingModifersSourceStart = pendingModsSourceStart; } /* * Answer the associated parsed structure */ public ASTNode parseTree(){ return this.blockDeclaration; } public void resetPendingModifiers() { this.pendingAnnotations = null; this.pendingAnnotationCount = 0; this.pendingModifiers = 0; this.pendingModifersSourceStart = -1; } public String toString(int tab) { StringBuffer result = new StringBuffer(tabString(tab)); result.append("Recovered block:\n"); //$NON-NLS-1$ this.blockDeclaration.print(tab + 1, result); if (this.statements != null) { for (int i = 0; i < this.statementCount; i++) { result.append("\n"); //$NON-NLS-1$ result.append(this.statements[i].toString(tab + 1)); } } return result.toString(); } /* * Rebuild a block from the nested structure which is in scope */ public Block updatedBlock(){ // if block was not marked to be preserved or empty, then ignore it if (!this.preserveContent || this.statementCount == 0) return null; Statement[] updatedStatements = new Statement[this.statementCount]; int updatedCount = 0; // may need to update the end of the last statement RecoveredStatement lastStatement = this.statements[this.statementCount - 1]; RecoveredMethod enclosingMethod = enclosingMethod(); RecoveredInitializer enclosingIntializer = enclosingInitializer(); int bodyEndValue = 0; if(enclosingMethod != null) { bodyEndValue = enclosingMethod.methodDeclaration.bodyEnd; if(enclosingIntializer != null && enclosingMethod.methodDeclaration.sourceStart < enclosingIntializer.fieldDeclaration.sourceStart) { bodyEndValue = enclosingIntializer.fieldDeclaration.declarationSourceEnd; } } else if(enclosingIntializer != null) { bodyEndValue = enclosingIntializer.fieldDeclaration.declarationSourceEnd; } else { bodyEndValue = this.blockDeclaration.sourceEnd - 1; } if(lastStatement instanceof RecoveredLocalVariable) { RecoveredLocalVariable lastLocalVariable = (RecoveredLocalVariable) lastStatement; if(lastLocalVariable.localDeclaration.declarationSourceEnd == 0) { lastLocalVariable.localDeclaration.declarationSourceEnd = bodyEndValue; lastLocalVariable.localDeclaration.declarationEnd = bodyEndValue; } } else if(lastStatement instanceof RecoveredBlock) { RecoveredBlock lastBlock = (RecoveredBlock) lastStatement; if(lastBlock.blockDeclaration.sourceEnd == 0) { lastBlock.blockDeclaration.sourceEnd = bodyEndValue; } } else if(!(lastStatement instanceof RecoveredType)){ if(lastStatement.statement.sourceEnd == 0) { lastStatement.statement.sourceEnd = bodyEndValue; } } int lastEnd = this.blockDeclaration.sourceStart; // only collect the non-null updated statements for (int i = 0; i < this.statementCount; i++){ Statement updatedStatement = this.statements[i].updatedStatement(); if (updatedStatement != null){ updatedStatements[updatedCount++] = updatedStatement; if (updatedStatement instanceof LocalDeclaration) { LocalDeclaration localDeclaration = (LocalDeclaration) updatedStatement; if(localDeclaration.declarationSourceEnd > lastEnd) { lastEnd = localDeclaration.declarationSourceEnd; } } else if (updatedStatement instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) updatedStatement; if(typeDeclaration.declarationSourceEnd > lastEnd) { lastEnd = typeDeclaration.declarationSourceEnd; } } else { if (updatedStatement.sourceEnd > lastEnd) { lastEnd = updatedStatement.sourceEnd; } } } } if (updatedCount == 0) return null; // not interesting block // resize statement collection if necessary if (updatedCount != this.statementCount){ this.blockDeclaration.statements = new Statement[updatedCount]; System.arraycopy(updatedStatements, 0, this.blockDeclaration.statements, 0, updatedCount); } else { this.blockDeclaration.statements = updatedStatements; } if (this.blockDeclaration.sourceEnd == 0) { if(lastEnd < bodyEndValue) { this.blockDeclaration.sourceEnd = bodyEndValue; } else { this.blockDeclaration.sourceEnd = lastEnd; } } return this.blockDeclaration; } /* * Rebuild a statement from the nested structure which is in scope */ public Statement updatedStatement(){ return updatedBlock(); } /* * A closing brace got consumed, might have closed the current element, * in which case both the currentElement is exited */ public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){ if ((--this.bracketBalance <= 0) && (this.parent != null)){ this.updateSourceEndIfNecessary(braceStart, braceEnd); /* if the block is the method body, then it closes the method too */ RecoveredMethod method = enclosingMethod(); if (method != null && method.methodBody == this){ return this.parent.updateOnClosingBrace(braceStart, braceEnd); } RecoveredInitializer initializer = enclosingInitializer(); if (initializer != null && initializer.initializerBody == this){ return this.parent.updateOnClosingBrace(braceStart, braceEnd); } return this.parent; } return this; } /* * An opening brace got consumed, might be the expected opening one of the current element, * in which case the bodyStart is updated. */ public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){ // create a nested block Block block = new Block(0); block.sourceStart = parser().scanner.startPosition; return this.add(block, 1); } /* * Final update the corresponding parse node */ public void updateParseTree(){ updatedBlock(); } /* * Rebuild a flattened block from the nested structure which is in scope */ public Statement updateStatement(){ // if block was closed or empty, then ignore it if (this.blockDeclaration.sourceEnd != 0 || this.statementCount == 0) return null; Statement[] updatedStatements = new Statement[this.statementCount]; int updatedCount = 0; // only collect the non-null updated statements for (int i = 0; i < this.statementCount; i++){ Statement updatedStatement = this.statements[i].updatedStatement(); if (updatedStatement != null){ updatedStatements[updatedCount++] = updatedStatement; } } if (updatedCount == 0) return null; // not interesting block // resize statement collection if necessary if (updatedCount != this.statementCount){ this.blockDeclaration.statements = new Statement[updatedCount]; System.arraycopy(updatedStatements, 0, this.blockDeclaration.statements, 0, updatedCount); } else { this.blockDeclaration.statements = updatedStatements; } return this.blockDeclaration; } /* * Record a field declaration */ public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) { resetPendingModifiers(); /* local variables inside method can only be final and non void */ char[][] fieldTypeName; if ((fieldDeclaration.modifiers & ~ClassFileConstants.AccFinal) != 0 // local var can only be final || (fieldDeclaration.type == null) // initializer || ((fieldTypeName = fieldDeclaration.type.getTypeName()).length == 1 // non void && CharOperation.equals(fieldTypeName[0], TypeBinding.VOID.sourceName()))){ this.updateSourceEndIfNecessary(previousAvailableLineEnd(fieldDeclaration.declarationSourceStart - 1)); return this.parent.add(fieldDeclaration, bracketBalanceValue); } /* do not consider a local variable starting passed the block end (if set) it must be belonging to an enclosing block */ if (this.blockDeclaration.sourceEnd != 0 && fieldDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){ return this.parent.add(fieldDeclaration, bracketBalanceValue); } // ignore the added field, since indicates a local variable behind recovery point // which thus got parsed as a field reference. This can happen if restarting after // having reduced an assistNode to get the following context (see 1GEK7SG) return this; } }
35.838983
135
0.760996
db9055643591899711a0a006e90a8178c498580c
1,810
package com.stripe.samplestore; import android.support.annotation.Nullable; import java.text.DecimalFormat; import java.util.Currency; /** * Class for utility functions. */ public class StoreUtils { static String getEmojiByUnicode(int unicode){ return new String(Character.toChars(unicode)); } static String getPriceString(long price, @Nullable Currency currency) { Currency displayCurrency = currency == null ? Currency.getInstance("USD") : currency; int fractionDigits = displayCurrency.getDefaultFractionDigits(); int totalLength = String.valueOf(price).length(); StringBuilder builder = new StringBuilder(); builder.append('\u00A4'); if (fractionDigits == 0) { for (int i = 0; i < totalLength; i++) { builder.append('#'); } DecimalFormat noDecimalCurrencyFormat = new DecimalFormat(builder.toString()); noDecimalCurrencyFormat.setCurrency(displayCurrency); return noDecimalCurrencyFormat.format(price); } int beforeDecimal = totalLength - fractionDigits; for (int i = 0; i < beforeDecimal; i++) { builder.append('#'); } // So we display "$0.55" instead of "$.55" if (totalLength <= fractionDigits) { builder.append('0'); } builder.append('.'); for (int i = 0; i < fractionDigits; i++) { builder.append('0'); } double modBreak = Math.pow(10, fractionDigits); double decimalPrice = price / modBreak; DecimalFormat decimalFormat = new DecimalFormat(builder.toString()); decimalFormat.setCurrency(displayCurrency); return decimalFormat.format(decimalPrice); } }
31.754386
90
0.61326
87eb31f48b32fc229e23d538d2f0eab1fcc305de
1,145
package eapli.base.rawmaterialmanagement.domain; import junit.framework.TestCase; import org.junit.Test; public class RawMaterialTest { @Test(expected = IllegalArgumentException.class) public void ensureMustHaveCategory() { new RawMaterial("PT50", "Exemplo1", "ExemploDescricao1", null); } @Test(expected = IllegalArgumentException.class) public void ensureMustHaveCode() { new RawMaterial(null, "Exemplo2", "ExemploDescricao2", new RawMaterialCategory("CAT14A", "Categoria1")); } @Test(expected = IllegalArgumentException.class) public void ensureMustHaveTechnicalSheet() { new RawMaterial("PT500", null, "ExemploDescricao2", new RawMaterialCategory("CAT14A", "Categoria1")); } @Test(expected = IllegalArgumentException.class) public void ensureMustHaveDescription() { new RawMaterial("PT500", "Exemplo346", null, new RawMaterialCategory("CAT14A", "Categoria1")); } @Test public void ensureRawMaterialIsCreatedWithSuccess() { new RawMaterial("PT246", "Exemplo2", "ExemploDescricao2", new RawMaterialCategory("CAT14A", "Categoria1")); } }
35.78125
115
0.717904
dc8e487d748e98948631767c2f27549ae61998a1
2,882
/* * PowerAuth Web Flow and related software components * Copyright (C) 2017 Wultra s.r.o. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.getlime.security.powerauth.app.webflow.demo.model; /** * Class representing a user displayed in the UI. * * @author Petr Dvorak, petr@wultra.com */ public class UserResponse { /** * Information about the user. */ public class User { private String id; private String givenName; private String familyName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } } /** * Information about the connection. */ public class Connection { private String language; private boolean sca; private String organizationId; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public boolean isSca() { return sca; } public void setSca(boolean sca) { this.sca = sca; } public String getOrganizationId() { return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } } private User user; private Connection connection; public UserResponse() { super(); this.user = new User(); this.connection = new Connection(); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Connection getConnection() { return connection; } public void setConnection(Connection connection) { this.connection = connection; } }
23.622951
75
0.607217
89f6fffa3590916e8df41c5f48997e080bd9a986
3,822
/* * Copyright © 2022 DATAMART LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 ru.datamart.prostore.query.execution.core.plugin.configuration; import ru.datamart.prostore.common.reader.SourceType; import lombok.val; import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.TypeFilter; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; public class ExcludePluginFilter implements TypeFilter { private static final String PLUGIN_PACKAGE_PATTERN_TEMPLATE = "ru.datamart.prostore.query.execution.plugin.(%s)"; private static final String CORE_PLUGINS_ACTIVE = "core.plugins.active"; private Pattern filter; @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { if (filter == null) { filter = initFilter(metadataReaderFactory).orElse(Pattern.compile("")); } val classMetadata = metadataReader.getClassMetadata(); val fullyQualifiedName = classMetadata.getClassName(); return filter.matcher(fullyQualifiedName).matches(); } private Optional<Pattern> initFilter(MetadataReaderFactory metadataReaderFactory) { val activePlugins = getActivePlugins(metadataReaderFactory); val excludedSources = getExcludedSources(activePlugins); if (activePlugins.isEmpty() || excludedSources.isEmpty()) { return Optional.empty(); } else { val filterPattern = String.format(PLUGIN_PACKAGE_PATTERN_TEMPLATE, String.join("|", excludedSources)); return Optional.of(Pattern.compile(filterPattern)); } } private List<String> getExcludedSources(List<String> activePlugins) { return Arrays.stream(SourceType.values()) .filter(sourceType -> sourceType != SourceType.INFORMATION_SCHEMA) .map(Enum::name) .filter(typeName -> activePlugins.stream() .noneMatch(apName -> apName.equalsIgnoreCase(typeName))) .map(typeName -> String.format("%s.*", typeName.toLowerCase())) .collect(Collectors.toList()); } private List<String> getActivePlugins(MetadataReaderFactory metadataReaderFactory) { return Arrays.stream(getActivePluginsSettings(metadataReaderFactory).split(",")) .map(pluginName -> pluginName.toUpperCase().trim()) .collect(Collectors.toList()); } private String getActivePluginsSettings(MetadataReaderFactory metadataReaderFactory) { val cachingMetadataReaderFactory = (CachingMetadataReaderFactory) metadataReaderFactory; val applicationContext = (AnnotationConfigReactiveWebServerApplicationContext) cachingMetadataReaderFactory.getResourceLoader(); val environment = applicationContext.getEnvironment(); return environment.getProperty(CORE_PLUGINS_ACTIVE); } }
46.048193
136
0.729461
dea8b77ad916a7b41370fbf8ec9b72086bfbc06f
1,937
package com.ruoyi.store.domain; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.ruoyi.common.utils.CustomLocalDateTimeDeserializer; import com.ruoyi.common.utils.CustomLocalDateTimeSerializer; import com.ruoyi.goods.domain.PmsSku; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.time.LocalDateTime; import java.util.List; /** * 关注店铺实体类 * * @author 伊甸园商城 on 2017/7/4. */ @Data @ApiModel(description = "关注店铺实体类") public class AttentionStore { /** * 主键id */ @ApiModelProperty(value = "主键id") private long id; /** * 会员id */ @ApiModelProperty(value = "会员id") private long customerId; /** * 店铺id */ @ApiModelProperty(value = "店铺id") private long storeId; /** * 删除标记 0 未删除 1 删除 */ @ApiModelProperty(value = "删除标记 0 未删除 1 删除") private int delFlag; /** * 创建时间 */ @JsonSerialize(using = CustomLocalDateTimeSerializer.class) @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class) @ApiModelProperty(value = "创建时间") private LocalDateTime createTime; /** * 店铺信息 */ @ApiModelProperty(value = "店铺信息") private TStoreInfo storeInfo; /** * 商品集合 */ @ApiModelProperty(value = "商品集合") private List<PmsSku> skuList; /** * 关注店铺数量 */ @ApiModelProperty(value = "关注店铺数量") private int storeAttentionCount; /** * 获取店铺关注 * * @param storeInfo 店铺信息 * @param skuList 单品集合 * @return 返回店铺关注 */ public AttentionStore getAttentionStore(TStoreInfo storeInfo, List<PmsSku> skuList, int storeAttentionCount) { this.setStoreInfo(storeInfo); this.setSkuList(skuList); this.setStoreAttentionCount(storeAttentionCount); return this; } }
23.621951
114
0.662364
4f67b098ed2c457fda2395d79145706b8350baaa
6,410
package mysh.sql; import java.io.Serializable; import java.util.Date; public class UmOrg implements Serializable { private Long orgId; private Long domainId; private Long parentOrgId; private String orgCode; private String orgName; private Short orgState; private String remarks; private String orgType; private String orgShort; private String orgIntroduct; private String provinceCode; private String cityCode; private String districtCode; private String streetCode; private String villageCode; private Long updateOperatorId; private Date updateTime; private Long createOperatorId; private Date createTime; private String webUrl; private String email; private String postcode; private String faxNo; private String orgAddr; private String contactTel; private String contactName; private String lawPersonTel; private String lawPersonName; private Integer orgLevel; private static final long serialVersionUID = 1L; public Long getOrgId() { return orgId; } public void setOrgId(Long orgId) { this.orgId = orgId; } public Long getDomainId() { return domainId; } public void setDomainId(Long domainId) { this.domainId = domainId; } public Long getParentOrgId() { return parentOrgId; } public void setParentOrgId(Long parentOrgId) { this.parentOrgId = parentOrgId; } public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode == null ? null : orgCode.trim(); } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName == null ? null : orgName.trim(); } public Short getOrgState() { return orgState; } public void setOrgState(Short orgState) { this.orgState = orgState; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks == null ? null : remarks.trim(); } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType == null ? null : orgType.trim(); } public String getOrgShort() { return orgShort; } public void setOrgShort(String orgShort) { this.orgShort = orgShort == null ? null : orgShort.trim(); } public String getOrgIntroduct() { return orgIntroduct; } public void setOrgIntroduct(String orgIntroduct) { this.orgIntroduct = orgIntroduct == null ? null : orgIntroduct.trim(); } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode == null ? null : provinceCode.trim(); } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode == null ? null : cityCode.trim(); } public String getDistrictCode() { return districtCode; } public void setDistrictCode(String districtCode) { this.districtCode = districtCode == null ? null : districtCode.trim(); } public String getStreetCode() { return streetCode; } public void setStreetCode(String streetCode) { this.streetCode = streetCode == null ? null : streetCode.trim(); } public String getVillageCode() { return villageCode; } public void setVillageCode(String villageCode) { this.villageCode = villageCode == null ? null : villageCode.trim(); } public Long getUpdateOperatorId() { return updateOperatorId; } public void setUpdateOperatorId(Long updateOperatorId) { this.updateOperatorId = updateOperatorId; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Long getCreateOperatorId() { return createOperatorId; } public void setCreateOperatorId(Long createOperatorId) { this.createOperatorId = createOperatorId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getWebUrl() { return webUrl; } public void setWebUrl(String webUrl) { this.webUrl = webUrl == null ? null : webUrl.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode == null ? null : postcode.trim(); } public String getFaxNo() { return faxNo; } public void setFaxNo(String faxNo) { this.faxNo = faxNo == null ? null : faxNo.trim(); } public String getOrgAddr() { return orgAddr; } public void setOrgAddr(String orgAddr) { this.orgAddr = orgAddr == null ? null : orgAddr.trim(); } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel == null ? null : contactTel.trim(); } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName == null ? null : contactName.trim(); } public String getLawPersonTel() { return lawPersonTel; } public void setLawPersonTel(String lawPersonTel) { this.lawPersonTel = lawPersonTel == null ? null : lawPersonTel.trim(); } public String getLawPersonName() { return lawPersonName; } public void setLawPersonName(String lawPersonName) { this.lawPersonName = lawPersonName == null ? null : lawPersonName.trim(); } public Integer getOrgLevel() { return orgLevel; } public void setOrgLevel(Integer orgLevel) { this.orgLevel = orgLevel; } }
21.438127
81
0.632293
e56b45d0d9a8d88b836c8ca97c311e2997b7aecd
689
package com.listenergao.audioandvideolearning.utils; import android.widget.Toast; import com.listenergao.audioandvideolearning.LearningApplication; public class ToastUtils { public static void toast(int resId) { toast(LearningApplication.getContext().getString(resId), Toast.LENGTH_SHORT); } public static void toast(String msg) { toast(msg, Toast.LENGTH_SHORT); } public static void toast(int resId, int duration) { toast(LearningApplication.getContext().getString(resId), duration); } private static void toast(String msg, int duration) { Toast.makeText(LearningApplication.getContext(), msg, duration).show(); } }
26.5
85
0.719884
68ebd6fa2ca0cf9146fafa974ab1f9b44bc87826
3,105
package css; import com.intellij.psi.PsiReference; import com.intellij.psi.css.CssDeclaration; import com.intellij.psi.css.inspections.CssInvalidElementInspection; import com.intellij.psi.css.inspections.CssUnknownPropertyInspection; import com.intellij.psi.css.inspections.invalid.CssUnknownTargetInspection; import com.intellij.psi.css.resolve.CssResolveManager; import com.intellij.psi.css.resolve.CssResolver; import com.intellij.psi.css.resolve.HtmlCssClassOrIdReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTag; import com.intellij.struts.StrutsTest; import com.intellij.util.containers.ContainerUtil; import java.io.IOException; public class CssInStrutsProjectResolveAndHighlightingTest extends StrutsTest { private static CssResolver getResolver() { final CssResolver resolver = CssResolveManager.getInstance().getNewResolver(); resolver.setUseAgentStylesheet(false); return resolver; } @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(new CssUnknownTargetInspection(), new CssInvalidElementInspection(), new CssUnknownPropertyInspection()); } public void testStrutsResolve() throws IOException { doStrutsTestWithGivenTldName("StrutsResolve","struts_html.tld"); } public void testStrutsResolve2() throws IOException { doStrutsTestWithGivenTldName("StrutsResolve","struts_html2.tld"); } public void testStrutsResolve3() throws IOException { doStrutsTestWithGivenTldName("StrutsResolve","struts_html3.tld"); } public void testStrutsResolve4() throws IOException { doStrutsTestWithGivenTldName("StrutsResolve","struts_html4.tld"); } private void doStrutsTestWithGivenTldName(String testName, final String name) throws IOException { myFixture.configureByFiles(testName + ".jsp", testName + ".css", "WEB-INF/" + name); myFixture.checkHighlighting(true, false, false); XmlTag tag = getTagAtCaret(); final CssDeclaration[] cssDeclarations = getResolver().resolve(tag); // do not pick up the style content from jsp include assertEquals( "css style ref in jsp", 3, cssDeclarations.length); for(String attrName : new String[] {"styleClass", "styleId"}) { final XmlAttribute attribute = tag.getAttribute(attrName, null); assertNotNull(attribute); final XmlAttributeValue valueElement = attribute.getValueElement(); final PsiReference[] references = valueElement.getReferences(); final HtmlCssClassOrIdReference ref = ContainerUtil.findInstance(references, HtmlCssClassOrIdReference.class); assertNotNull(ref); assertTrue( ref.multiResolve(false).length > 0 ); } } private XmlTag getTagAtCaret() { return PsiTreeUtil.getParentOfType(myFixture.getFile().findElementAt(myFixture.getEditor().getCaretModel().getOffset()), XmlTag.class); } @Override protected String getBasePath() { return "/css/"; } }
37.409639
139
0.756844
e4b3796cb15c35b933808a0706cde07c8eeb9cfd
1,963
package org.gradle.test.performance.mediummonolithicjavaproject.p156; public class Production3139 { private Production3136 property0; public Production3136 getProperty0() { return property0; } public void setProperty0(Production3136 value) { property0 = value; } private Production3137 property1; public Production3137 getProperty1() { return property1; } public void setProperty1(Production3137 value) { property1 = value; } private Production3138 property2; public Production3138 getProperty2() { return property2; } public void setProperty2(Production3138 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
18.695238
69
0.631177
fe7305f53ea4d3e0ead7de1cafe8102dbbeb8397
1,622
// // samskivert library - useful routines for java programs // Copyright (C) 2001-2012 Michael Bayne, et al. // http://github.com/samskivert/samskivert/blob/master/COPYING package com.samskivert.depot.impl.jdbc; import java.sql.Connection; import java.sql.SQLException; /** * The default liaison is used if no other liaison could be matched for a particular database * connection. It isn't very smart or useful but we need something. */ public class DefaultLiaison extends BaseLiaison { @Override // from DatabaseLiaison public boolean matchesURL (String url) { return true; } @Override // from DatabaseLiaison public boolean isDuplicateRowException (SQLException sqe) { return false; } @Override // from DatabaseLiaison public boolean isTransientException (SQLException sqe) { return false; } @Override // from DatabaseLiaison public void createGenerator (Connection conn, String tableName, String columnName, int initValue) throws SQLException { // nothing doing } @Override // from DatabaseLiaison public void deleteGenerator (Connection conn, String tableName, String columnName) throws SQLException { // nothing doing } @Override // from DatabaseLiaison public String columnSQL (String column) { return column; } @Override // from DatabaseLiaison public String tableSQL (String table) { return table; } @Override // from DatabaseLiaison public String indexSQL (String index) { return index; } }
24.208955
101
0.678175
d3b690365ee14e13b9245f518aa5f2519bbac1d2
51,406
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/tensor_slice.proto package org.tensorflow.framework; /** * <pre> * Can only be interpreted if you know the corresponding TensorShape. * </pre> * * Protobuf type {@code tensorflow.TensorSliceProto} */ public final class TensorSliceProto extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tensorflow.TensorSliceProto) TensorSliceProtoOrBuilder { // Use TensorSliceProto.newBuilder() to construct. private TensorSliceProto(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TensorSliceProto() { extent_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private TensorSliceProto( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { extent_ = new java.util.ArrayList<org.tensorflow.framework.TensorSliceProto.Extent>(); mutable_bitField0_ |= 0x00000001; } extent_.add( input.readMessage(org.tensorflow.framework.TensorSliceProto.Extent.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { extent_ = java.util.Collections.unmodifiableList(extent_); } makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.framework.TensorSliceProto.class, org.tensorflow.framework.TensorSliceProto.Builder.class); } public interface ExtentOrBuilder extends // @@protoc_insertion_point(interface_extends:tensorflow.TensorSliceProto.Extent) com.google.protobuf.MessageOrBuilder { /** * <pre> * Start index of the slice, starting at 0. * </pre> * * <code>optional int64 start = 1;</code> */ long getStart(); /** * <code>optional int64 length = 2;</code> */ long getLength(); public org.tensorflow.framework.TensorSliceProto.Extent.HasLengthCase getHasLengthCase(); } /** * <pre> * Extent of the slice in one dimension. * </pre> * * Protobuf type {@code tensorflow.TensorSliceProto.Extent} */ public static final class Extent extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tensorflow.TensorSliceProto.Extent) ExtentOrBuilder { // Use Extent.newBuilder() to construct. private Extent(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Extent() { start_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private Extent( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 8: { start_ = input.readInt64(); break; } case 16: { hasLengthCase_ = 2; hasLength_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_Extent_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_Extent_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.framework.TensorSliceProto.Extent.class, org.tensorflow.framework.TensorSliceProto.Extent.Builder.class); } private int hasLengthCase_ = 0; private java.lang.Object hasLength_; public enum HasLengthCase implements com.google.protobuf.Internal.EnumLite { LENGTH(2), HASLENGTH_NOT_SET(0); private final int value; private HasLengthCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static HasLengthCase valueOf(int value) { return forNumber(value); } public static HasLengthCase forNumber(int value) { switch (value) { case 2: return LENGTH; case 0: return HASLENGTH_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public HasLengthCase getHasLengthCase() { return HasLengthCase.forNumber( hasLengthCase_); } public static final int START_FIELD_NUMBER = 1; private long start_; /** * <pre> * Start index of the slice, starting at 0. * </pre> * * <code>optional int64 start = 1;</code> */ public long getStart() { return start_; } public static final int LENGTH_FIELD_NUMBER = 2; /** * <code>optional int64 length = 2;</code> */ public long getLength() { if (hasLengthCase_ == 2) { return (java.lang.Long) hasLength_; } return 0L; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (start_ != 0L) { output.writeInt64(1, start_); } if (hasLengthCase_ == 2) { output.writeInt64( 2, (long)((java.lang.Long) hasLength_)); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (start_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, start_); } if (hasLengthCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeInt64Size( 2, (long)((java.lang.Long) hasLength_)); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.tensorflow.framework.TensorSliceProto.Extent)) { return super.equals(obj); } org.tensorflow.framework.TensorSliceProto.Extent other = (org.tensorflow.framework.TensorSliceProto.Extent) obj; boolean result = true; result = result && (getStart() == other.getStart()); result = result && getHasLengthCase().equals( other.getHasLengthCase()); if (!result) return false; switch (hasLengthCase_) { case 2: result = result && (getLength() == other.getLength()); break; case 0: default: } return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); hash = (37 * hash) + START_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getStart()); switch (hasLengthCase_) { case 2: hash = (37 * hash) + LENGTH_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLength()); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto.Extent parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto.Extent parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto.Extent parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.tensorflow.framework.TensorSliceProto.Extent prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Extent of the slice in one dimension. * </pre> * * Protobuf type {@code tensorflow.TensorSliceProto.Extent} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tensorflow.TensorSliceProto.Extent) org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_Extent_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_Extent_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.framework.TensorSliceProto.Extent.class, org.tensorflow.framework.TensorSliceProto.Extent.Builder.class); } // Construct using org.tensorflow.framework.TensorSliceProto.Extent.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); start_ = 0L; hasLengthCase_ = 0; hasLength_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_Extent_descriptor; } public org.tensorflow.framework.TensorSliceProto.Extent getDefaultInstanceForType() { return org.tensorflow.framework.TensorSliceProto.Extent.getDefaultInstance(); } public org.tensorflow.framework.TensorSliceProto.Extent build() { org.tensorflow.framework.TensorSliceProto.Extent result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.tensorflow.framework.TensorSliceProto.Extent buildPartial() { org.tensorflow.framework.TensorSliceProto.Extent result = new org.tensorflow.framework.TensorSliceProto.Extent(this); result.start_ = start_; if (hasLengthCase_ == 2) { result.hasLength_ = hasLength_; } result.hasLengthCase_ = hasLengthCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.tensorflow.framework.TensorSliceProto.Extent) { return mergeFrom((org.tensorflow.framework.TensorSliceProto.Extent)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.tensorflow.framework.TensorSliceProto.Extent other) { if (other == org.tensorflow.framework.TensorSliceProto.Extent.getDefaultInstance()) return this; if (other.getStart() != 0L) { setStart(other.getStart()); } switch (other.getHasLengthCase()) { case LENGTH: { setLength(other.getLength()); break; } case HASLENGTH_NOT_SET: { break; } } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.tensorflow.framework.TensorSliceProto.Extent parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.tensorflow.framework.TensorSliceProto.Extent) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int hasLengthCase_ = 0; private java.lang.Object hasLength_; public HasLengthCase getHasLengthCase() { return HasLengthCase.forNumber( hasLengthCase_); } public Builder clearHasLength() { hasLengthCase_ = 0; hasLength_ = null; onChanged(); return this; } private long start_ ; /** * <pre> * Start index of the slice, starting at 0. * </pre> * * <code>optional int64 start = 1;</code> */ public long getStart() { return start_; } /** * <pre> * Start index of the slice, starting at 0. * </pre> * * <code>optional int64 start = 1;</code> */ public Builder setStart(long value) { start_ = value; onChanged(); return this; } /** * <pre> * Start index of the slice, starting at 0. * </pre> * * <code>optional int64 start = 1;</code> */ public Builder clearStart() { start_ = 0L; onChanged(); return this; } /** * <code>optional int64 length = 2;</code> */ public long getLength() { if (hasLengthCase_ == 2) { return (java.lang.Long) hasLength_; } return 0L; } /** * <code>optional int64 length = 2;</code> */ public Builder setLength(long value) { hasLengthCase_ = 2; hasLength_ = value; onChanged(); return this; } /** * <code>optional int64 length = 2;</code> */ public Builder clearLength() { if (hasLengthCase_ == 2) { hasLengthCase_ = 0; hasLength_ = null; onChanged(); } return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:tensorflow.TensorSliceProto.Extent) } // @@protoc_insertion_point(class_scope:tensorflow.TensorSliceProto.Extent) private static final org.tensorflow.framework.TensorSliceProto.Extent DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.tensorflow.framework.TensorSliceProto.Extent(); } public static org.tensorflow.framework.TensorSliceProto.Extent getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Extent> PARSER = new com.google.protobuf.AbstractParser<Extent>() { public Extent parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Extent(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Extent> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Extent> getParserForType() { return PARSER; } public org.tensorflow.framework.TensorSliceProto.Extent getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public static final int EXTENT_FIELD_NUMBER = 1; private java.util.List<org.tensorflow.framework.TensorSliceProto.Extent> extent_; /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public java.util.List<org.tensorflow.framework.TensorSliceProto.Extent> getExtentList() { return extent_; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public java.util.List<? extends org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder> getExtentOrBuilderList() { return extent_; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public int getExtentCount() { return extent_.size(); } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.Extent getExtent(int index) { return extent_.get(index); } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder getExtentOrBuilder( int index) { return extent_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < extent_.size(); i++) { output.writeMessage(1, extent_.get(i)); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < extent_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, extent_.get(i)); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.tensorflow.framework.TensorSliceProto)) { return super.equals(obj); } org.tensorflow.framework.TensorSliceProto other = (org.tensorflow.framework.TensorSliceProto) obj; boolean result = true; result = result && getExtentList() .equals(other.getExtentList()); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (getExtentCount() > 0) { hash = (37 * hash) + EXTENT_FIELD_NUMBER; hash = (53 * hash) + getExtentList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.tensorflow.framework.TensorSliceProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.framework.TensorSliceProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.framework.TensorSliceProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.framework.TensorSliceProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.framework.TensorSliceProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.tensorflow.framework.TensorSliceProto prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Can only be interpreted if you know the corresponding TensorShape. * </pre> * * Protobuf type {@code tensorflow.TensorSliceProto} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tensorflow.TensorSliceProto) org.tensorflow.framework.TensorSliceProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.framework.TensorSliceProto.class, org.tensorflow.framework.TensorSliceProto.Builder.class); } // Construct using org.tensorflow.framework.TensorSliceProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getExtentFieldBuilder(); } } public Builder clear() { super.clear(); if (extentBuilder_ == null) { extent_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { extentBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.tensorflow.framework.TensorSliceProtos.internal_static_tensorflow_TensorSliceProto_descriptor; } public org.tensorflow.framework.TensorSliceProto getDefaultInstanceForType() { return org.tensorflow.framework.TensorSliceProto.getDefaultInstance(); } public org.tensorflow.framework.TensorSliceProto build() { org.tensorflow.framework.TensorSliceProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.tensorflow.framework.TensorSliceProto buildPartial() { org.tensorflow.framework.TensorSliceProto result = new org.tensorflow.framework.TensorSliceProto(this); int from_bitField0_ = bitField0_; if (extentBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { extent_ = java.util.Collections.unmodifiableList(extent_); bitField0_ = (bitField0_ & ~0x00000001); } result.extent_ = extent_; } else { result.extent_ = extentBuilder_.build(); } onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.tensorflow.framework.TensorSliceProto) { return mergeFrom((org.tensorflow.framework.TensorSliceProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.tensorflow.framework.TensorSliceProto other) { if (other == org.tensorflow.framework.TensorSliceProto.getDefaultInstance()) return this; if (extentBuilder_ == null) { if (!other.extent_.isEmpty()) { if (extent_.isEmpty()) { extent_ = other.extent_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureExtentIsMutable(); extent_.addAll(other.extent_); } onChanged(); } } else { if (!other.extent_.isEmpty()) { if (extentBuilder_.isEmpty()) { extentBuilder_.dispose(); extentBuilder_ = null; extent_ = other.extent_; bitField0_ = (bitField0_ & ~0x00000001); extentBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getExtentFieldBuilder() : null; } else { extentBuilder_.addAllMessages(other.extent_); } } } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.tensorflow.framework.TensorSliceProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.tensorflow.framework.TensorSliceProto) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<org.tensorflow.framework.TensorSliceProto.Extent> extent_ = java.util.Collections.emptyList(); private void ensureExtentIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { extent_ = new java.util.ArrayList<org.tensorflow.framework.TensorSliceProto.Extent>(extent_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.framework.TensorSliceProto.Extent, org.tensorflow.framework.TensorSliceProto.Extent.Builder, org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder> extentBuilder_; /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public java.util.List<org.tensorflow.framework.TensorSliceProto.Extent> getExtentList() { if (extentBuilder_ == null) { return java.util.Collections.unmodifiableList(extent_); } else { return extentBuilder_.getMessageList(); } } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public int getExtentCount() { if (extentBuilder_ == null) { return extent_.size(); } else { return extentBuilder_.getCount(); } } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.Extent getExtent(int index) { if (extentBuilder_ == null) { return extent_.get(index); } else { return extentBuilder_.getMessage(index); } } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder setExtent( int index, org.tensorflow.framework.TensorSliceProto.Extent value) { if (extentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtentIsMutable(); extent_.set(index, value); onChanged(); } else { extentBuilder_.setMessage(index, value); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder setExtent( int index, org.tensorflow.framework.TensorSliceProto.Extent.Builder builderForValue) { if (extentBuilder_ == null) { ensureExtentIsMutable(); extent_.set(index, builderForValue.build()); onChanged(); } else { extentBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder addExtent(org.tensorflow.framework.TensorSliceProto.Extent value) { if (extentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtentIsMutable(); extent_.add(value); onChanged(); } else { extentBuilder_.addMessage(value); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder addExtent( int index, org.tensorflow.framework.TensorSliceProto.Extent value) { if (extentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtentIsMutable(); extent_.add(index, value); onChanged(); } else { extentBuilder_.addMessage(index, value); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder addExtent( org.tensorflow.framework.TensorSliceProto.Extent.Builder builderForValue) { if (extentBuilder_ == null) { ensureExtentIsMutable(); extent_.add(builderForValue.build()); onChanged(); } else { extentBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder addExtent( int index, org.tensorflow.framework.TensorSliceProto.Extent.Builder builderForValue) { if (extentBuilder_ == null) { ensureExtentIsMutable(); extent_.add(index, builderForValue.build()); onChanged(); } else { extentBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder addAllExtent( java.lang.Iterable<? extends org.tensorflow.framework.TensorSliceProto.Extent> values) { if (extentBuilder_ == null) { ensureExtentIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, extent_); onChanged(); } else { extentBuilder_.addAllMessages(values); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder clearExtent() { if (extentBuilder_ == null) { extent_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { extentBuilder_.clear(); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public Builder removeExtent(int index) { if (extentBuilder_ == null) { ensureExtentIsMutable(); extent_.remove(index); onChanged(); } else { extentBuilder_.remove(index); } return this; } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.Extent.Builder getExtentBuilder( int index) { return getExtentFieldBuilder().getBuilder(index); } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder getExtentOrBuilder( int index) { if (extentBuilder_ == null) { return extent_.get(index); } else { return extentBuilder_.getMessageOrBuilder(index); } } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public java.util.List<? extends org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder> getExtentOrBuilderList() { if (extentBuilder_ != null) { return extentBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(extent_); } } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.Extent.Builder addExtentBuilder() { return getExtentFieldBuilder().addBuilder( org.tensorflow.framework.TensorSliceProto.Extent.getDefaultInstance()); } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public org.tensorflow.framework.TensorSliceProto.Extent.Builder addExtentBuilder( int index) { return getExtentFieldBuilder().addBuilder( index, org.tensorflow.framework.TensorSliceProto.Extent.getDefaultInstance()); } /** * <pre> * Extent of the slice in all tensor dimensions. * Must have one entry for each of the dimension of the tensor that this * slice belongs to. The order of sizes is the same as the order of * dimensions in the TensorShape. * </pre> * * <code>repeated .tensorflow.TensorSliceProto.Extent extent = 1;</code> */ public java.util.List<org.tensorflow.framework.TensorSliceProto.Extent.Builder> getExtentBuilderList() { return getExtentFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.framework.TensorSliceProto.Extent, org.tensorflow.framework.TensorSliceProto.Extent.Builder, org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder> getExtentFieldBuilder() { if (extentBuilder_ == null) { extentBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.framework.TensorSliceProto.Extent, org.tensorflow.framework.TensorSliceProto.Extent.Builder, org.tensorflow.framework.TensorSliceProto.ExtentOrBuilder>( extent_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); extent_ = null; } return extentBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:tensorflow.TensorSliceProto) } // @@protoc_insertion_point(class_scope:tensorflow.TensorSliceProto) private static final org.tensorflow.framework.TensorSliceProto DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.tensorflow.framework.TensorSliceProto(); } public static org.tensorflow.framework.TensorSliceProto getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TensorSliceProto> PARSER = new com.google.protobuf.AbstractParser<TensorSliceProto>() { public TensorSliceProto parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TensorSliceProto(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TensorSliceProto> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TensorSliceProto> getParserForType() { return PARSER; } public org.tensorflow.framework.TensorSliceProto getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
34.547043
190
0.656538
d0312d9fdb9e60399f5c9cf33e78a77b2a8e76a7
419
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.plugin.ij.formatting; import com.intellij.codeInsight.editorActions.SimpleTokenSetQuoteHandler; import com.intellij.psi.JavaTokenType; import com.intellij.psi.tree.IElementType; public class GosuQuoteHandler extends SimpleTokenSetQuoteHandler { public GosuQuoteHandler() { super(JavaTokenType.STRING_LITERAL, JavaTokenType.CHARACTER_LITERAL); } }
26.1875
73
0.811456
eb9fdd3283bb8c380f99ebd3776fd1dc734a8ecb
13,860
package jetbrains.mps.debugger.java.runtime.engine; /*Generated by MPS */ import jetbrains.mps.annotations.GeneratedClass; import jetbrains.mps.debugger.java.runtime.engine.requests.IRequestManager; import jetbrains.mps.logging.Logger; import org.apache.log4j.LogManager; import java.util.Map; import jetbrains.mps.debugger.java.runtime.engine.requests.Requestor; import java.util.Set; import com.sun.jdi.request.EventRequest; import com.intellij.util.containers.HashMap; import com.sun.jdi.request.EventRequestManager; import jetbrains.mps.debugger.java.runtime.engine.events.EventsProcessor; import java.util.List; import jetbrains.mps.baseLanguage.closures.runtime._FunctionTypes; import jetbrains.mps.internal.collections.runtime.ListSequence; import java.util.ArrayList; import org.jetbrains.annotations.Nullable; import jetbrains.mps.debugger.java.runtime.engine.concurrent.ManagerThread; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashSet; import com.sun.jdi.request.InvalidRequestStateException; import com.sun.jdi.InternalException; import com.sun.jdi.request.BreakpointRequest; import jetbrains.mps.debugger.java.runtime.breakpoints.JavaBreakpoint; import com.sun.jdi.Location; import com.sun.jdi.request.MethodEntryRequest; import com.sun.jdi.ReferenceType; import com.sun.jdi.request.MethodExitRequest; import com.sun.jdi.request.AccessWatchpointRequest; import com.sun.jdi.Field; import com.sun.jdi.request.ModificationWatchpointRequest; import com.sun.jdi.request.ExceptionRequest; import com.sun.jdi.request.StepRequest; import com.sun.jdi.ThreadReference; import jetbrains.mps.debugger.java.runtime.engine.requests.StepRequestor; import jetbrains.mps.debugger.java.runtime.engine.requests.ClassPrepareRequestor; import com.sun.jdi.request.ClassPrepareRequest; import jetbrains.mps.internal.collections.runtime.IVisitor; import com.sun.jdi.event.ClassPrepareEvent; import com.sun.jdi.ClassType; import com.sun.jdi.InterfaceType; import jetbrains.mps.debug.api.BreakpointManagerComponent; import jetbrains.mps.debug.api.breakpoints.IBreakpoint; @GeneratedClass(node = "r:0b933946-5ee4-42ea-9b69-bd1790a8e611(jetbrains.mps.debugger.java.runtime.engine)/8961922059449033006", model = "r:0b933946-5ee4-42ea-9b69-bd1790a8e611(jetbrains.mps.debugger.java.runtime.engine)") public class RequestManager implements IRequestManager { private static final Logger LOG = Logger.wrap(LogManager.getLogger(RequestManager.class)); private static final Object REQUESTOR = new Object(); private static final Object CLASS_NAME = new Object(); private final Map<Requestor, Set<EventRequest>> myRequestorToBelongedRequests = new HashMap<Requestor, Set<EventRequest>>(); private EventRequestManager myEventRequestManager; private EventsProcessor myDebugEventsProcessor; private final MyDebugProcessListener myDebugProcessListener = new MyDebugProcessListener(); private final Map<Requestor, String> myInvalidRequestsAndWarnings = new HashMap<Requestor, String>(); private final List<_FunctionTypes._void_P0_E0> myWarningsListeners = ListSequence.fromList(new ArrayList<_FunctionTypes._void_P0_E0>()); public RequestManager(EventsProcessor processor) { myDebugEventsProcessor = processor; myDebugEventsProcessor.addDebugProcessListener(myDebugProcessListener); } public EventRequestManager getVMRequestManager() { return myEventRequestManager; } @Nullable public Requestor findRequestor(EventRequest request) { ManagerThread.assertIsMangerThread(); return (request != null ? (Requestor) request.getProperty(REQUESTOR) : null); } @NotNull public Set<EventRequest> findRequests(Requestor requestor) { ManagerThread.assertIsMangerThread(); if (!(myRequestorToBelongedRequests.containsKey(requestor))) { return Collections.emptySet(); } return new HashSet<EventRequest>(myRequestorToBelongedRequests.get(requestor)); } private void registerRequestInternal(final Requestor requestor, final EventRequest request) { registerRequest(requestor, request); request.putProperty(REQUESTOR, requestor); } private void registerRequest(Requestor requestor, EventRequest request) { Set<EventRequest> reqSet = myRequestorToBelongedRequests.get(requestor); if (reqSet == null) { reqSet = new HashSet<EventRequest>(); myRequestorToBelongedRequests.put(requestor, reqSet); } reqSet.add(request); } public void deleteRequests(Requestor requestor) { ManagerThread.assertIsMangerThread(); if (!(myDebugEventsProcessor.isAttached())) { return; } final Set<EventRequest> requests = myRequestorToBelongedRequests.remove(requestor); if (requests == null) { return; } for (final EventRequest request : requests) { try { final Requestor targetRequestor = (Requestor) request.getProperty(REQUESTOR); if (targetRequestor != requestor) { // the same request may be assigned to more than one requestor, but // there is only one 'targetRequestor' for each request, so if target requestor and requestor being processed are different, // should clear also the mapping targetRequestor->request final Set<EventRequest> allTargetRequestorRequests = myRequestorToBelongedRequests.get(targetRequestor); if (allTargetRequestorRequests != null) { allTargetRequestorRequests.remove(request); if (allTargetRequestorRequests.size() == 0) { myRequestorToBelongedRequests.remove(targetRequestor); } } } myEventRequestManager.deleteEventRequest(request); } catch (InvalidRequestStateException ignored) { // request is already deleted } catch (InternalException e) { LOG.error(e); } } } public BreakpointRequest createBreakpointRequest(JavaBreakpoint requestor, Location location) { // ------------------- requests creation ManagerThread.assertIsMangerThread(); BreakpointRequest request = myEventRequestManager.createBreakpointRequest(location); initRequest(requestor, request); return request; } public MethodEntryRequest createMethodEntryRequest(JavaBreakpoint requestor, ReferenceType type) { ManagerThread.assertIsMangerThread(); MethodEntryRequest request = myEventRequestManager.createMethodEntryRequest(); request.addClassFilter(type); initRequest(requestor, request); return request; } public MethodExitRequest createMethodExitRequest(JavaBreakpoint requestor, ReferenceType type) { ManagerThread.assertIsMangerThread(); MethodExitRequest request = myEventRequestManager.createMethodExitRequest(); request.addClassFilter(type); initRequest(requestor, request); return request; } public AccessWatchpointRequest createFieldAccessRequest(JavaBreakpoint requestor, Field field) { ManagerThread.assertIsMangerThread(); AccessWatchpointRequest request = myEventRequestManager.createAccessWatchpointRequest(field); initRequest(requestor, request); return request; } public ModificationWatchpointRequest createFieldModificationRequest(JavaBreakpoint requestor, Field field) { ManagerThread.assertIsMangerThread(); ModificationWatchpointRequest request = myEventRequestManager.createModificationWatchpointRequest(field); initRequest(requestor, request); return request; } public ExceptionRequest createExceptionRequest(JavaBreakpoint requestor, ReferenceType reference) { ManagerThread.assertIsMangerThread(); ExceptionRequest request = myEventRequestManager.createExceptionRequest(reference, true, true); initRequest(requestor, request); return request; } private void initRequest(JavaBreakpoint requestor, EventRequest req) { int suspendPolicy = requestor.getSuspendPolicy(); if (suspendPolicy == EventRequest.SUSPEND_NONE) { suspendPolicy = EventRequest.SUSPEND_ALL; } // we suspend all, do smth and then resume req.setSuspendPolicy(suspendPolicy); registerRequestInternal(requestor, req); } public void deleteStepRequests() { ManagerThread.assertIsMangerThread(); // todo what are these step requests to delete? List<StepRequest> stepRequests = myEventRequestManager.stepRequests(); if (stepRequests.size() > 0) { List<StepRequest> toDelete = new ArrayList<StepRequest>(stepRequests.size()); for (StepRequest request : stepRequests) { ThreadReference threadReference = request.thread(); // on attempt to delete a request assigned to a thread with unknown status, a JDWP error occures if (threadReference.status() != ThreadReference.THREAD_STATUS_UNKNOWN) { toDelete.add(request); } } // removing from requestor maps for (StepRequest stepRequest : toDelete) { Requestor requestor = findRequestor(stepRequest); if (requestor != null) { Set<EventRequest> requestSet = myRequestorToBelongedRequests.get(requestor); requestSet.remove(stepRequest); if (requestSet.isEmpty()) { myRequestorToBelongedRequests.remove(requestor); } } } myEventRequestManager.deleteEventRequests(toDelete); } } public StepRequest createStepRequest(StepRequestor requestor, int stepType, ThreadReference stepThread, int suspendPolicy) { deleteStepRequests(); StepRequest stepRequest = myEventRequestManager.createStepRequest(stepThread, StepRequest.STEP_LINE, stepType); stepRequest.setSuspendPolicy(suspendPolicy); registerRequestInternal(requestor, stepRequest); return stepRequest; } public void callbackOnPrepareClasses(ClassPrepareRequestor requestor, String classOrPatternToBeLoaded) { // todo: some other types of requests; later // ------------------- ~requests creation // by classname ManagerThread.assertIsMangerThread(); ClassPrepareRequest classPrepareRequest = createClassPrepareRequest(requestor, classOrPatternToBeLoaded); classPrepareRequest.enable(); } private ClassPrepareRequest createClassPrepareRequest(ClassPrepareRequestor requestor, String className) { ClassPrepareRequest classPrepareRequest = myEventRequestManager.createClassPrepareRequest(); classPrepareRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); classPrepareRequest.addClassFilter(className); classPrepareRequest.putProperty(CLASS_NAME, className); registerRequestInternal(requestor, classPrepareRequest); return classPrepareRequest; } public void enableRequest(EventRequest request) { // currently does no much more than request.enable() ManagerThread.assertIsMangerThread(); LOG.assertLog(findRequestor(request) != null, "Assertion failed."); request.enable(); } public void setInvalid(Requestor requestor, String message) { ManagerThread.assertIsMangerThread(); myInvalidRequestsAndWarnings.put(requestor, message); ListSequence.fromList(myWarningsListeners).visitAll(new IVisitor<_FunctionTypes._void_P0_E0>() { public void visit(_FunctionTypes._void_P0_E0 it) { it.invoke(); } }); } @Nullable public String getWarning(Requestor requestor) { ManagerThread.assertIsMangerThread(); return myInvalidRequestsAndWarnings.get(requestor); } public void addWarningsListener(_FunctionTypes._void_P0_E0 listener) { ListSequence.fromList(myWarningsListeners).addElement(listener); } public void removeWarningsListener(_FunctionTypes._void_P0_E0 listener) { ListSequence.fromList(myWarningsListeners).removeElement(listener); } public void processClassPrepared(final ClassPrepareEvent event) { if (!(myDebugEventsProcessor.isAttached())) { return; } final ReferenceType refType = event.referenceType(); if (refType instanceof ClassType || refType instanceof InterfaceType) { ClassPrepareRequestor requestor = (ClassPrepareRequestor) event.request().getProperty(REQUESTOR); if (requestor != null) { requestor.processClassPrepare(myDebugEventsProcessor, refType); } } } public static void createClassPrepareRequests(final JavaBreakpoint breakpoint) { VMEventsProcessorManagerComponent.getInstance(breakpoint.getProject()).performAllDebugProcessesAction((EventsProcessor processor) -> { if (processor.isAttached()) { breakpoint.createClassPrepareRequest(processor); } }); } public static void removeClassPrepareRequests(final JavaBreakpoint breakpoint) { VMEventsProcessorManagerComponent.getInstance(breakpoint.getProject()).performAllDebugProcessesAction((EventsProcessor processor) -> { if (processor.isAttached()) { processor.getRequestManager().deleteRequests(breakpoint); } }); } public class MyDebugProcessListener extends DebugProcessAdapter { public MyDebugProcessListener() { } @Override public void processDetached(@NotNull EventsProcessor process, boolean closedByUser) { myEventRequestManager = null; myRequestorToBelongedRequests.clear(); } @Override public void processAttached(@NotNull EventsProcessor process) { myEventRequestManager = myDebugEventsProcessor.getVirtualMachine().eventRequestManager(); // invoke later, so that requests are for sure created only _after_ 'processAttached()' methods of other listeneres are executed process.schedule(() -> { BreakpointManagerComponent breakpointManager = myDebugEventsProcessor.getBreakpointManager(); for (IBreakpoint breakpoint : breakpointManager.getAllIBreakpoints()) { if (breakpoint instanceof JavaBreakpoint) { ((JavaBreakpoint) breakpoint).createClassPrepareRequest(myDebugEventsProcessor); } } }); } } }
46.666667
222
0.763781
883cedd91e318907ba7c87f70c6cb1d3fc64f17c
16,957
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import junit.framework.TestCase; /** * @author Glen Stampoultzis (glens at apache.org) * @author Marc Johnson (mjohnson at apache dot org) */ public final class TestHexDump extends TestCase { private static char toHex(int n) { return Character.toUpperCase(Character.forDigit(n & 0x0F, 16)); } public void testDump() throws IOException { byte[] testArray = new byte[ 256 ]; for (int j = 0; j < 256; j++) { testArray[ j ] = ( byte ) j; } ByteArrayOutputStream stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0, stream, 0); byte[] outputArray = new byte[ 16 * (73 + HexDump.EOL.length()) ]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) ' '; for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) toHex(k); outputArray[ offset++ ] = ( byte ) ' '; } for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } byte[] actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[ j ], actualOutput[ j ]); } // verify proper behavior with non-zero offset stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0x10000000, stream, 0); outputArray = new byte[ 16 * (73 + HexDump.EOL.length()) ]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[ offset++ ] = ( byte ) '1'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) ' '; for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) toHex(k); outputArray[ offset++ ] = ( byte ) ' '; } for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[ j ], actualOutput[ j ]); } // verify proper behavior with negative offset stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0xFF000000, stream, 0); outputArray = new byte[ 16 * (73 + HexDump.EOL.length()) ]; for (int j = 0; j < 16; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[ offset++ ] = ( byte ) 'F'; outputArray[ offset++ ] = ( byte ) 'F'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) ' '; for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toHex(j); outputArray[ offset++ ] = ( byte ) toHex(k); outputArray[ offset++ ] = ( byte ) ' '; } for (int k = 0; k < 16; k++) { outputArray[ offset++ ] = ( byte ) toAscii((j * 16) + k); } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[ j ], actualOutput[ j ]); } // verify proper behavior with non-zero index stream = new ByteArrayOutputStream(); HexDump.dump(testArray, 0x10000000, stream, 0x81); outputArray = new byte[ (8 * (73 + HexDump.EOL.length())) - 1 ]; for (int j = 0; j < 8; j++) { int offset = (73 + HexDump.EOL.length()) * j; outputArray[ offset++ ] = ( byte ) '1'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) '0'; outputArray[ offset++ ] = ( byte ) toHex(j + 8); outputArray[ offset++ ] = ( byte ) '1'; outputArray[ offset++ ] = ( byte ) ' '; for (int k = 0; k < 16; k++) { int index = 0x81 + (j * 16) + k; if (index < 0x100) { outputArray[ offset++ ] = ( byte ) toHex(index / 16); outputArray[ offset++ ] = ( byte ) toHex(index); } else { outputArray[ offset++ ] = ( byte ) ' '; outputArray[ offset++ ] = ( byte ) ' '; } outputArray[ offset++ ] = ( byte ) ' '; } for (int k = 0; k < 16; k++) { int index = 0x81 + (j * 16) + k; if (index < 0x100) { outputArray[ offset++ ] = ( byte ) toAscii(index); } } System.arraycopy(HexDump.EOL.getBytes(), 0, outputArray, offset, HexDump.EOL.getBytes().length); } actualOutput = stream.toByteArray(); assertEquals("array size mismatch", outputArray.length, actualOutput.length); for (int j = 0; j < outputArray.length; j++) { assertEquals("array[ " + j + "] mismatch", outputArray[ j ], actualOutput[ j ]); } // verify proper behavior with negative index try { HexDump.dump(testArray, 0x10000000, new ByteArrayOutputStream(), -1); fail("should have caught ArrayIndexOutOfBoundsException on negative index"); } catch (ArrayIndexOutOfBoundsException ignored_exception) { // as expected } // verify proper behavior with index that is too large try { HexDump.dump(testArray, 0x10000000, new ByteArrayOutputStream(), testArray.length); fail("should have caught ArrayIndexOutOfBoundsException on large index"); } catch (ArrayIndexOutOfBoundsException ignored_exception) { // as expected } // verify proper behavior with null stream try { HexDump.dump(testArray, 0x10000000, null, 0); fail("should have caught IllegalArgumentException on negative index"); } catch (IllegalArgumentException ignored_exception) { // as expected } // verify proper behaviour with empty byte array ByteArrayOutputStream os = new ByteArrayOutputStream( ); HexDump.dump( new byte[0], 0, os, 0 ); assertEquals( "No Data" + System.getProperty( "line.separator"), os.toString() ); } public void testToHex() { assertEquals("000A", HexDump.toHex((short)0xA)); assertEquals("[]", HexDump.toHex(new short[] { })); assertEquals("[000A]", HexDump.toHex(new short[] { 0xA })); assertEquals("[000A, 000B]", HexDump.toHex(new short[] { 0xA, 0xB })); assertEquals("0A", HexDump.toHex((byte)0xA)); assertEquals("0000000A", HexDump.toHex(0xA)); assertEquals("[]", HexDump.toHex(new byte[] { })); assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA })); assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB })); assertEquals(": 0", HexDump.toHex(new byte[] { }, 10)); assertEquals("0: 0A", HexDump.toHex(new byte[] { 0xA }, 10)); assertEquals("0: 0A, 0B", HexDump.toHex(new byte[] { 0xA, 0xB }, 10)); assertEquals("0: 0A, 0B\n2: 0C, 0D", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD }, 2)); assertEquals("0: 0A, 0B\n2: 0C, 0D\n4: 0E, 0F", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }, 2)); assertEquals("FFFF", HexDump.toHex((short)0xFFFF)); assertEquals("00000000000004D2", HexDump.toHex(1234l)); confirmStr("0xFE", HexDump.byteToHex(-2)); confirmStr("0x25", HexDump.byteToHex(37)); confirmStr("0xFFFE", HexDump.shortToHex(-2)); confirmStr("0x0005", HexDump.shortToHex(5)); confirmStr("0xFFFFFF9C", HexDump.intToHex(-100)); confirmStr("0x00001001", HexDump.intToHex(4097)); confirmStr("0xFFFFFFFFFFFF0006", HexDump.longToHex(-65530)); confirmStr("0x0000000000003FCD", HexDump.longToHex(16333)); } private static void confirmStr(String expected, char[] actualChars) { assertEquals(expected, new String(actualChars)); } private static char toAscii(int c) { char rval = '.'; if (c >= 32 && c <= 126) { rval = ( char ) c; } return rval; } public void testDumpToString() throws Exception { byte[] testArray = new byte[ 256 ]; for (int j = 0; j < 256; j++) { testArray[ j ] = ( byte ) j; } String dump = HexDump.dump(testArray, 0, 0); //System.out.println("Hex: \n" + dump); assertTrue("Had: \n" + dump, dump.contains("0123456789:;<=>?")); dump = HexDump.dump(testArray, 2, 1); //System.out.println("Hex: \n" + dump); assertTrue("Had: \n" + dump, dump.contains("123456789:;<=>?@")); } public void testDumpToStringOutOfIndex() throws Exception { byte[] testArray = new byte[ 0 ]; try { HexDump.dump(testArray, 0, -1); fail("Should throw an exception with invalid input"); } catch (ArrayIndexOutOfBoundsException e) { // expected } try { HexDump.dump(testArray, 0, 1); fail("Should throw an exception with invalid input"); } catch (ArrayIndexOutOfBoundsException e) { // expected } } public void testDumpToPrintStream() throws IOException { byte[] testArray = new byte[ 256 ]; for (int j = 0; j < 256; j++) { testArray[ j ] = ( byte ) j; } InputStream in = new ByteArrayInputStream(testArray); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteOut); try { HexDump.dump(in, out, 0, 256); } finally { out.close(); } String str = new String(byteOut.toByteArray()); assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); } finally { in.close(); } in = new ByteArrayInputStream(testArray); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteOut); try { // test with more than we have HexDump.dump(in, out, 0, 1000); } finally { out.close(); } String str = new String(byteOut.toByteArray()); assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); } finally { in.close(); } in = new ByteArrayInputStream(testArray); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteOut); try { // test with -1 HexDump.dump(in, out, 0, -1); } finally { out.close(); } String str = new String(byteOut.toByteArray()); assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); } finally { in.close(); } in = new ByteArrayInputStream(testArray); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteOut); try { HexDump.dump(in, out, 1, 235); } finally { out.close(); } String str = new String(byteOut.toByteArray()); assertTrue("Line contents should be moved by one now, but Had: \n" + str, str.contains("123456789:;<=>?@")); } finally { in.close(); } } public void testConstruct() throws Exception { // to cover private constructor // get the default constructor final Constructor<HexDump> c = HexDump.class.getDeclaredConstructor(new Class[] {}); // make it callable from the outside c.setAccessible(true); // call it assertNotNull(c.newInstance((Object[]) null)); } public void testMain() throws Exception { File file = TempFile.createTempFile("HexDump", ".dat"); try { FileOutputStream out = new FileOutputStream(file); try { IOUtils.copy(new ByteArrayInputStream("teststring".getBytes()), out); } finally { out.close(); } assertTrue(file.exists()); assertTrue(file.length() > 0); HexDump.main(new String[] { file.getAbsolutePath() }); } finally { assertTrue(file.exists() && file.delete()); } } }
37.024017
119
0.503509
74357c9c6946e4198e775e8053f40e5f5ab3c080
2,638
/* * Copyright (c) 2017 Snow Volf (Artem Zhiganov). * 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 ru.SnowVolf.translate.ui.widget; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import static android.R.attr.enabled; /** * Created by kosh20111 on 10/8/2015. * <p/> * Viewpager that has scrolling animation by default */ public class ViewPagerView extends ViewPager { private boolean isEnabled; public ViewPagerView(Context context) { super(context); } public ViewPagerView(@NonNull Context context, AttributeSet attrs) { super(context, attrs); int[] attrsArray = {enabled}; TypedArray array = context.obtainStyledAttributes(attrs, attrsArray); isEnabled = array.getBoolean(0, true); array.recycle(); } @Override public boolean isEnabled() { return isEnabled; } @Override public void setEnabled(boolean enabled) { this.isEnabled = enabled; requestLayout(); } @Override public void setAdapter(@Nullable PagerAdapter adapter) { super.setAdapter(adapter); if (isInEditMode()) return; if (adapter != null) { setOffscreenPageLimit(adapter.getCount()); } } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { try { return !isEnabled() || super.onTouchEvent(event); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { try { return isEnabled() && super.onInterceptTouchEvent(event); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return false; } }
29.977273
106
0.684989
1c9eeb105cb11933a600de72afec829bc6fee74f
2,477
/* * Copyright 2013-2022 Erudika. https://erudika.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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.server.persistence; import org.apache.commons.lang3.StringUtils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; /** * Perform an integration test of the generic SQL DAO using a specific mode. * @author Jeremy Wiesner [jswiesner@gmail.com] */ @Ignore public abstract class SqlDAOIT extends DAOTest { private static final String ROOT_APP_NAME = "para-test"; public SqlDAOIT(String mode) { super(new SqlDAO()); org.h2.Driver.load(); System.setProperty("para.sql.driver", "org.h2.Driver"); System.setProperty("para.sql.url", "h2:mem:test" + (StringUtils.isBlank(mode) ? "" : ";MODE=" + mode)); System.setProperty("para.sql.user", "user"); System.setProperty("para.sql.password", "password"); initialize(); } private void initialize() { SqlUtils.createTable(ROOT_APP_NAME); SqlUtils.createTable(appid1); SqlUtils.createTable(appid2); SqlUtils.createTable(appid3); } @AfterClass public static void destroy() { SqlUtils.deleteTable(ROOT_APP_NAME); SqlUtils.deleteTable(appid1); SqlUtils.deleteTable(appid2); SqlUtils.deleteTable(appid3); SqlUtils.shutdownClient(); } @Test public void testCreateDeleteExistsTable() throws InterruptedException { String testappid1 = "test-index"; String badAppid = "test index 123"; SqlUtils.createTable(""); assertFalse(SqlUtils.existsTable("")); SqlUtils.createTable(testappid1); assertTrue(SqlUtils.existsTable(testappid1)); SqlUtils.deleteTable(testappid1); assertFalse(SqlUtils.existsTable(testappid1)); assertFalse(SqlUtils.createTable(badAppid)); assertFalse(SqlUtils.existsTable(badAppid)); assertFalse(SqlUtils.deleteTable(badAppid)); } }
29.843373
105
0.746064
37fb1d9b7ca268d0dbadedfd23786e031d0e54cf
10,853
package home.shared.Utilities; import com.thoughtworks.xstream.XStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.cert.X509Certificate; import java.util.ArrayList; public class ParseToken extends Object { String str; int err; int from_index; boolean _is_ordered; public boolean is_ordered() { return _is_ordered; } public void set_ordered( boolean f ) { _is_ordered = f; } public ParseToken() { } public ParseToken( String _str) { from_index = 0; err = 0; str = _str; } public String GetString(String token) { err = 0; boolean found_escaped_chars = false; int pos = str.indexOf( token, from_index ); if ((pos >= 0) && ((pos + token.length()) < str.length())) { pos += token.length(); char delim = str.charAt( pos ); int end = pos; if (delim == '\'' || delim == '\"') { pos++; end = pos; // FIND END OF while(end != -1) { end = str.indexOf( delim, end ); // IS THIS DELIMITER ESCAPED ? if (str.charAt(end-1) != '\\') break; found_escaped_chars = true; // OK, LOOK FOR NEXT ONE end++; } if (end == -1) { err = 2; return ""; } } else { end = pos; while( end < str.length() ) { char ch = str.charAt( end ); if (ch == ' ') break; if (ch == '\n') break; if (ch == '\t') break; end++; } } // SHIFT STARTINDEX IF WE WANT TO SCAN ORDERED if (is_ordered()) from_index = end; if (found_escaped_chars) { StringBuffer sb = new StringBuffer(str.substring( pos, end )); int l = sb.length(); for (int i = 0; i < l; i++) { if ((sb.charAt(i) == '\\') && sb.charAt(i+1) != '\\') { sb.replace(i, i+1, ""); l = sb.length(); } } return sb.toString(); } return str.substring( pos, end ); } err = 1; return ""; } public String GetStringDelim(String token, char token_delim) { err = 0; boolean found_escaped_chars = false; int pos = str.indexOf( token, from_index ); if ((pos >= 0) && ((pos + token.length()) < str.length())) { pos += token.length(); while (pos < str.length() && str.charAt( pos ) == token_delim) pos++; char delim = str.charAt( pos ); int end = pos; if (delim == '\'' || delim == '\"') { pos++; end = pos; // FIND END OF while(end != -1) { end = str.indexOf( delim, end ); // IS THIS DELIMITER ESCAPED ? if (str.charAt(end-1) != '\\') break; found_escaped_chars = true; // OK, LOOK FOR NEXT ONE end++; } if (end == -1) { err = 2; return ""; } } else { end = pos; while( end < str.length() ) { char ch = str.charAt( end ); if (ch == ' ') break; if (ch == '\n') break; if (ch == '\t') break; end++; } } // SHIFT STARTINDEX IF WE WANT TO SCAN ORDERED if (is_ordered()) from_index = end; if (found_escaped_chars) { StringBuffer sb = new StringBuffer(str.substring( pos, end )); int l = sb.length(); for (int i = 0; i < l; i++) { if ((sb.charAt(i) == '\\') && sb.charAt(i+1) != '\\') { sb.replace(i, i+1, ""); l = sb.length(); } } return sb.toString(); } return str.substring( pos, end ); } err = 1; return ""; } public Long GetLong(String token) { String tmp = GetString(token); if (tmp.length() == 0) return new Long(0); return new Long(tmp); } public long GetLongValue(String token) { String tmp = GetString(token); if (tmp.length() == 0) return 0; return Long.parseLong(tmp); } public Double GetDouble(String token) { String tmp = GetString(token); if (tmp.length() == 0) return new Double(0); return new Double(tmp); } public double GetDoubleValue(String token) { String tmp = GetString(token); if (tmp.length() == 0) return 0.0; return Double.parseDouble(tmp); } public boolean GetBoolean(String token) { String tmp = GetString(token); if (tmp.length() == 0) return false; if (tmp.charAt(0) == '1') return true; return false; } public int getErr() { return err; } public String get_remaining_string() { return str.substring(from_index, str.length()); } public String GetCompressedString(String token) { String cstr = GetString(token); return ZipUtilities.uncompress(cstr); } public Object GetCompressedObject( String token ) { String cstr = GetString(token); return DeCompressObject(cstr); } public ArrayList<X509Certificate[]> GetCompressed509CertArrayList( String token ) { String cstr = GetString(token); return DeCompressX509CertArrayList(cstr); } public static String BuildCompressedX509CertArrayList( ArrayList<X509Certificate[]> cert_list ) { ArrayList<ArrayList<String>> certStringList = new ArrayList<>(); for (X509Certificate[] x509Certificates : cert_list) { ArrayList<String> stringList = new ArrayList<>(); certStringList.add(stringList); for (X509Certificate x509Certificate : x509Certificates) { ByteArrayOutputStream byos = new ByteArrayOutputStream(); try { ObjectOutputStream out = new ObjectOutputStream(byos); out.writeObject(x509Certificate); out.close(); } catch (Exception exception) { System.err.println("Abort in BuildCompressedX509CertArrayList: " + exception.getMessage()); } byte[] d = byos.toByteArray(); XStream xs = new XStream(); String xml = xs.toXML(d); stringList.add(xml); // // ByteArrayInputStream byis = new ByteArrayInputStream(d); // ObjectInputStream in = new ObjectInputStream(byis); // Object o = in.readObject(); /* * XStream xs = new XStream(); * String xml = xs.toXML(x509Certificate); * Object o = xs.fromXML(xml); * */ //System.out.print(o); } } XStream xs = new XStream(); return ZipUtilities.compress(xs.toXML(certStringList)); } public static ArrayList<X509Certificate[]> DeCompressX509CertArrayList( String cstr ) { String xml = ZipUtilities.uncompress(cstr); XStream xs = new XStream(); @SuppressWarnings("unchecked") ArrayList<ArrayList<String>> certStringList = (ArrayList<ArrayList<String>>) xs.fromXML(xml); ArrayList<X509Certificate[]> certArrayList = new ArrayList<>(); for (ArrayList<String> stringList : certStringList) { ArrayList<X509Certificate> certList = new ArrayList<>(); for (String string : stringList) { byte[] d = (byte[]) xs.fromXML(string); ByteArrayInputStream byis = new ByteArrayInputStream(d); try { try (ObjectInputStream in = new ObjectInputStream(byis)) { X509Certificate cert = (X509Certificate) in.readObject(); certList.add(cert); } } catch (Exception exception) { System.err.println("Abort in DeCompressX509CertArrayList: " + exception.getMessage()); } } certArrayList.add(certList.toArray(new X509Certificate[0])); } return certArrayList; } public static String BuildCompressedObjectString( Object o ) { XStream xs = new XStream(); String xml = xs.toXML(o); String cxml = ZipUtilities.compress(xml); return cxml; } public static Object DeCompressObject( String cstr ) { String xml = ZipUtilities.uncompress(cstr); XStream xs = new XStream(); return xs.fromXML(xml); } public <T> T GetObject( String token, Class t ) { Object o = GetCompressedObject(token); if (t.isInstance(o)) { return (T) o; } System.err.println("Wrong class in GetObject, expected: " + t.getName() + " got: " + o.getClass().getName()); return null; } public ArrayList<X509Certificate[]> GetX509CertArrayList( String token ) { return GetCompressed509CertArrayList(token); } }
30.063712
117
0.447895
1063c607048edf377d6bc436b632dfda02f7ddf4
3,110
package io.mercury.serialization.wire; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; import net.openhft.chronicle.wire.Marshallable; import net.openhft.chronicle.wire.WireIn; import net.openhft.chronicle.wire.WireKey; import net.openhft.chronicle.wire.WireOut; /** * * @author gadei */ public class WireCollection extends WireModel implements Marshallable { enum Values implements WireKey { REFERENCE, PATH, NAME, PROPERTIES, COLLECTIONS }; private String reference; private String path; private String name; private Map<String, WireProperty> properties = new HashMap<>(); private Map<String, WireCollection> collections = new HashMap<>(); public WireCollection() { } public WireCollection(String reference, String path, String name, long id, int revision, String key) { super(id, revision, key); this.reference = reference; this.path = path; this.name = name; } @Override public void readMarshallable(@NotNull WireIn wire) throws IllegalStateException { super.readMarshallable(wire); this.reference = wire.read(WireCollection.Values.REFERENCE).text(); this.path = wire.read(WireCollection.Values.PATH).text(); this.name = wire.read(WireCollection.Values.NAME).text(); this.properties = wire.read(WireCollection.Values.PROPERTIES).marshallableAsMap(String.class, WireProperty.class); this.collections = wire.read(WireCollection.Values.COLLECTIONS).marshallableAsMap(String.class, WireCollection.class); } @Override public void writeMarshallable(WireOut wire) { super.writeMarshallable(wire); wire.write(WireCollection.Values.REFERENCE).text(reference).write(WireCollection.Values.PATH).text(path) .write(WireCollection.Values.NAME).text(name); if (properties.size() > 0) { wire.write(WireCollection.Values.PROPERTIES).marshallable(properties); } if (collections.size() > 0) { wire.write(WireCollection.Values.COLLECTIONS).marshallable(collections); } } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void clearProperties() { properties.clear(); } public Map<String, WireProperty> getProperties() { return properties; } public void setProperties(Map<String, WireProperty> properties) { this.properties = properties; } public void addProperty(WireProperty property) { this.properties.put(property.getReference(), property); } public void setCollections(Map<String, WireCollection> collections) { this.collections = collections; } public Map<String, WireCollection> getCollections() { return collections; } public void addCollection(WireCollection collection) { this.collections.put(collection.getReference(), collection); } }
26.581197
107
0.72283
8c329ed58826998a1231bdc6aa3c30d48fdbd465
645
package org.xpdojo.designpatterns._03_behavioral_patterns._05_mediator; import org.xpdojo.designpatterns._03_behavioral_patterns._05_mediator.hotel.FrontDesk; import java.time.LocalDateTime; public class Guest { private final Integer id; private final FrontDesk frontDesk = new FrontDesk(); public Guest(Integer id) { this.id = id; } public String getTowers(int numberOfTowers) { return this.frontDesk.getTowers(this, numberOfTowers); } private void dinner(LocalDateTime dateTime) { this.frontDesk.dinner(this, dateTime); } public Integer getId() { return id; } }
22.241379
86
0.706977
d330a8e0d7ccae4428f8c3d3c123b3d103eb72a8
976
package org.cujau.xml; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.NamespaceContext; /** * Map-based NamespaceContext implementation. */ public class NamespaceContextImpl implements NamespaceContext { private Map<String, String> prefixToURI = new HashMap<String, String>(); private Map<String, String> uriToPrefix = new HashMap<String, String>(); @Override public String getNamespaceURI( String prefix ) { return prefixToURI.get( prefix ); } @Override public String getPrefix( String namespaceURI ) { return uriToPrefix.get( namespaceURI ); } @Override public Iterator<String> getPrefixes( String namespaceURI ) { return prefixToURI.keySet().iterator(); } public void addNamespace( String prefix, String uri ) { prefixToURI.put( prefix, uri ); uriToPrefix.put( uri, prefix ); } }
26.378378
77
0.667008
9c854cfd65416cf68e11d871f287c52302da6911
6,693
package network; import beans.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Server; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import utils.Ressources; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; public class ServeurKryoNetTron { private static boolean run = true; private Server server; private LinkedList<String> console; private HashMap<Integer, PacketLog> listeJoueurs; private int nbreConnexions = 0; static public final int port = Ressources.port; // le port utilisé pour TCP private int nbJoueursPret; private int xCarte; private int yCarte; public ServeurKryoNetTron() throws IOException { nbJoueursPret = 0; listeJoueurs = new HashMap<Integer, PacketLog>(); console = new LinkedList<String>(); chargerRessources(); System.out.println("SERVEUR - Taille carte x:" + xCarte + ", y:" + yCarte + ""); console.add("SERVEUR - Lancement du serveur"); server = new Server(); Kryo kryo = server.getKryo(); kryo.register(PacketLog.class); kryo.register(PacketLogBack.class); kryo.register(PacketCoord.class); kryo.register(PacketLeave.class); kryo.register(PacketMAJJoueurs.class); kryo.register(PacketAlerte.class); kryo.register(PacketPret.class); console.add("SERVEUR - Serveur lancé"); server.addListener(new Listener() { public void connected(Connection connection) { nbreConnexions = nbreConnexions + 1; } public void received(Connection c, Object object) { if (object instanceof PacketLog) { PacketLog log = (PacketLog) object; String nom = log.getNom(); console.add("SERVEUR - Connecté LOGIN: " + nom); console.add("SERVEUR - Nombre de connection(s) :" + nbreConnexions); listeJoueurs.put(c.getID(), log); /* on prépare le message de retour à tous les joueurs */ PacketLogBack annonce = new PacketLogBack(); annonce.setMessage("SERVEUR - Le joueur :" + nom + " vient de se connecter !\n"); annonce.setxCarte(xCarte); annonce.setyCarte(yCarte); server.sendToAllTCP(annonce); // joueurOnMap.add(c.getID()); PacketMAJJoueurs pmj = new PacketMAJJoueurs(); pmj.setR(log.getR()); pmj.setG(log.getG()); pmj.setB(log.getB()); pmj.setNombreJoueurs(nbreConnexions); pmj.setID(c.getID()); server.sendToAllTCP(pmj); for (int i = 0; i < server.getConnections().length; i++) { Connection[] cs = server.getConnections(); if (cs[i].getID() != c.getID()) { System.out.println("MAJ Recus de " + c.getID() + " et envoi à " + cs[i].getID()); PacketMAJJoueurs pmj2 = new PacketMAJJoueurs(); pmj2.setR(listeJoueurs.get(cs[i].getID()).getR()); pmj2.setG(listeJoueurs.get(cs[i].getID()).getG()); pmj2.setB(listeJoueurs.get(cs[i].getID()).getB()); pmj2.setNombreJoueurs(nbreConnexions); pmj2.setID(cs[i].getID()); server.sendToTCP(c.getID(), pmj2); } } } else if (object instanceof PacketCoord) { int ID = c.getID(); PacketCoord packet = new PacketCoord((PacketCoord) object); server.sendToAllExceptTCP(ID, packet); } else if (object instanceof PacketAlerte) { PacketAlerte packet = new PacketAlerte((PacketAlerte) object); server.sendToAllExceptTCP(c.getID(), packet); } else if (object instanceof PacketPret) { nbJoueursPret++; PacketPret packet = new PacketPret(); System.out.println("SERVEUR - nbJoueursPret : " + nbJoueursPret + " nbConnec : " + nbreConnexions); if (nbJoueursPret == nbreConnexions) { server.sendToAllTCP(packet); } } else { // System.out.println("SERVEUR - Comprend pas " + // c.getID()); } } public void disconnected(Connection connection) { int ID = connection.getID(); // PacketLeave p = new PacketLeave(ID); server.sendToAllExceptTCP(ID, ID); System.out.println("SERVEUR - déconnection de " + connection.getID()); } }); server.bind(port); server.start(); } public static void main(String[] args) throws IOException { new ServeurKryoNetTron(); } private void chargerRessources() { SAXBuilder saxBuilder = new SAXBuilder(); File file = new File("src/main/resources/confServer.xml"); try { Document document = saxBuilder.build(file); Element element = document.getRootElement(); setxCarte(Integer.parseInt(element.getChildText("x"))); yCarte = Integer.parseInt(element.getChildText("y")); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public LinkedList<String> getConsole() { LinkedList<String> tmp = new LinkedList<String>(console); console.clear(); return tmp; } public boolean isRun() { return run; } public int getyCarte() { return yCarte; } public void setyCarte(int yCarte) { this.yCarte = yCarte; } public void setRun(boolean run) { ServeurKryoNetTron.run = run; } public int getxCarte() { return xCarte; } public void setxCarte(int xCarte) { this.xCarte = xCarte; } public int getNbJoueursPret() { return nbJoueursPret; } public void setNbJoueursPret(int nbJoueursPret) { this.nbJoueursPret = nbJoueursPret; } }
36.178378
119
0.554161
76bcdad09e02751db7a65e4b9ed8ea2aa4b0ef8d
11,522
package com.zzh.lib.switchbutton.gesture; import android.content.Context; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import java.util.ArrayList; import java.util.List; /** * 触摸事件处理帮助类<br> */ public class HTouchHelper { private float mCurrentX; private float mCurrentY; private float mLastX; private float mLastY; private float mDownX; private float mDownY; private Direction mDirection = Direction.None; /** * 处理触摸事件 * * @param ev */ public void processTouchEvent(MotionEvent ev) { mLastX = mCurrentX; mLastY = mCurrentY; mCurrentX = ev.getRawX(); mCurrentY = ev.getRawY(); final int aciton = ev.getAction(); switch (aciton) { case MotionEvent.ACTION_DOWN: mDownX = mCurrentX; mDownY = mCurrentY; setDirection(Direction.None); break; default: break; } } public float getCurrentX() { return mCurrentX; } public float getCurrentY() { return mCurrentY; } public float getLastX() { return mLastX; } public float getLastY() { return mLastY; } public float getDownX() { return mDownX; } public float getDownY() { return mDownY; } //---------- Delta Start ---------- /** * 返回当前事件和上一次事件之间的x轴方向增量 * * @return */ public float getDeltaX() { return mCurrentX - mLastX; } /** * 返回当前事件和上一次事件之间的y轴方向增量 */ public float getDeltaY() { return mCurrentY - mLastY; } /** * 返回当前事件和{@link MotionEvent#ACTION_DOWN}事件之间的x轴方向增量 * * @return */ public float getDeltaXFromDown() { return mCurrentX - mDownX; } /** * 返回当前事件和{@link MotionEvent#ACTION_DOWN}事件之间的y轴方向增量 * * @return */ public float getDeltaYFromDown() { return mCurrentY - mDownY; } //---------- Delta End ---------- //---------- Degree Start ---------- /** * 返回当前事件和上一次事件之间的x轴方向夹角 * * @return */ public double getDegreeX() { final float dx = getDeltaX(); if (dx == 0) return 0; final float dy = getDeltaY(); final float angle = Math.abs(dy) / Math.abs(dx); return Math.toDegrees(Math.atan(angle)); } /** * 返回当前事件和上一次事件之间的y轴方向夹角 * * @return */ public double getDegreeY() { final float dy = getDeltaY(); if (dy == 0) return 0; final float dx = getDeltaX(); final float angle = Math.abs(dx) / Math.abs(dy); return Math.toDegrees(Math.atan(angle)); } /** * 返回当前事件和{@link MotionEvent#ACTION_DOWN}事件之间的x轴方向夹角 * * @return */ public double getDegreeXFromDown() { final float dx = getDeltaXFromDown(); if (dx == 0) return 0; final float dy = getDeltaYFromDown(); final float angle = Math.abs(dy) / Math.abs(dx); return Math.toDegrees(Math.atan(angle)); } /** * 返回当前事件和{@link MotionEvent#ACTION_DOWN}事件之间的y轴方向夹角 * * @return */ public double getDegreeYFromDown() { final float dy = getDeltaYFromDown(); if (dy == 0) return 0; final float dx = getDeltaXFromDown(); final float angle = Math.abs(dx) / Math.abs(dy); return Math.toDegrees(Math.atan(angle)); } //---------- Degree End ---------- //---------- Direction Start ---------- /** * 保存当前移动方向 * * @param touchSlop 最小移动距离 * @return */ public boolean saveDirection(final int touchSlop) { if (mDirection != Direction.None) return false; final float dx = getDeltaXFromDown(); final float dy = getDeltaYFromDown(); final float dxAbs = Math.abs(dx); final float dyAbs = Math.abs(dy); final float deltaMax = Math.max(dxAbs, dyAbs); if (deltaMax == 0 || deltaMax < touchSlop) return false; if (dxAbs > dyAbs) { // horizontal if (dx < 0) setDirection(Direction.MoveLeft); else setDirection(Direction.MoveRight); } else { // vertical if (dy < 0) setDirection(Direction.MoveTop); else setDirection(Direction.MoveBottom); } return true; } /** * 保存水平方向 * * @param touchSlop 最小移动距离 * @return */ public boolean saveDirectionHorizontal(final int touchSlop) { if (mDirection == Direction.MoveLeft || mDirection == Direction.MoveRight) return false; final float dx = getDeltaXFromDown(); if (dx == 0) return false; if (Math.abs(dx) < touchSlop) return false; if (dx < 0) setDirection(Direction.MoveLeft); else setDirection(Direction.MoveRight); return true; } /** * 保存竖直方向 * * @param touchSlop 最小移动距离 * @return */ public boolean saveDirectionVertical(final int touchSlop) { if (mDirection == Direction.MoveTop || mDirection == Direction.MoveBottom) return false; final float dy = getDeltaYFromDown(); if (dy == 0) return false; if (Math.abs(dy) < touchSlop) return false; if (dy < 0) setDirection(Direction.MoveTop); else setDirection(Direction.MoveBottom); return true; } private void setDirection(Direction direction) { mDirection = direction; } /** * 返回已保存的移动方向 * * @return */ public Direction getDirection() { return mDirection; } //---------- Direction End ---------- /** * 是否是点击事件 * * @param event * @param context * @return */ public boolean isClick(MotionEvent event, Context context) { if (event.getAction() == MotionEvent.ACTION_UP) { final long clickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout(); final int touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); final long duration = event.getEventTime() - event.getDownTime(); final int dx = (int) getDeltaXFromDown(); final int dy = (int) getDeltaYFromDown(); if (duration < clickTimeout && dx < touchSlop && dy < touchSlop) return true; } return false; } //----------static method start---------- /** * 返回合理的增量 * * @param current 当前值 * @param min 最小值 * @param max 最大值 * @param delta 增量 * @return */ public static int getLegalDelta(int current, int min, int max, int delta) { if (delta == 0) return 0; final int future = current + delta; if (future < min) { delta += (min - future); } else if (future > max) { delta += (max - future); } return delta; } /** * 是否请求当前view的父view不要拦截事件 * * @param view * @param disallowIntercept true-请求父view不要拦截,false-父view可以拦截 */ public static void requestDisallowInterceptTouchEvent(View view, boolean disallowIntercept) { final ViewParent parent = view.getParent(); if (parent != null) parent.requestDisallowInterceptTouchEvent(disallowIntercept); } /** * view是否处于某个坐标点下面,相对父布局的坐标 * * @param view * @param x * @param y * @return */ public static boolean isViewUnder(View view, int x, int y) { return x >= view.getLeft() && x < view.getRight() && y >= view.getTop() && y < view.getBottom(); } /** * view是否处于某个坐标点下面,相对屏幕的坐标 * * @param view * @param x * @param y * @return */ public static boolean isViewUnderScreen(View view, int x, int y) { final int[] location = new int[2]; view.getLocationOnScreen(location); return x >= location[0] && x < location[0] + view.getWidth() && y >= location[1] && y < location[1] + view.getHeight(); } /** * 找到parent中处于指定坐标下的child * * @param parent * @param x * @param y * @return */ public static List<View> findChildrenUnder(ViewGroup parent, int x, int y) { final List<View> list = new ArrayList<>(2); final int count = parent.getChildCount(); for (int i = count - 1; i >= 0; i--) { final View child = parent.getChildAt(i); if (isViewUnder(child, x, y)) { list.add(child); } } return list; } /** * 找到parent中处于指定坐标下最顶部的child(Z值最大,最后面添加) * * @param parent * @param x * @param y * @return */ public static View findTopChildUnder(ViewGroup parent, int x, int y) { if (Build.VERSION.SDK_INT < 21) return parent.getChildAt(parent.getChildCount() - 1); final List<View> list = findChildrenUnder(parent, x, y); if (list.isEmpty()) return null; View target = null; for (View item : list) { if (target == null) { target = item; } else { if (item.getZ() > target.getZ()) target = item; } } return target; } /** * view是否已经滚动到最左边 * * @param view * @return */ public static boolean isScrollToLeft(View view) { return !view.canScrollHorizontally(-1); } /** * view是否已经滚动到最顶部 * * @param view * @return */ public static boolean isScrollToTop(View view) { return !view.canScrollVertically(-1); } /** * view是否已经滚动到最右边 * * @param view * @return */ public static boolean isScrollToRight(View view) { return !view.canScrollHorizontally(1); } /** * view是否已经滚动到最底部 * * @param view * @return */ public static boolean isScrollToBottom(View view) { return !view.canScrollVertically(1); } //----------static method end---------- public StringBuilder getDebugInfo() { final StringBuilder sb = new StringBuilder("\r\n") .append("Down:").append(mDownX).append(",").append(mDownY).append("\r\n") .append("Current:").append(mCurrentX).append(",").append(mCurrentY).append("\r\n") .append("Delta from down:").append(getDeltaXFromDown()).append(",").append(getDeltaYFromDown()).append("\r\n") .append("Delta from last:").append(getDeltaX()).append(",").append(getDeltaY()).append("\r\n") .append("Degree from down:").append(getDegreeXFromDown()).append(",").append(getDegreeYFromDown()).append("\r\n") .append("Degree from last:").append(getDegreeX()).append(",").append(getDegreeY()).append("\r\n"); return sb; } public enum Direction { None, MoveLeft, MoveTop, MoveRight, MoveBottom } }
23.855072
129
0.534195
84aba9932503c2578ae758c3870ca6c5d3180944
2,802
package ca.uhn.fhir.jpa.searchparam.extractor; /*- * #%L * HAPI FHIR Search Parameters * %% * Copyright (C) 2014 - 2022 Smile CDR, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * This class fully and unabashedly stolen from Hibernate search 5.11.4 FINAL's implementation as it was stripped in HS6 */ public class GeopointNormalizer { static int WHOLE_CIRCLE_DEGREE_RANGE = 360; static int LONGITUDE_DEGREE_RANGE = WHOLE_CIRCLE_DEGREE_RANGE; static int LATITUDE_DEGREE_RANGE = WHOLE_CIRCLE_DEGREE_RANGE / 2; static int LATITUDE_DEGREE_MIN = -LATITUDE_DEGREE_RANGE / 2; static int LATITUDE_DEGREE_MAX = LATITUDE_DEGREE_RANGE / 2; public static double normalizeLongitude(double longitude) { if ( longitude == ( -LONGITUDE_DEGREE_RANGE / 2 ) ) { return LONGITUDE_DEGREE_RANGE / 2 ; } else { return normalizeLongitudeInclusive( longitude ); } } public static double normalizeLongitudeInclusive(double longitude) { if ( (longitude < -( LONGITUDE_DEGREE_RANGE / 2 ) ) || (longitude > ( LONGITUDE_DEGREE_RANGE / 2 ) ) ) { double _longitude; // shift 180 and normalize full circle turn _longitude = ( ( longitude + ( LONGITUDE_DEGREE_RANGE / 2 ) ) % WHOLE_CIRCLE_DEGREE_RANGE ); // as Java % is not a math modulus we may have negative numbers so the unshift is sign dependant if ( _longitude < 0 ) { _longitude = _longitude + ( LONGITUDE_DEGREE_RANGE / 2 ); } else { _longitude = _longitude - ( LONGITUDE_DEGREE_RANGE / 2 ); } return _longitude; } else { return longitude; } } /** * @param latitude in degrees * @return latitude normalized in [-90;+90] */ public static double normalizeLatitude(double latitude) { if ( latitude > LATITUDE_DEGREE_MAX || latitude < LATITUDE_DEGREE_MIN ) { // shift 90, normalize full circle turn and 'symmetry' on the lat axis with abs double _latitude = Math.abs( ( latitude + ( LATITUDE_DEGREE_RANGE / 2 ) ) % ( WHOLE_CIRCLE_DEGREE_RANGE ) ); // Push 2nd and 3rd quadran in 1st and 4th by 'symmetry' if ( _latitude > LATITUDE_DEGREE_RANGE ) { _latitude = WHOLE_CIRCLE_DEGREE_RANGE - _latitude; } // unshift _latitude = _latitude - ( LATITUDE_DEGREE_RANGE / 2 ); return _latitude; } else { return latitude; } } }
33.759036
120
0.710207
e122b481cee3bc5c1212da4d7ade69acffb44edc
1,764
package com.interview.codingblocks.week6recursion; import java.util.Scanner; public class SmartKeypad { private static String table1[] = {" ", ".+@$", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; private static void solve( String input, char[] out, int i, int j ) { //if 'i' reaches end of input string; then start printing string recursively //and output last char should not be null if (i > input.length() - 1 && out[out.length - 1] != '\u0000') { System.out.println(out); return; } //if 'i th ' index is less that input string length then only go for next recursion if (i < input.length()) { int digitIndex = input.charAt(i) - '0'; //convert 1 to digit 1; So that we can get index of table Array //if char occur like 2113 : then our recursion should not stuck at 1 and we call on next index. if (digitIndex == 1 || digitIndex == 0) solve(input, out, i + 1, j); //checking until K reaches end of mapped input length. e.g 2 = abc for (int k = 0; k < table1[digitIndex].length(); k++) { out[j] = table1[digitIndex].toCharArray()[k]; //this recursion continue until i reaches end of input: eg 23 : i goes till length = 2 // 'J' help in stores the char at position solve(input, out, i + 1, j + 1); } } } //https://hack.codingblocks.com/contests/c/452/96 public static void main( String[] args ) { Scanner scanner = new Scanner(System.in); String input = scanner.next(); char[] arr = new char[input.length()]; solve(input, arr, 0, 0); } }
35.28
115
0.55839
fa32d26021bc89eb3ca962653507a0ebc7e212c3
1,026
package gov.usgs.cida.gdp.coreprocessing.analysis.grid; import org.junit.AfterClass; import org.junit.BeforeClass; /** * @author jordan * I realize that this class is pretty much just to test the default Visitor * functions, and that they don't really do anything currently. * So this isn't very useful, but I'm going to leave it in place anyway. */ public class GridCellVisitorInheritMock extends GridCellVisitor { private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GridCellVisitorInheritMock.class); @BeforeClass public static void setUpBeforeClass() throws Exception { log.debug("Started testing class."); } @AfterClass public static void tearDownAfterClass() throws Exception { log.debug("Ended testing class."); } private int processCount = 0; @Override public void processGridCell(int xCellIndex, int yCellIndex, double value) { processCount++; } public int getProcessCount() { return processCount; } }
28.5
110
0.716374
6d8f1305b4ba3fbc56d7b0764106d95a3e066bb4
1,955
package training.math; import org.junit.jupiter.api.Test; import util.CollectionUtil; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.IntFunction; import static org.junit.jupiter.api.Assertions.assertEquals; /** * 89. 格雷编码: https://leetcode-cn.com/problems/gray-code/ * * 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 * 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。 * * 格雷编码序列必须以 0 开头。 * * 例 1: * 输入: 2 * 输出: [0,1,3,2] * 解释: * 00 - 0 * 01 - 1 * 11 - 3 * 10 - 2 * * 对于给定的 n,其格雷编码序列并不唯一。 * 例如,[0,2,3,1] 也是一个有效的格雷编码序列。 * 00 - 0 * 10 - 2 * 11 - 3 * 01 - 1 * * 例 2: * 输入: 0 * 输出: [0] * 解释: 我们定义格雷编码序列必须以 0 开头。 * 给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。 * 因此,当 n = 0 时,其格雷编码序列为 [0]。 */ public class E89_Medium_GrayCode { public static void test(IntFunction<List<Integer>> method) { //noinspection unchecked CollectionUtil.in(method.apply(2), Arrays.asList(0, 1, 3, 2), Arrays.asList(0, 2, 3, 1)); assertEquals(Collections.singletonList(0), method.apply(0)); assertEquals(Arrays.asList(0, 1, 3, 2, 6, 7, 5, 4), method.apply(3)); } /** * 0 1 * 00 01 11 10 * 000 001 011 010 110 111 101 100 * * 注意到 n 位的格雷码就是 n - 1 位格雷码倒过来排列并且每个数最高位加 1。 * * LeetCode 耗时:4 ms - 97.96% * 内存消耗:44.2 MB - 98.53% */ public List<Integer> grayCode(int n) { if (n == 0) { return Collections.singletonList(0); } Integer[] result = new Integer[1 << n]; result[0] = 0; result[1] = 1; for (int len = 2, shift = 1; len < result.length; len *= 2, shift++) { for (int i = 0; i < len; i++) { result[i + len] = result[len - 1 - i] + (1 << shift); } } return Arrays.asList(result); } @Test public void testGrayCode() { test(this::grayCode); } }
23
97
0.561125
ecab9e8fa01feff3ad52e299757cc8abb4853b6b
118
package kr.pe.kwonnam.freemarkerdynamicqlbuilder; /** * */ public enum EmployeeType { FULLTIME, PARTTIME }
11.8
49
0.694915
7fe16f624bbcf7ac2a7283d80f0ad0c03967f3a0
257
package dmt.server.data.entity; import dmt.server.data.helper.Entity; import dmt.server.data.table.UserAccountRecoveryTable; /** * @author Marco Romagnolo */ public class UserAccountRecoveryEntity extends UserAccountRecoveryTable implements Entity { }
21.416667
91
0.809339
085a40aa73413a1dc657037bb855e5ba49141eb2
1,061
package com.hubspot.singularity.s3downloader.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Provider; import com.hubspot.singularity.runner.base.sentry.SingularityRunnerExceptionNotifier; import com.hubspot.singularity.s3.base.ArtifactManager; import com.hubspot.singularity.s3.base.config.SingularityS3Configuration; public class ArtifactManagerProvider implements Provider<ArtifactManager> { private final Logger log; private final SingularityS3Configuration s3Configuration; private final SingularityRunnerExceptionNotifier exceptionNotifier; @Inject public ArtifactManagerProvider(SingularityS3Configuration s3Configuration, SingularityRunnerExceptionNotifier exceptionNotifier) { this.log = LoggerFactory.getLogger(ArtifactManager.class); this.s3Configuration = s3Configuration; this.exceptionNotifier = exceptionNotifier; } @Override public ArtifactManager get() { return new ArtifactManager(s3Configuration, log, exceptionNotifier); } }
34.225806
132
0.831291
d8280f337ac729a4616372db515e2ea686c7e0b3
18,460
/* * Copyright 2011 Voxeo Corp. * * 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.phono.audio.codec.gsm; import java.io.*; /** * This class implements some of the basic arithmetic for encoding and * decoding gsm.<br/> * Chapter 5.2 and 5.3 of <br/> * <br/> * ETSI EN 300 961 V8.1.1 (2000-11)<br/> * European Standard (Telecommunications series)<br/> * Digital cellular telecommunications system (Phase 2+);<br/> * Full rate speech;<br/> * Transcoding<br/> * (GSM 06.10 version 8.1.1 Release 1999)<br/> * */ public class GSM_Base implements GSM_Constant { public final Arithmetic AR = new Arithmetic(); /** LARpp_j from previous frame */ protected short _LARpp_j_1[]; /** * Keep _LAR, so main can use them */ protected short _LAR[]; /** * Keep the segment _params, so main can use them */ protected SegmentParam _params[]; public GSM_Base() { _LARpp_j_1 = new short[9]; } /** * Procedure 5.2.15 APCM quantization of the selected RPE sequence<br/> * * This is cut in three, to facilitate decoding: * - apcmQuantizationRPESequence (short xM[], SegmentParam param) * - getExponentMantissa(SegmentParam param) * - computeXMC(short xM[], SegmentParam param) */ // 4x per frame protected void getExponentMantissa(SegmentParam param) { short var1, var2, itest; /* * Quantizing and coding of the xM[0..12] RPE sequence to get * the _xMc[0..12]. * This computation uses the fact that the decoded version of * _xmaxc can be calculated by using the exponent and the * mantissa part of _xmaxc (logarithmic table). * * So, this method avoids any division and uses only a scaling * of the RPE samples by a function of the exponent. A direct * multiplication by the inverse of the mantissa (NRFAC[0..7] * found in table 5.5) gives the 3 bit coded version _xMc[0..12] * of the RPE samples. */ // Compute exponent and mantissa of the decoded version of _xmaxc. param._exp = 0; if (param._xmaxc > 15) { var1 = AR.toShort(param._xmaxc >> 3); param._exp = AR.s_sub(var1, (short)1); } var2 = AR.toShort(param._exp << 3); param._mant = AR.s_sub(param._xmaxc, var2); // Normalize mantissa 0 <= param._mant <= 7. if (param._mant == 0) { param._exp = -4; param._mant = 15; } else { // TODO: itest seems like boolean flag? // change to while loop? itest = 0; for (int i=0; i<3; i++) { if (param._mant > 7) { itest = 1; } if (itest == 0) { var1 = AR.toShort(param._mant << 1); param._mant = AR.s_add(var1, (short)1); /* } if (itest == 0) { */ param._exp = AR.s_sub(param._exp, (short)1); } } } param._mant = AR.s_sub(param._mant, (short)8); } /** * Procedure 5.2.16 APCM inverse quantization * This part is for decoding the RPE sequence of coded _xMc[0..12] * samples to obtain the xMp[0..12] array. Table 5.6 is used to get * the mantissa of _xmaxc (FAC[0..7]). */ // 4x per frame protected short[] apcmInverseQuantization(SegmentParam param) { short xMp[] = new short[13]; short temp, temp1, temp2, temp3, var1; // See 5.2.15 for _mant temp1 = FAC[param._mant]; // See 5.2.15 for _exp temp2 = AR.s_sub((short)6, param._exp); temp3 = AR.toShort(1 << AR.s_sub(temp2, (short)1)); for (int i=0; i<13; i++) { // This subtraction is used to restore the sign of _xMc[i]. var1 = AR.toShort(param._xMc[i] << 1); temp = AR.s_sub(var1, (short)7); temp = AR.toShort(temp << 12); temp = AR.s_mult_r(temp1, temp); temp = AR.s_add(temp, temp3); xMp[i] = AR.toShort(temp >> temp2); } return xMp; } /** * Procedure 5.2.17 RPE grid positioning<br/> * This procedure computes the reconstructed long term residual * signal ep[0..39] for the LTP analysis filter. The inputs are the * _Mc which is the grid position selection and the xMp[0..12] * decoded RPE samples which are upsampled by a factor of 3 by * inserting zero values. */ // 4x per frame protected short[] rpeGridPositioning(short xMp[], SegmentParam param) { short ep[] = new short[SEGMENT]; /* // No need, new short[] inits all to zero for (int k=0; k<SEGMENT; k++) { ep[k] = 0; } */ for (int i=0; i<13; i++) { ep[param._Mc + (3*i)] = xMp[i]; } return ep; } /** * Procedure 5.2.8 Decoding of the coded Log.-Area Ratios<br/> */ /* * This procedure requires for efficient implementation two tables. * INVA[1..8]=integer((32768*8)/(real_A[1..8]); 8 values (table 5.2) * MIC[1..8]=minimum value of the _LAR[1..8]; 8 values (table 5.1) */ protected short[] decodeLAR(short LARc[], short LARpp[]) { // Compute the LARpp[1..8]. short temp1, temp2; for (int i=1; i<9; i++) { // The addition of MIC[i] is used to restore the sign of // _LAR[i]. temp1 = AR.toShort(AR.s_add(LARc[i], MIC[i]) << 10); temp2 = AR.toShort(B[i] << 1); temp1 = AR.s_sub(temp1, temp2); temp1 = AR.s_mult_r(INVA[i], temp1); LARpp[i] = AR.s_add(temp1, temp1); } return LARpp; } /** * Procedure 5.2.9 Computation of the quantized reflection coefficients<br/> * * Within each frame of 160 analysed speech samples the short term * analysis and synthesis filters operate with four different sets * of coefficients, derived from the previous set of decoded * LARs(LARpp(j-1)) and the actual set of decoded LARs (LARpp(j)). * <br/> * <br/> * Procedure 5.2.9.1 Interpolation of the LARpp[1..8] to get the * LARp[1..8]<br/> * <br/> */ /* * Procedure 5.2.9 Computation of the quantized reflection coefficients<br/> * * Within each frame of 160 analysed speech samples the short term * analysis and synthesis filters operate with four different sets * of coefficients, derived from the previous set of decoded * LARs(LARpp(j-1)) and the actual set of decoded LARs (LARpp(j)). */ /** * Procedure 5.2.9.1 Interpolation of the LARpp[1..8] to get the * LARp[1..8]<br/> * For k_start = 0 to k_end &lt; 13 <br/> * Initial value: LARpp(j-1)[1..8]=0;<br/> */ protected short[] interpolationLARpp_1(short LARpp_j_1[], short LARpp_j[], short LARp[]) { short var1, var2; for (int i=1; i<9; i++) { var1 = AR.toShort(LARpp_j_1[i] >> 2); var2 = AR.toShort(LARpp_j[i] >> 2); LARp[i] = AR.s_add(var1, var2); var2 = AR.toShort(LARpp_j_1[i] >> 1); LARp[i] = AR.s_add(LARp[i], var2); } return LARp; } /** * Procedure 5.2.9.1 Interpolation of the LARpp[1..8] to get the * LARp[1..8]<br/> * For k_start = 13 to k_end &lt; 27<br/> */ protected short[] interpolationLARpp_2(short LARpp_j_1[], short LARpp_j[], short LARp[]) { short var1, var2; for (int i=1; i<9; i++) { var1 = AR.toShort(LARpp_j_1[i] >> 1); var2 = AR.toShort(LARpp_j[i] >> 1); LARp[i] = AR.s_add(var1, var2); } return LARp; } /** * Procedure 5.2.9.1 Interpolation of the LARpp[1..8] to get the * LARp[1..8]<br/> * For k_start = 27 to k_end &lt; 40 <br/> */ protected short[] interpolationLARpp_3(short LARpp_j_1[], short LARpp_j[], short LARp[]) { short var1, var2; for (int i=1; i<9; i++) { var1 = AR.toShort(LARpp_j_1[i] >> 2); var2 = AR.toShort(LARpp_j[i] >> 2); LARp[i] = AR.s_add(var1, var2); var1 = LARp[i]; var2 = AR.toShort(LARpp_j[i] >> 1); LARp[i] = AR.s_add(var1, var2); } return LARp; } /** * Procedure 5.2.9.1 Interpolation of the LARpp[1..8] to get the * LARp[1..8]<br/> * For k_start = 40 to k_end &lt; 160 <br/> */ protected short[] interpolationLARpp_4(short LARpp_j_1[], short LARpp_j[], short LARp[]) { // TODO: // use memcopy? for (int i=1; i<9; i++) { LARp[i] = LARpp_j[i]; } return LARp; } /** * Procedure 5.2.9.2 Computation of the rp[1..8] from the interpolated * LARp[1..8]<br/> * The input of this procedure is the interpolated LARp[1..8] array. * The reflection coefficients, rp[i], are used in the analysis * filter and in the synthesis filter. */ protected short[] computeRP(short LARp[], short rp[]) { short temp, var1; for (int i=1; i<9; i++) { temp = AR.s_abs(LARp[i]); if (temp < 11059) { temp = AR.toShort(temp << 1); } else if (temp < 20070) { temp = AR.s_add(temp, (short)11059); } else { var1 = AR.toShort(temp >> 2); temp = AR.s_add(var1, (short)26112); } rp[i] = temp; if (LARp[i] < 0) { rp[i] = AR.s_sub((short)0, rp[i]); } } return rp; } // The test files that come with the pdf are in LITTLE_ENDIAN public final static boolean LITTLE_ENDIAN = true; public short readShort(DataInputStream in) throws java.io.IOException { short s; if (LITTLE_ENDIAN) { s = readShortLittleEndian(in); } else { s = in.readShort(); } return s; } public short readShortLittleEndian(DataInputStream in) throws java.io.IOException { // 2 bytes int low = in.readByte() & 0xFF; int high = in.readByte() & 0xFF; short s = (short)(high << 8 | low); return s; } public void writeShort(DataOutputStream out, short value) throws java.io.IOException { if (LITTLE_ENDIAN) { writeShortLittleEndian(out, value); } else { out.writeShort(value); } } public void writeShortLittleEndian(DataOutputStream out, short value) throws java.io.IOException { // 2 bytes byte low = (byte) (value & 0xFF); byte high = (byte) ((value >> 8) & 0xFF); byte bytes[] = {low, high}; out.write(bytes, 0, bytes.length); } /** * Set bit number (bitno) to one. The bit numbering pretends the * byte array is one very long word. * * @param output The output array to set the bit * @param bitno The position of the bit (in output) */ public static void setBit(byte output[], int bitno) throws java.lang.ArrayIndexOutOfBoundsException { // bit 0 is on the left hand side, if bit 0 should be set to '1' // this would show as: 1000 0000 = 0x80 // each byte is 8 bits int index = bitno / 8; int index_bitno = bitno % 8; // shift the '1' into the right place // shift with zero extension byte mask = (byte) (0x80 >>> index_bitno); // OR the bit into the byte, so the other bits remain // undisturbed. output[index] |= mask; } /** * Copies a number of bits from input to output. * Copy bits from left to right (MSB - LSB). * * @param input The input value to read from * @param in_noLSB The number of LSB in input to copy * @param output The output array to copy the bits to * @param out_pos The start position in output * @return the updated out_pos */ public static int copyBits(int input, int in_noLSB, byte output[], int out_pos) { int res; int value = input; // start with the left most bit I've got to copy over: int mask = 0x1 << (in_noLSB -1); for (int i=0; i<in_noLSB; i++) { // see if the that bit is one or zero res = (value & mask); if (res > 0) { setBit(output, out_pos); } // shift the mask to the next position // shift with zero extension mask = mask >>> 1; out_pos++; } return out_pos; } /** * Returns zero or one. * * @param input The input array to read from * @param bitno The position of the bit (in input) * @return one or zero */ public static int getBit(byte input[], int bitno) throws java.lang.ArrayIndexOutOfBoundsException { // bit 0 is on the left hand side, if bit 0 should be set to '1' // this would show as: 1000 0000 = 0x80 // each byte is 8 bits int index = bitno / 8; int index_bitno = bitno % 8; byte onebyte = input[index]; // shift the '1' into the right place // shift with zero extension byte mask = (byte) (0x80 >>> index_bitno); // mask (AND) it so see if the bit is one or zero int res = (onebyte & mask); if (res < 0) { // it can be negative when testing the signed bit (bit zero // in this case) res = 1; } return res; } /** * Copy a number of bits from input into a short. * Copy bits from left to right (MSB - LSB). * * @param input The input array to read from * @param in_pos The position of the bit (in input) to start from * @param no_bits The number of bits to copy * @return The new value as a short */ public static short copyBits(byte input[], int in_pos, int no_bits) { // LSB is on the right hand side short out_value = 0; // start with the left most bit I've got to copy into: int out_value_mask = 0x1 << (no_bits -1); int myBit; for (int b=0; b<no_bits; b++) { myBit = getBit(input, in_pos); if (myBit > 0) { // OR the bit into place, so the other bits remain // undisturbed. out_value |= out_value_mask; } // move to the next bit of input in_pos++; // get ready for the next bit of output // shift with zero extension out_value_mask = (short) (out_value_mask >>> 1); } return out_value; } public void writeCodedParams(DataOutputStream out) throws java.io.IOException { /* * LSB Variable Frame * 6 _LAR[1] 1 * 6 _LAR[2] 2 * 5 _LAR[3] 3 * 5 _LAR[4] 4 * 4 _LAR[5] 5 * 4 _LAR[6] 6 * 3 _LAR[7] 7 * 3 _LAR[8] 8 */ /* * 4x: * LSB Variable Seg1 Seg2 * 7 _Nc 9 26 * 2 _bc 10 27 * 2 _Mc 11 28 * 6 _xmaxc 12 29 * 3 _xMc[0..12] 13-25 30-42 */ // NOT GSM_HEADER!!! for (int i=1; i<9; i++) { writeShort(out, _LAR[i]); } for (int s=0; s<4; s++) { SegmentParam para = _params[s]; writeShort(out, para._Nc); writeShort(out, para._bc); writeShort(out, para._Mc); writeShort(out, para._xmaxc); for (int i=0; i<para._xMc.length; i++) { writeShort(out, para._xMc[i]); } } } public void readCodedParams(DataInputStream in) throws java.io.IOException { /* * LSB Variable Frame * 6 _LAR[1] 1 * 6 _LAR[2] 2 * 5 _LAR[3] 3 * 5 _LAR[4] 4 * 4 _LAR[5] 5 * 4 _LAR[6] 6 * 3 _LAR[7] 7 * 3 _LAR[8] 8 */ /* * 4x: * LSB Variable Seg1 Seg2 * 7 _Nc 9 26 * 2 _bc 10 27 * 2 _Mc 11 28 * 6 _xmaxc 12 29 * 3 _xMc[0..12] 13-25 30-42 */ // NOT GSM_HEADER!!! _LAR = new short[9]; for (int i=1; i<9; i++) { _LAR[i] = readShort(in); } _params = new SegmentParam[4]; for (int s=0; s<4; s++) { SegmentParam para = new SegmentParam(); para._Nc = readShort(in); para._bc = readShort(in); para._Mc = readShort(in); para._xmaxc = readShort(in); para._xMc = new short[13]; for (int i=0; i<para._xMc.length; i++) { para._xMc[i] = readShort(in); } _params[s] = para; } } }
32.048611
80
0.508017
aa8aeca714ce8715469c57f85fd92699648f2c8f
9,056
package es.redmic.test.vesselsview.integration.controller; /*- * #%L * Vessels-query-endpoint * %% * Copyright (C) 2019 REDMIC Project / Server * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.startsWith; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.kafka.test.rule.EmbeddedKafkaRule; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import es.redmic.models.es.common.query.dto.MgetDTO; import es.redmic.models.es.common.query.dto.SimpleQueryDTO; import es.redmic.testutils.documentation.DocumentationViewBaseTest; import es.redmic.testutils.utils.JsonToBeanTestUtil; import es.redmic.vesselsview.VesselsViewApplication; import es.redmic.vesselsview.model.vesseltype.VesselType; import es.redmic.vesselsview.repository.vesseltype.VesselTypeESRepository; @SpringBootTest(classes = { VesselsViewApplication.class }) @RunWith(SpringJUnit4ClassRunner.class) @TestPropertySource(properties = { "schema.registry.port=18082" }) @DirtiesContext public class VesselTypeControllerTest extends DocumentationViewBaseTest { @Value("${documentation.VESSEL_HOST}") private String HOST; @Value("${controller.mapping.vesseltype}") private String VESSELTYPE_PATH; @Autowired VesselTypeESRepository repository; VesselType vesselType = new VesselType(); @ClassRule public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1); @PostConstruct public void CreateVesselFromRestTestPostConstruct() throws Exception { createSchemaRegistryRestApp(embeddedKafka.getEmbeddedKafka().getZookeeperConnectionString(), embeddedKafka.getEmbeddedKafka().getBrokersAsString()); } @Override @Before public void setUp() { String code = RandomStringUtils.random(4, true, false); vesselType.setId("vesseltype-code-" + code); vesselType.setCode(code); vesselType.setName("Other Type, no additional information"); vesselType.setName_en("Other Type, no additional information"); repository.save(vesselType); // @formatter:off mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .addFilters(springSecurityFilterChain) .apply(documentationConfiguration(this.restDocumentation) .uris().withScheme(SCHEME).withHost(HOST).withPort(PORT)) .alwaysDo(this.document).build(); // @formatter:on } @After public void clean() { repository.delete(vesselType.getId()); } @Test public void getVesselType_Return200_WhenItemExist() throws Exception { // @formatter:off this.mockMvc.perform(get(VESSELTYPE_PATH + "/" + vesselType.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body", notNullValue())) .andExpect(jsonPath("$.body.id", is(vesselType.getId()))); // @formatter:on } @Test public void searchVesselTypesPost_Return200_WhenSearchIsCorrect() throws Exception { SimpleQueryDTO dataQuery = new SimpleQueryDTO(); dataQuery.setSize(1); // @formatter:off this.mockMvc .perform(post(VESSELTYPE_PATH + "/_search").content(mapper.writeValueAsString(dataQuery)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body.data", notNullValue())) .andExpect(jsonPath("$.body.data[0]", notNullValue())) .andExpect(jsonPath("$.body.data.length()", is(1))) .andDo(getSimpleQueryFieldsDescriptor()); // @formatter:on } @Test public void searchVesselTypesQueryString_Return200_WhenSearchIsCorrect() throws Exception { // @formatter:off this.mockMvc .perform(get(VESSELTYPE_PATH) .param("fields", "{name}") .param("text", vesselType.getName()) .param("from", "0") .param("size", "1").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body.data", notNullValue())) .andExpect(jsonPath("$.body.data[0]", notNullValue())) .andExpect(jsonPath("$.body.data.length()", is(1))) .andDo(getSearchSimpleParametersDescription()); // @formatter:off } @Test public void mgetVesselTypes_Return200_WhenVesselTypesExists() throws Exception { MgetDTO mgetQuery = new MgetDTO(); mgetQuery.setIds(Arrays.asList(vesselType.getId())); mgetQuery.setFields(Arrays.asList("id")); // @formatter:off this.mockMvc .perform(post(VESSELTYPE_PATH + "/_mget").content(mapper.writeValueAsString(mgetQuery)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body.data", notNullValue())) .andExpect(jsonPath("$.body.data[0]", notNullValue())) .andExpect(jsonPath("$.body.data[0].id", is(vesselType.getId()))) .andExpect(jsonPath("$.body.data.length()", is(1))) .andDo(getMgetRequestDescription()); // @formatter:on } @Test public void suggestVesselTypesQueryString_Return200_WhenSuggestIsCorrect() throws Exception { // @formatter:off this.mockMvc .perform(get(VESSELTYPE_PATH + "/_suggest") .param("fields", new String[] { "name" }) .param("text", vesselType.getName()) .param("size", "1") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body", notNullValue())) .andExpect(jsonPath("$.body.length()", is(1))) .andExpect(jsonPath("$.body[0]", startsWith("<b>"))) .andExpect(jsonPath("$.body[0]", endsWith("</b>"))) .andDo(getSuggestParametersDescription()); // @formatter:on } @Test public void suggestVesselTypesPost_Return200_WhenSuggestIsCorrect() throws Exception { SimpleQueryDTO dataQuery = new SimpleQueryDTO(); dataQuery.setSize(1); dataQuery.createSimpleQueryDTOFromSuggestQueryParams(new String[] { "name" }, vesselType.getName(), 1); // @formatter:off this.mockMvc .perform(post(VESSELTYPE_PATH + "/_suggest").content(mapper.writeValueAsString(dataQuery)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body", notNullValue())) .andExpect(jsonPath("$.body.length()", is(1))) .andExpect(jsonPath("$.body[0]", startsWith("<b>"))) .andExpect(jsonPath("$.body[0]", endsWith("</b>"))) .andDo(getSimpleQueryFieldsDescriptor());; // @formatter:on } @SuppressWarnings("unchecked") @Test public void getFilterSchema_Return200_WhenSchemaIsAvailable() throws Exception { Map<String, Object> schemaExpected = (Map<String, Object>) JsonToBeanTestUtil .getBean("/data/schemas/vesseltypequeryschema.json", Map.class); // @formatter:off this.mockMvc.perform(get(VESSELTYPE_PATH + filterSchemaPath) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.success", is(true))) .andExpect(jsonPath("$.body", notNullValue())) .andExpect(jsonPath("$.body", notNullValue())) .andExpect(jsonPath("$.body", is(schemaExpected))); // @formatter:on } }
34.43346
106
0.743154
0cd1a588cb15c6c25b20ad284bf4935e53684e10
1,015
package com.ruoyi.project.erp.mrpPurchase.service; import com.ruoyi.project.erp.mrpPurchase.domain.MrpPurchase; import java.util.List; /** * mrp采购单关联 服务层 * * @author sj * @date 2019-06-26 */ public interface IMrpPurchaseService { /** * 查询mrp采购单关联信息 * * @param id mrp采购单关联ID * @return mrp采购单关联信息 */ public MrpPurchase selectMrpPurchaseById(Integer id); /** * 查询mrp采购单关联列表 * * @param mrpPurchase mrp采购单关联信息 * @return mrp采购单关联集合 */ public List<MrpPurchase> selectMrpPurchaseList(MrpPurchase mrpPurchase); /** * 新增mrp采购单关联 * * @param mrpPurchase mrp采购单关联信息 * @return 结果 */ public int insertMrpPurchase(MrpPurchase mrpPurchase); /** * 修改mrp采购单关联 * * @param mrpPurchase mrp采购单关联信息 * @return 结果 */ public int updateMrpPurchase(MrpPurchase mrpPurchase); /** * 删除mrp采购单关联信息 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteMrpPurchaseByIds(String ids); }
18.454545
73
0.639409
e6b1a07f4c1edc823beb1fe8d8fecf913a6bb893
6,539
package MathPackODE.Solvers; import MathPack.MatrixEqu; import MathPack.StringGraph; import MathPack.WorkSpace; import MathPackODE.Solver; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.lang.StrictMath.*; public class TRBDF extends Solver{ double[] xn, newtonF, fn, // dx/dt=f(xn)=fn fng, // dx/dt=f(xng)=fng fnn, xng; double[][] dF; double tolerance=1e-6, gamma=2.0-sqrt(2.0), hmax=1e-3, hmin=1e-16, // gamma=1, kGamma=(-3.0*gamma*gamma+4.0*gamma-2.0)/(12.0*(2.0-gamma)); @Override public void evalNextStep() { double t0=time.getValue(); time.set(t0+gamma*dt); // TR step estimJ(dF, null, fn, Xvector, null); // estimate d(d.X)/dX makeTRJ(dF); while(true){ trF(); double err = MatrixEqu.norm(newtonF); while (err > tolerance) { MatrixEqu.solveLU(dF, newtonF); // dF*deltaX=f0 for (int i = 0; i < diffRank; i++) { double val = Xvector.get(i).getValue() - newtonF[i]; Xvector.get(i).set(val); xng[i] = val; } evalSysState(); trF(); // eval F(X) err = MatrixEqu.norm(newtonF); if (err > tolerance) { // for (int i = 0; i < diffRank; i++) // del[i] *= -1.0; // // updateJ(dF, F, f0, del); // // del = Arrays.copyOf(F, diffRank); //update J estimJ(dF, null, fng, Xvector, null); // estimate d(d.X)/dX makeTRJ(dF); } else { break; } } time.set(t0+dt); // BDF2 step estimJ(dF, null, fng, Xvector, null); // estimate d(d.X)/dX makeBDFJ(dF); bdfF(); err = MatrixEqu.norm(newtonF); while (err > tolerance) { MatrixEqu.solveLU(dF, newtonF); // dF*deltaX=f0 for (int i = 0; i < diffRank; i++) { Xvector.get(i).set(Xvector.get(i).getValue() - newtonF[i]); } evalSysState(); bdfF(); // eval F(X) err = MatrixEqu.norm(newtonF); if (err > tolerance) { // for (int i = 0; i < diffRank; i++) // del[i] *= -1.0; // // updateJ(dF, F, f0, del); // // del = Arrays.copyOf(F, diffRank); //update J estimJ(dF, null, fng, Xvector, null); // estimate d(d.X)/dX makeBDFJ(dF); } else { break; } } //err err = 0; double norm = 0; for (int i = 0; i < diffRank; i++) { norm += xn[i] * xn[i]; double v = 2.0 * kGamma * dt * (1.0 / gamma * fn[i] - fng[i] / gamma / (1.0 - gamma) + fnn[i] / (1.0 - gamma)); err += v * v; } norm = sqrt(norm); err = sqrt(err); double r = err / (relTol * norm + 1e-6); if (r > 2) { dt /= 10.0; time.set(t0); if(dt<hmin){ throw new Error("Stepsize too small: "+dt+", at t="+t0); } for(int i=0;i<diffRank;i++){ Xvector.get(i).set(xn[i]); } //evalSysState(); // //update J estimJ(dF, null, fn, Xvector, null); // estimate d(d.X)/dX makeBDFJ(dF); } else { // dt/=max(pow(r,1.0/4.0),0.4); double temp = 1.25*pow(err/relTol,1.0/3.0); if (temp > 0.2) dt = dt / temp; else dt = 5.0*dt; dt=min(dt,hmax); break; } } copyArray(Xvector,xn); fn=Arrays.copyOf(fnn,diffRank); // if(!isErrnous) // evalSysState(); //time+=dt; } @Override protected void selfInit(){ xn=new double[diffRank]; xng=new double[diffRank]; copyArray(Xvector,xn); fn=new double[diffRank]; copyArray(dXvector,fn); fng=new double[diffRank]; fnn=new double[diffRank]; newtonF=new double[diffRank]; dF=new double[diffRank][diffRank]; } /** * fng=dXvector * xng=Xvector */ void trF(){ for (int i = 0; i < diffRank; i++) { fng[i]=dXvector.get(i).getValue(); newtonF[i] = (Xvector.get(i).getValue()-xn[i])-gamma*dt/2.0*(fng[i]+fn[i]); } } /** * x_(n+1)=Xvector */ void bdfF(){ for (int i = 0; i < diffRank; i++) { fnn[i]=dXvector.get(i).getValue(); newtonF[i] = (Xvector.get(i).getValue()-xng[i]/(gamma*(2.0-gamma))+xn[i]*(1.0-gamma)*(1.0-gamma)/gamma/(2.0-gamma)) -(1.0-gamma)/(2.0-gamma)*dt*fnn[i]; } } /** * Estimates d(d.X)/dX * @param J - output * @param fx - target function * @param f0 - function value at fx(x0) * @param x - x0 initial point * @param fac */ @Override protected void estimJ(double[][] J, List<StringGraph> fx, double[] f0, ArrayList<WorkSpace.Variable> x, double[] fac){ int ny=f0.length; for(int i=0;i<ny;i++){ double x0=x.get(i).getValue(), del=x0*1e-3; del=del==0?1e-6:del; x.get(i).set(x0+del); evalSysState(); for(int j=0;j<ny;j++){ J[j][i]=(dXvector.get(j).getValue()-f0[j])/del; } x.get(i).set(x0); } } private void makeTRJ(double[][] J){ for(int i=0;i<diffRank;i++){ for(int j=0;j<diffRank;j++){ double add=i==j?1.0:0.0; J[i][j]=add-gamma*dt/2.0*J[i][j]; } } } private void makeBDFJ(double[][] J){ for(int i=0;i<diffRank;i++){ for(int j=0;j<diffRank;j++){ double add=i==j?1.0:0.0; J[i][j]=add-(1.0-gamma)/(2.0-gamma)*dt*J[i][j]; } } } }
28.554585
127
0.419789
68003a124252e95d2d48d72c3ed2711851c7f95d
25,475
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.facebook.share.widget; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.facebook.FacebookCallback; import com.facebook.internal.AppCall; import com.facebook.internal.CallbackManagerImpl; import com.facebook.internal.DialogFeature; import com.facebook.internal.DialogPresenter; import com.facebook.internal.FacebookDialogBase; import com.facebook.internal.FragmentWrapper; import com.facebook.share.internal.AppInviteDialogFeature; import com.facebook.share.internal.ResultProcessor; import com.facebook.share.internal.ShareInternalUtility; import com.facebook.share.model.AppInviteContent; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public class AppInviteDialog extends FacebookDialogBase { private class NativeHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public boolean canShow(AppInviteContent appinvitecontent, boolean flag) { return false; // 0 0:iconst_0 // 1 1:ireturn } public volatile boolean canShow(Object obj, boolean flag) { return canShow((AppInviteContent)obj, flag); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #28 <Class AppInviteContent> // 3 5:iload_2 // 4 6:invokevirtual #30 <Method boolean canShow(AppInviteContent, boolean)> // 5 9:ireturn } public AppCall createAppCall(AppInviteContent appinvitecontent) { AppCall appcall = createBaseAppCall(); // 0 0:aload_0 // 1 1:getfield #16 <Field AppInviteDialog this$0> // 2 4:invokevirtual #36 <Method AppCall AppInviteDialog.createBaseAppCall()> // 3 7:astore_2 DialogPresenter.setupAppCallForNativeDialog(appcall, ((_cls1) (appinvitecontent)). new com.facebook.internal.DialogPresenter.ParameterProvider() { public Bundle getLegacyParameters() { Log.e("AppInviteDialog", "Attempting to present the AppInviteDialog with an outdated Facebook app on the device"); // 0 0:ldc1 #32 <String "AppInviteDialog"> // 1 2:ldc1 #34 <String "Attempting to present the AppInviteDialog with an outdated Facebook app on the device"> // 2 4:invokestatic #40 <Method int Log.e(String, String)> // 3 7:pop return new Bundle(); // 4 8:new #42 <Class Bundle> // 5 11:dup // 6 12:invokespecial #43 <Method void Bundle()> // 7 15:areturn } public Bundle getParameters() { return AppInviteDialog.createParameters(content); // 0 0:aload_0 // 1 1:getfield #24 <Field AppInviteContent val$content> // 2 4:invokestatic #48 <Method Bundle AppInviteDialog.access$200(AppInviteContent)> // 3 7:areturn } final NativeHandler this$1; final AppInviteContent val$content; { this$1 = final_nativehandler; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #22 <Field AppInviteDialog$NativeHandler this$1> content = AppInviteContent.this; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #24 <Field AppInviteContent val$content> super(); // 6 10:aload_0 // 7 11:invokespecial #27 <Method void Object()> // 8 14:return } } , AppInviteDialog.getFeature()); // 4 8:aload_2 // 5 9:new #10 <Class AppInviteDialog$NativeHandler$1> // 6 12:dup // 7 13:aload_0 // 8 14:aload_1 // 9 15:invokespecial #39 <Method void AppInviteDialog$NativeHandler$1(AppInviteDialog$NativeHandler, AppInviteContent)> // 10 18:invokestatic #43 <Method DialogFeature AppInviteDialog.access$300()> // 11 21:invokestatic #49 <Method void DialogPresenter.setupAppCallForNativeDialog(AppCall, com.facebook.internal.DialogPresenter$ParameterProvider, DialogFeature)> return appcall; // 12 24:aload_2 // 13 25:areturn } public volatile AppCall createAppCall(Object obj) { return createAppCall((AppInviteContent)obj); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #28 <Class AppInviteContent> // 3 5:invokevirtual #52 <Method AppCall createAppCall(AppInviteContent)> // 4 8:areturn } final AppInviteDialog this$0; private NativeHandler() { this$0 = AppInviteDialog.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #16 <Field AppInviteDialog this$0> super(((FacebookDialogBase) (AppInviteDialog.this))); // 3 5:aload_0 // 4 6:aload_1 // 5 7:invokespecial #19 <Method void com.facebook.internal.FacebookDialogBase$ModeHandler(FacebookDialogBase)> // 6 10:return } } public static final class Result { public Bundle getData() { return bundle; // 0 0:aload_0 // 1 1:getfield #17 <Field Bundle bundle> // 2 4:areturn } private final Bundle bundle; public Result(Bundle bundle1) { // 0 0:aload_0 // 1 1:invokespecial #15 <Method void Object()> bundle = bundle1; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #17 <Field Bundle bundle> // 5 9:return } } private class WebFallbackHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public boolean canShow(AppInviteContent appinvitecontent, boolean flag) { return false; // 0 0:iconst_0 // 1 1:ireturn } public volatile boolean canShow(Object obj, boolean flag) { return canShow((AppInviteContent)obj, flag); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #26 <Class AppInviteContent> // 3 5:iload_2 // 4 6:invokevirtual #28 <Method boolean canShow(AppInviteContent, boolean)> // 5 9:ireturn } public AppCall createAppCall(AppInviteContent appinvitecontent) { AppCall appcall = createBaseAppCall(); // 0 0:aload_0 // 1 1:getfield #14 <Field AppInviteDialog this$0> // 2 4:invokevirtual #34 <Method AppCall AppInviteDialog.createBaseAppCall()> // 3 7:astore_2 DialogPresenter.setupAppCallForWebFallbackDialog(appcall, AppInviteDialog.createParameters(appinvitecontent), AppInviteDialog.getFeature()); // 4 8:aload_2 // 5 9:aload_1 // 6 10:invokestatic #38 <Method Bundle AppInviteDialog.access$200(AppInviteContent)> // 7 13:invokestatic #42 <Method DialogFeature AppInviteDialog.access$300()> // 8 16:invokestatic #48 <Method void DialogPresenter.setupAppCallForWebFallbackDialog(AppCall, Bundle, DialogFeature)> return appcall; // 9 19:aload_2 // 10 20:areturn } public volatile AppCall createAppCall(Object obj) { return createAppCall((AppInviteContent)obj); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #26 <Class AppInviteContent> // 3 5:invokevirtual #51 <Method AppCall createAppCall(AppInviteContent)> // 4 8:areturn } final AppInviteDialog this$0; private WebFallbackHandler() { this$0 = AppInviteDialog.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #14 <Field AppInviteDialog this$0> super(((FacebookDialogBase) (AppInviteDialog.this))); // 3 5:aload_0 // 4 6:aload_1 // 5 7:invokespecial #17 <Method void com.facebook.internal.FacebookDialogBase$ModeHandler(FacebookDialogBase)> // 6 10:return } } public AppInviteDialog(Activity activity) { super(activity, DEFAULT_REQUEST_CODE); // 0 0:aload_0 // 1 1:aload_1 // 2 2:getstatic #41 <Field int DEFAULT_REQUEST_CODE> // 3 5:invokespecial #47 <Method void FacebookDialogBase(Activity, int)> // 4 8:return } public AppInviteDialog(Fragment fragment) { this(new FragmentWrapper(fragment)); // 0 0:aload_0 // 1 1:new #51 <Class FragmentWrapper> // 2 4:dup // 3 5:aload_1 // 4 6:invokespecial #53 <Method void FragmentWrapper(Fragment)> // 5 9:invokespecial #56 <Method void AppInviteDialog(FragmentWrapper)> // 6 12:return } public AppInviteDialog(android.support.v4.app.Fragment fragment) { this(new FragmentWrapper(fragment)); // 0 0:aload_0 // 1 1:new #51 <Class FragmentWrapper> // 2 4:dup // 3 5:aload_1 // 4 6:invokespecial #59 <Method void FragmentWrapper(android.support.v4.app.Fragment)> // 5 9:invokespecial #56 <Method void AppInviteDialog(FragmentWrapper)> // 6 12:return } private AppInviteDialog(FragmentWrapper fragmentwrapper) { super(fragmentwrapper, DEFAULT_REQUEST_CODE); // 0 0:aload_0 // 1 1:aload_1 // 2 2:getstatic #41 <Field int DEFAULT_REQUEST_CODE> // 3 5:invokespecial #62 <Method void FacebookDialogBase(FragmentWrapper, int)> // 4 8:return } public static boolean canShow() { return false; // 0 0:iconst_0 // 1 1:ireturn } private static boolean canShowNativeDialog() { return false; // 0 0:iconst_0 // 1 1:ireturn } private static boolean canShowWebFallback() { return false; // 0 0:iconst_0 // 1 1:ireturn } private static Bundle createParameters(AppInviteContent appinvitecontent) { String s; Bundle bundle; bundle = new Bundle(); // 0 0:new #80 <Class Bundle> // 1 3:dup // 2 4:invokespecial #82 <Method void Bundle()> // 3 7:astore_2 bundle.putString("app_link_url", appinvitecontent.getApplinkUrl()); // 4 8:aload_2 // 5 9:ldc1 #84 <String "app_link_url"> // 6 11:aload_0 // 7 12:invokevirtual #90 <Method String AppInviteContent.getApplinkUrl()> // 8 15:invokevirtual #94 <Method void Bundle.putString(String, String)> bundle.putString("preview_image_url", appinvitecontent.getPreviewImageUrl()); // 9 18:aload_2 // 10 19:ldc1 #96 <String "preview_image_url"> // 11 21:aload_0 // 12 22:invokevirtual #99 <Method String AppInviteContent.getPreviewImageUrl()> // 13 25:invokevirtual #94 <Method void Bundle.putString(String, String)> bundle.putString("destination", appinvitecontent.getDestination().toString()); // 14 28:aload_2 // 15 29:ldc1 #101 <String "destination"> // 16 31:aload_0 // 17 32:invokevirtual #105 <Method com.facebook.share.model.AppInviteContent$Builder$Destination AppInviteContent.getDestination()> // 18 35:invokevirtual #110 <Method String com.facebook.share.model.AppInviteContent$Builder$Destination.toString()> // 19 38:invokevirtual #94 <Method void Bundle.putString(String, String)> s = appinvitecontent.getPromotionCode(); // 20 41:aload_0 // 21 42:invokevirtual #113 <Method String AppInviteContent.getPromotionCode()> // 22 45:astore_1 if(s == null) //* 23 46:aload_1 //* 24 47:ifnull 53 //* 25 50:goto 56 s = ""; // 26 53:ldc1 #115 <String ""> // 27 55:astore_1 appinvitecontent = ((AppInviteContent) (appinvitecontent.getPromotionText())); // 28 56:aload_0 // 29 57:invokevirtual #118 <Method String AppInviteContent.getPromotionText()> // 30 60:astore_0 if(TextUtils.isEmpty(((CharSequence) (appinvitecontent)))) goto _L2; else goto _L1 // 31 61:aload_0 // 32 62:invokestatic #124 <Method boolean TextUtils.isEmpty(CharSequence)> // 33 65:ifne 126 _L1: JSONObject jsonobject = new JSONObject(); // 34 68:new #126 <Class JSONObject> // 35 71:dup // 36 72:invokespecial #127 <Method void JSONObject()> // 37 75:astore_3 jsonobject.put("promo_code", ((Object) (s))); // 38 76:aload_3 // 39 77:ldc1 #129 <String "promo_code"> // 40 79:aload_1 // 41 80:invokevirtual #133 <Method JSONObject JSONObject.put(String, Object)> // 42 83:pop jsonobject.put("promo_text", ((Object) (appinvitecontent))); // 43 84:aload_3 // 44 85:ldc1 #135 <String "promo_text"> // 45 87:aload_0 // 46 88:invokevirtual #133 <Method JSONObject JSONObject.put(String, Object)> // 47 91:pop bundle.putString("deeplink_context", jsonobject.toString()); // 48 92:aload_2 // 49 93:ldc1 #137 <String "deeplink_context"> // 50 95:aload_3 // 51 96:invokevirtual #138 <Method String JSONObject.toString()> // 52 99:invokevirtual #94 <Method void Bundle.putString(String, String)> bundle.putString("promo_code", s); // 53 102:aload_2 // 54 103:ldc1 #129 <String "promo_code"> // 55 105:aload_1 // 56 106:invokevirtual #94 <Method void Bundle.putString(String, String)> bundle.putString("promo_text", ((String) (appinvitecontent))); // 57 109:aload_2 // 58 110:ldc1 #135 <String "promo_text"> // 59 112:aload_0 // 60 113:invokevirtual #94 <Method void Bundle.putString(String, String)> return bundle; // 61 116:aload_2 // 62 117:areturn _L4: Log.e("AppInviteDialog", "Json Exception in creating deeplink context"); // 63 118:ldc1 #27 <String "AppInviteDialog"> // 64 120:ldc1 #140 <String "Json Exception in creating deeplink context"> // 65 122:invokestatic #146 <Method int Log.e(String, String)> // 66 125:pop _L2: return bundle; // 67 126:aload_2 // 68 127:areturn appinvitecontent; // 69 128:astore_0 if(true) goto _L4; else goto _L3 _L3: //* 70 129:goto 118 } private static DialogFeature getFeature() { return ((DialogFeature) (AppInviteDialogFeature.APP_INVITES_DIALOG)); // 0 0:getstatic #152 <Field AppInviteDialogFeature AppInviteDialogFeature.APP_INVITES_DIALOG> // 1 3:areturn } public static void show(Activity activity, AppInviteContent appinvitecontent) { (new AppInviteDialog(activity)).show(appinvitecontent); // 0 0:new #2 <Class AppInviteDialog> // 1 3:dup // 2 4:aload_0 // 3 5:invokespecial #156 <Method void AppInviteDialog(Activity)> // 4 8:aload_1 // 5 9:invokevirtual #159 <Method void show(AppInviteContent)> // 6 12:return } public static void show(Fragment fragment, AppInviteContent appinvitecontent) { show(new FragmentWrapper(fragment), appinvitecontent); // 0 0:new #51 <Class FragmentWrapper> // 1 3:dup // 2 4:aload_0 // 3 5:invokespecial #53 <Method void FragmentWrapper(Fragment)> // 4 8:aload_1 // 5 9:invokestatic #163 <Method void show(FragmentWrapper, AppInviteContent)> // 6 12:return } public static void show(android.support.v4.app.Fragment fragment, AppInviteContent appinvitecontent) { show(new FragmentWrapper(fragment), appinvitecontent); // 0 0:new #51 <Class FragmentWrapper> // 1 3:dup // 2 4:aload_0 // 3 5:invokespecial #59 <Method void FragmentWrapper(android.support.v4.app.Fragment)> // 4 8:aload_1 // 5 9:invokestatic #163 <Method void show(FragmentWrapper, AppInviteContent)> // 6 12:return } private static void show(FragmentWrapper fragmentwrapper, AppInviteContent appinvitecontent) { (new AppInviteDialog(fragmentwrapper)).show(appinvitecontent); // 0 0:new #2 <Class AppInviteDialog> // 1 3:dup // 2 4:aload_0 // 3 5:invokespecial #56 <Method void AppInviteDialog(FragmentWrapper)> // 4 8:aload_1 // 5 9:invokevirtual #159 <Method void show(AppInviteContent)> // 6 12:return } protected AppCall createBaseAppCall() { return new AppCall(getRequestCode()); // 0 0:new #168 <Class AppCall> // 1 3:dup // 2 4:aload_0 // 3 5:invokevirtual #171 <Method int getRequestCode()> // 4 8:invokespecial #174 <Method void AppCall(int)> // 5 11:areturn } protected List getOrderedModeHandlers() { ArrayList arraylist = new ArrayList(); // 0 0:new #178 <Class ArrayList> // 1 3:dup // 2 4:invokespecial #179 <Method void ArrayList()> // 3 7:astore_1 arraylist.add(((Object) (new NativeHandler()))); // 4 8:aload_1 // 5 9:new #11 <Class AppInviteDialog$NativeHandler> // 6 12:dup // 7 13:aload_0 // 8 14:aconst_null // 9 15:invokespecial #182 <Method void AppInviteDialog$NativeHandler(AppInviteDialog, AppInviteDialog$1)> // 10 18:invokevirtual #186 <Method boolean ArrayList.add(Object)> // 11 21:pop arraylist.add(((Object) (new WebFallbackHandler()))); // 12 22:aload_1 // 13 23:new #19 <Class AppInviteDialog$WebFallbackHandler> // 14 26:dup // 15 27:aload_0 // 16 28:aconst_null // 17 29:invokespecial #187 <Method void AppInviteDialog$WebFallbackHandler(AppInviteDialog, AppInviteDialog$1)> // 18 32:invokevirtual #186 <Method boolean ArrayList.add(Object)> // 19 35:pop return ((List) (arraylist)); // 20 36:aload_1 // 21 37:areturn } protected void registerCallbackImpl(CallbackManagerImpl callbackmanagerimpl, final FacebookCallback final_facebookcallback) { if(final_facebookcallback == null) //* 0 0:aload_2 //* 1 1:ifnonnull 9 final_facebookcallback = null; // 2 4:aconst_null // 3 5:astore_2 else //* 4 6:goto 20 final_facebookcallback = ((FacebookCallback) (new ResultProcessor(final_facebookcallback) { public void onSuccess(AppCall appcall, Bundle bundle) { if("cancel".equalsIgnoreCase(ShareInternalUtility.getNativeDialogCompletionGesture(bundle))) //* 0 0:ldc1 #27 <String "cancel"> //* 1 2:aload_2 //* 2 3:invokestatic #33 <Method String ShareInternalUtility.getNativeDialogCompletionGesture(Bundle)> //* 3 6:invokevirtual #39 <Method boolean String.equalsIgnoreCase(String)> //* 4 9:ifeq 22 { callback.onCancel(); // 5 12:aload_0 // 6 13:getfield #19 <Field FacebookCallback val$callback> // 7 16:invokeinterface #45 <Method void FacebookCallback.onCancel()> return; // 8 21:return } else { callback.onSuccess(((Object) (new Result(bundle)))); // 9 22:aload_0 // 10 23:getfield #19 <Field FacebookCallback val$callback> // 11 26:new #47 <Class AppInviteDialog$Result> // 12 29:dup // 13 30:aload_2 // 14 31:invokespecial #50 <Method void AppInviteDialog$Result(Bundle)> // 15 34:invokeinterface #53 <Method void FacebookCallback.onSuccess(Object)> return; // 16 39:return } } final AppInviteDialog this$0; final FacebookCallback val$callback; { this$0 = AppInviteDialog.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #17 <Field AppInviteDialog this$0> callback = facebookcallback1; // 3 5:aload_0 // 4 6:aload_3 // 5 7:putfield #19 <Field FacebookCallback val$callback> super(final_facebookcallback); // 6 10:aload_0 // 7 11:aload_2 // 8 12:invokespecial #22 <Method void ResultProcessor(FacebookCallback)> // 9 15:return } } )); // 5 9:new #7 <Class AppInviteDialog$1> // 6 12:dup // 7 13:aload_0 // 8 14:aload_2 // 9 15:aload_2 // 10 16:invokespecial #194 <Method void AppInviteDialog$1(AppInviteDialog, FacebookCallback, FacebookCallback)> // 11 19:astore_2 final_facebookcallback = ((FacebookCallback) (new com.facebook.internal.CallbackManagerImpl.Callback() { public boolean onActivityResult(int i, Intent intent) { return ShareInternalUtility.handleActivityResult(getRequestCode(), i, intent, resultProcessor); // 0 0:aload_0 // 1 1:getfield #19 <Field AppInviteDialog this$0> // 2 4:invokevirtual #31 <Method int AppInviteDialog.getRequestCode()> // 3 7:iload_1 // 4 8:aload_2 // 5 9:aload_0 // 6 10:getfield #21 <Field ResultProcessor val$resultProcessor> // 7 13:invokestatic #37 <Method boolean ShareInternalUtility.handleActivityResult(int, int, Intent, ResultProcessor)> // 8 16:ireturn } final AppInviteDialog this$0; final ResultProcessor val$resultProcessor; { this$0 = AppInviteDialog.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #19 <Field AppInviteDialog this$0> resultProcessor = resultprocessor; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #21 <Field ResultProcessor val$resultProcessor> super(); // 6 10:aload_0 // 7 11:invokespecial #24 <Method void Object()> // 8 14:return } } )); // 12 20:new #9 <Class AppInviteDialog$2> // 13 23:dup // 14 24:aload_0 // 15 25:aload_2 // 16 26:invokespecial #197 <Method void AppInviteDialog$2(AppInviteDialog, ResultProcessor)> // 17 29:astore_2 callbackmanagerimpl.registerCallback(getRequestCode(), ((com.facebook.internal.CallbackManagerImpl.Callback) (final_facebookcallback))); // 18 30:aload_1 // 19 31:aload_0 // 20 32:invokevirtual #171 <Method int getRequestCode()> // 21 35:aload_2 // 22 36:invokevirtual #203 <Method void CallbackManagerImpl.registerCallback(int, com.facebook.internal.CallbackManagerImpl$Callback)> // 23 39:return } public void show(AppInviteContent appinvitecontent) { // 0 0:return } public volatile void show(Object obj) { show((AppInviteContent)obj); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #86 <Class AppInviteContent> // 3 5:invokevirtual #159 <Method void show(AppInviteContent)> // 4 8:return } private static final int DEFAULT_REQUEST_CODE; private static final String TAG = "AppInviteDialog"; static { DEFAULT_REQUEST_CODE = com.facebook.internal.CallbackManagerImpl.RequestCodeOffset.AppInvite.toRequestCode(); // 0 0:getstatic #35 <Field com.facebook.internal.CallbackManagerImpl$RequestCodeOffset com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.AppInvite> // 1 3:invokevirtual #39 <Method int com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode()> // 2 6:putstatic #41 <Field int DEFAULT_REQUEST_CODE> //* 3 9:return } /* static Bundle access$200(AppInviteContent appinvitecontent) { return createParameters(appinvitecontent); // 0 0:aload_0 // 1 1:invokestatic #67 <Method Bundle createParameters(AppInviteContent)> // 2 4:areturn } */ /* static DialogFeature access$300() { return getFeature(); // 0 0:invokestatic #72 <Method DialogFeature getFeature()> // 1 3:areturn } */ }
38.079223
174
0.590815
a68de26d9e41b52984c21d8104df5d027b8bf524
4,038
package ai.mozark.devices.utils.aws; import ai.mozark.devices.util.RestUtil; import com.amazonaws.services.devicefarm.AWSDeviceFarm; import com.amazonaws.services.devicefarm.model.DeviceFilter; import com.amazonaws.services.devicefarm.model.ListDevicesRequest; import com.amazonaws.services.devicefarm.model.ListDevicesResult; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List; public class DeviceUtils { private static AWSDeviceFarm client = MyAwsClient.getClient(); RestUtil restUtil = new RestUtil(); public JSONArray listDevices1(String platform) { try { List<DeviceFilter> filters = new ArrayList<DeviceFilter>(); DeviceFilter filter = new DeviceFilter(); filter.setAttribute("AVAILABILITY"); filter.setOperator("EQUALS"); List<String> avaialbilityList = new ArrayList<String>(); avaialbilityList.add("AVAILABLE"); avaialbilityList.add("HIGHLY_AVAILABLE"); filter.setValues(avaialbilityList); filters.add(filter); filter = new DeviceFilter(); filter.setAttribute("PLATFORM"); filter.setOperator("EQUALS"); avaialbilityList = new ArrayList<String>(); avaialbilityList.add(platform); filter.setValues(avaialbilityList); filters.add(filter); ListDevicesRequest request = new ListDevicesRequest().withFilters(filters); ListDevicesResult result = client.listDevices(request); JSONArray array = new JSONArray(); array.add(result); JSONObject projectListObj = array.getJSONObject(0); JSONArray deviceArray = projectListObj.getJSONArray("devices"); // System.out.println(deviceArray); return deviceArray; }catch (Exception e) { e.printStackTrace(); return null; } } public JSONArray listDevices() { //String platform,String os,String name try { List<DeviceFilter> filters = new ArrayList<DeviceFilter>(); DeviceFilter filter = new DeviceFilter(); List<String> avaialbilityList = new ArrayList<String>(); /* if(!restUtil.isEmpty(platform)) { filter = new DeviceFilter(); filter.setAttribute("PLATFORM"); filter.setOperator("EQUALS"); avaialbilityList = new ArrayList<String>(); avaialbilityList.add(platform); filter.setValues(avaialbilityList); filters.add(filter); } if(!restUtil.isEmpty(os)) { filter = new DeviceFilter(); filter.setAttribute("OS_VERSION"); filter.setOperator("GREATER_THAN_OR_EQUALS"); avaialbilityList = new ArrayList<String>(); avaialbilityList.add(os); filter.setValues(avaialbilityList); filters.add(filter); } if(!restUtil.isEmpty(name)) { filter = new DeviceFilter(); filter.setAttribute("MODEL"); filter.setOperator("CONTAINS"); avaialbilityList = new ArrayList<String>(); avaialbilityList.add(name); filter.setValues(avaialbilityList); filters.add(filter); } */ ListDevicesRequest request = new ListDevicesRequest() ; // .withFilters(filters); ListDevicesResult result = client.listDevices(request); JSONArray array = new JSONArray(); array.add(result); JSONObject projectListObj = array.getJSONObject(0); JSONArray deviceArray = projectListObj.getJSONArray("devices"); // System.out.println(deviceArray); return deviceArray; }catch (Exception e) { e.printStackTrace(); return null; } } }
39.203883
87
0.603517
55350a724742b596a05e486748d6246183c781d5
5,193
/* * The MIT License * * Copyright 2016 Volchkov Andrey. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.wolf.wljglplayground.object; import org.joml.Vector2f; import org.joml.Vector3f; /** * * @author Volchkov Andrey */ public class BoxMesh extends AbstractProceduralMesh { private final float length; private final float width; private final float height; public BoxMesh(float length, float width, float height) { this.length = length; this.width = width; this.height = height; } /** * Create cube 1.0f */ public BoxMesh() { this(1.0f, 1.0f, 1.0f); } @Override protected Vector3f[] generateVertices() { //create vertices Vector3f p0 = new Vector3f(-length * 0.5f, -width * 0.5f, height * 0.5f); Vector3f p1 = new Vector3f(length * 0.5f, -width * 0.5f, height * 0.5f); Vector3f p2 = new Vector3f(length * 0.5f, -width * 0.5f, -height * 0.5f); Vector3f p3 = new Vector3f(-length * 0.5f, -width * 0.5f, -height * 0.5f); Vector3f p4 = new Vector3f(-length * 0.5f, width * 0.5f, height * 0.5f); Vector3f p5 = new Vector3f(length * 0.5f, width * 0.5f, height * 0.5f); Vector3f p6 = new Vector3f(length * 0.5f, width * 0.5f, -height * 0.5f); Vector3f p7 = new Vector3f(-length * 0.5f, width * 0.5f, -height * 0.5f); Vector3f[] vertices = new Vector3f[]{ //bottom p0, p1, p2, p3, //left p7, p4, p0, p3, //front p4, p5, p1, p0, //back p6, p7, p3, p2, //right p5, p6, p2, p1, //top p7, p6, p5, p4 }; return vertices; } @Override protected Vector3f[] generateNormals(Vector3f[] vertices) { //create normales Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f); Vector3f down = new Vector3f(0.0f, -1.0f, 0.0f); Vector3f front = new Vector3f(0.0f, 0.0f, 1.0f); Vector3f back = new Vector3f(0.0f, 0.0f, -1.0f); Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f); Vector3f right = new Vector3f(1.0f, 0.0f, 0.0f); Vector3f[] normales = new Vector3f[]{ //bottom down, down, down, down, //left left, left, left, left, //front front, front, front, front, //back back, back, back, back, //right right, right, right, right, //top up, up, up, up }; return normales; } @Override protected Vector2f[] generateUVs(int length) { Vector2f c00 = new Vector2f(0.0f, 0.0f); Vector2f c10 = new Vector2f(1.0f, 0.0f); Vector2f c01 = new Vector2f(0.0f, 1.0f); Vector2f c11 = new Vector2f(1.0f, 1.0f); Vector2f[] uvs = new Vector2f[]{ //bottom c11, c01, c00, c10, //left c11, c01, c00, c10, //front c11, c01, c00, c10, //back c11, c01, c00, c10, //right c11, c01, c00, c10, //top c11, c01, c00, c10 }; return uvs; } @Override protected int[] createTrianglesIndexes(int length) { return new int[]{ // Bottom 3, 1, 0, 3, 2, 1, // Left 3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1, 3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1, // Front 3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2, 3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2, // Back 3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3, 3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3, // Right 3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4, 3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4, // Top 3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5, 3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5 }; } }
33.288462
83
0.511073
ee643b23cc039c90d0a4fb0cad13cac1f7e0a00d
7,638
/* * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ package com.sun.hotspot.igv.coordinator.actions; import com.sun.hotspot.igv.coordinator.OutlineTopComponent; import com.sun.hotspot.igv.data.GraphDocument; import com.sun.hotspot.igv.data.serialization.BinaryParser; import com.sun.hotspot.igv.data.serialization.GraphParser; import com.sun.hotspot.igv.data.serialization.ParseMonitor; import com.sun.hotspot.igv.data.serialization.Parser; import com.sun.hotspot.igv.settings.Settings; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.openide.util.Exceptions; import org.openide.util.RequestProcessor; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.util.actions.SystemAction; /** * * @author Thomas Wuerthinger */ @ActionID( category = "File", id = "com.sun.hotspot.igv.coordinator.actions.ImportAction" ) @ActionRegistration( iconBase = "com/sun/hotspot/igv/coordinator/images/import.png", displayName = "#CTL_ImportAction" ) @ActionReferences({ @ActionReference(path = "Menu/File", position = 0), @ActionReference(path = "Shortcuts", name = "C-O") }) public final class ImportAction extends SystemAction { private static final int WORKUNITS = 10000; public static FileFilter getFileFilter() { return new FileFilter() { @Override public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".xml") || f.getName().toLowerCase().endsWith(".bgv") || f.isDirectory(); } @Override public String getDescription() { return "Graph files (*.xml, *.bgv)"; } }; } @Override public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ImportAction.getFileFilter()); fc.setCurrentDirectory(new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT))); fc.setMultiSelectionEnabled(true); if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { for (final File file : fc.getSelectedFiles()) { File dir = file; if (!dir.isDirectory()) { dir = dir.getParentFile(); } Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath()); try { final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ); final ProgressHandle handle = ProgressHandleFactory.createHandle("Opening file " + file.getName()); handle.start(WORKUNITS); final long startTime = System.currentTimeMillis(); final long start = channel.size(); ParseMonitor monitor = new ParseMonitor() { @Override public void updateProgress() { try { int prog = (int) (WORKUNITS * (double) channel.position() / (double) start); handle.progress(prog); } catch (IOException ex) { } } @Override public void setState(String state) { updateProgress(); handle.progress(state); } }; final GraphParser parser; final OutlineTopComponent component = OutlineTopComponent.findInstance(); if (file.getName().endsWith(".xml")) { parser = new Parser(channel, monitor, null); } else if (file.getName().endsWith(".bgv")) { parser = new BinaryParser(channel, monitor, component.getDocument(), null); } else { parser = null; } RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { try { final GraphDocument document = parser.parse(); if (document != null) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { component.requestActive(); component.getDocument().addGraphDocument(document); } }); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } handle.finish(); long stop = System.currentTimeMillis(); Logger.getLogger(getClass().getName()).log(Level.INFO, "Loaded in " + file + " in " + ((stop - startTime) / 1000.0) + " seconds"); } }); } catch (FileNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } } } @Override public String getName() { return NbBundle.getMessage(ImportAction.class, "CTL_ImportAction"); } @Override protected String iconResource() { return "com/sun/hotspot/igv/coordinator/images/import.png"; } @Override public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } }
41.737705
162
0.559963
a31917f72872dfddd88f7d05de657b39493a1a11
736
package cliporama; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.*; import javafx.stage.Stage; @SuppressWarnings("restriction") public class Main extends Application { public static void main(String[] args) { launch(args); } /** * Lance le cadre de l'interface JAVAFX */ @Override public void start(Stage primaryStage) { Parent root; try { root = FXMLLoader.load(getClass().getResource("Lanceur.fxml")); //Charge l'interface } catch (Exception e) { e.printStackTrace(); return; } Scene scene = new Scene(root); //Permet la création de la fenetre contenant l'interface primaryStage.setScene(scene); primaryStage.sizeToScene(); primaryStage.show(); } }
22.30303
89
0.721467
0e8dd9e14855e44ce508fe9475e1254bd141d95c
550
package exemplo12.polimorfismo; import java.util.ArrayList; import java.util.List; public class TestaTocadorBarulho { public static void main(String[] args) { TocadorDeBarulho t = new TocadorDeBarulho(); List<Barulhento> lista = new ArrayList<>(); lista.add(new Carro()); lista.add(new Carro()); lista.add(new Gato()); lista.add(new Carro()); lista.add(new Gato()); lista.add(new Carro()); lista.add(new ArCondicionado()); //Os objetos tomam formas diferentes for (Barulhento b : lista){ t.play(b); } } }
18.965517
46
0.672727
f2595b04ed3fe7bed0cd37c431e160b2cbdc6654
56
/** * 描画用クラスのあるパッケージ */ package densan.s.game.drawing;
14
30
0.696429
4003278e290ad7151c4bc16ec8330a5955558655
7,230
package jadx.gui.ui.codearea; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.swing.*; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.data.annotations.VarDeclareRef; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.MethodNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JMethod; import jadx.gui.treemodel.JNode; import jadx.gui.utils.NLS; import static javax.swing.KeyStroke.getKeyStroke; public final class FridaAction extends JNodeMenuAction<JNode> { private static final Logger LOG = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private static final long serialVersionUID = 4692546569977976384L; private Map<String, Boolean> isInitial = new HashMap<>(); private String methodName; public FridaAction(CodeArea codeArea) { super(NLS.str("popup.frida") + " (f)", codeArea); LOG.info("triggered meee"); KeyStroke key = getKeyStroke(KeyEvent.VK_F, 0); codeArea.getInputMap().put(key, "trigger frida"); codeArea.getActionMap().put("trigger frida", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { node = getNodeByOffset(codeArea.getWordStart(codeArea.getCaretPosition())); copyFridaCode(); } }); } private void copyFridaCode() { if (node != null) { if (node instanceof JMethod) { JMethod n = (JMethod) node; MethodNode methodNode = n.getJavaMethod().getMethodNode(); MethodInfo mi = methodNode.getMethodInfo(); methodName = mi.getName(); if (methodName.equals("<init>") || methodName.equals("onCreate")) { methodName = "$init"; } String fullClassName = methodNode.getParentClass().getFullName(); String className = methodNode.getParentClass().getShortName(); LOG.debug("node is jmethod"); ClassNode tmp = methodNode.getParentClass(); while (true) { if (!tmp.isTopClass()) { fullClassName = fullClassName.substring(0, fullClassName.lastIndexOf(".")) + "$" + fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length()); } else { break; } tmp = tmp.getParentClass(); } JMethod jMth = (JMethod) node; int mthLine = jMth.getLine(); List<String> argNames = jMth.getRootClass().getCodeInfo().getAnnotations().entrySet().stream() .filter(e -> e.getKey().getLine() == mthLine && e.getValue() instanceof VarDeclareRef) .sorted(Comparator.comparingInt(e -> e.getKey().getPos())) .map(e -> ((VarDeclareRef) e.getValue()).getName()) .collect(Collectors.toList()); StringBuilder functionParameters = new StringBuilder(); for (String argName : argNames) { functionParameters.append(argName + ", "); } if (functionParameters.toString().length() > 2) { functionParameters.setLength(functionParameters.length() - 2); } List<MethodNode> methods = methodNode.getParentClass().getMethods(); List<MethodNode> filteredmethod = methods.stream().filter(m -> m.getName().equals(methodName)).collect(Collectors.toList()); StringBuilder sb = new StringBuilder(); String overloadStr = ""; if (filteredmethod.size() > 1) { List<ArgType> methodArgs = mi.getArgumentsTypes(); for (ArgType argType : methodArgs) { sb.append("'" + parseArgType(argType) + "', "); } if (sb.length() > 2) { sb.setLength(sb.length() - 2); } overloadStr = sb.toString(); } String functionUntilImplementation = ""; if (!overloadStr.equals("")) { functionUntilImplementation = String.format("%s.%s.overload(%s).implementation", className, methodName, overloadStr); } else { functionUntilImplementation = String.format("%s.%s.implementation", className, methodName); } String functionParameterAndBody = ""; String functionParametersString = functionParameters.toString(); if (!functionParametersString.equals("")) { functionParameterAndBody = String.format( "%s = function(%s){\n\tconsole.log('%s is called')\n\tlet ret = this.%s(%s)\n\tconsole.log('%s ret value is ' + ret)\n\treturn ret\n}", functionUntilImplementation, functionParametersString, methodName, methodName, functionParametersString, methodName); } else { functionParameterAndBody = String.format( "%s = function(){\n\tconsole.log('%s is called')\n\tlet ret = this.%s()\n\tconsole.log('%s ret value is ' + ret)\n\treturn ret\n}", functionUntilImplementation, methodName, methodName, methodName); } String finalFridaCode = ""; if (isInitial.getOrDefault(fullClassName, true)) { finalFridaCode = String.format("let %s = Java.use(\"%s\")\n%s", className, fullClassName, functionParameterAndBody); isInitial.put(fullClassName, false); } else { finalFridaCode = functionParameterAndBody; } LOG.debug("frida code : " + finalFridaCode); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection selection = new StringSelection(finalFridaCode); clipboard.setContents(selection, selection); } else if (node instanceof JClass) { LOG.debug("node is jclass"); JClass jc = (JClass) node; String fullClassName = jc.getCls().getClassNode().getClassInfo().getFullName(); String className = jc.getCls().getClassNode().getClassInfo().getShortName(); ClassNode tmp = jc.getCls().getClassNode(); while (true) { if (!tmp.isTopClass()) { fullClassName = fullClassName.substring(0, fullClassName.lastIndexOf(".")) + "$" + fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length()); } else { break; } tmp = tmp.getParentClass(); } String finalFridaCode = String.format("let %s = Java.use(\"%s\")", className, fullClassName); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection selection = new StringSelection(finalFridaCode); clipboard.setContents(selection, selection); LOG.debug("frida code : " + finalFridaCode); isInitial.put(fullClassName, false); } else { LOG.debug("node is something else"); } } } private String parseArgType(ArgType x) { StringBuilder parsedArgType = new StringBuilder(); if (x.isArray()) { parsedArgType.append(x.getPrimitiveType().getShortName()); parsedArgType.append(x.getArrayElement().getPrimitiveType().getShortName()); if (!x.getArrayElement().isPrimitive()) { parsedArgType.append(x.getArrayElement().toString() + ";"); } } else { parsedArgType.append(x.toString()); } return parsedArgType.toString(); } @Override public void actionPerformed(ActionEvent e) { node = codeArea.getNodeUnderCaret(); copyFridaCode(); } @Nullable @Override public JNode getNodeByOffset(int offset) { return codeArea.getJNodeAtOffset(offset); } }
37.268041
142
0.697925
4da5d66a7945998a0a06bc5e67b4ec5874912cec
3,401
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.analysis.phonetic; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.language.DaitchMokotoffSoundex; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; /** * Create tokens for phonetic matches based on Daitch–Mokotoff Soundex. * * @lucene.experimental */ public final class DaitchMokotoffSoundexFilter extends TokenFilter { /** true if encoded tokens should be added as synonyms */ protected boolean inject = true; /** phonetic encoder */ protected DaitchMokotoffSoundex encoder = new DaitchMokotoffSoundex(); // output is a string such as ab|ac|... private static final Pattern pattern = Pattern.compile("([^|]+)"); // matcher over any buffered output private final Matcher matcher = pattern.matcher(""); // encoded representation private String encoded; // preserves all attributes for any buffered outputs private State state; private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); private final PositionIncrementAttribute posAtt = addAttribute(PositionIncrementAttribute.class); /** * Creates a DaitchMokotoffSoundexFilter by either adding encoded forms as synonyms ( * <code>inject=true</code>) or replacing them. */ public DaitchMokotoffSoundexFilter(TokenStream in, boolean inject) { super(in); this.inject = inject; } @Override public boolean incrementToken() throws IOException { if (matcher.find()) { assert state != null && encoded != null; restoreState(state); termAtt.setEmpty().append(encoded, matcher.start(1), matcher.end(1)); posAtt.setPositionIncrement(0); return true; } if (input.incrementToken()) { // pass through zero-length terms if (termAtt.length() == 0) { return true; } encoded = encoder.soundex(termAtt.toString()); state = captureState(); matcher.reset(encoded); if (!inject) { if (matcher.find()) { termAtt.setEmpty().append(encoded, matcher.start(1), matcher.end(1)); } } return true; } else { return false; } } @Override public void reset() throws IOException { super.reset(); matcher.reset(""); state = null; } }
33.673267
100
0.694502
e6e05ea764c16194e110c205ceb74214d0aa6a4d
496
package com.zhuwj.dict.service.impl; import com.zhuwj.dict.entity.DictDetail; import com.zhuwj.dict.mapper.DictDetailMapper; import com.zhuwj.dict.service.DictDetailService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 基础表 服务实现类 * </p> * * @author zhuwj * @since 2020-05-24 */ @Service public class DictDetailServiceImpl extends ServiceImpl<DictDetailMapper, DictDetail> implements DictDetailService { }
23.619048
115
0.78629
371680e7665391622dbcb4dcec62a623408651aa
1,199
package buildingOrderModule.stateFactories.actions.executableActions; import buildingOrderModule.scoringDirector.gameState.GameState; import buildingOrderModule.simulator.TypeWrapper; import bwapi.UnitType; /** * TrainUnitActionTerran_Wraith.java --- Class for training a Terran_Wraith. * * @author P H - 19.09.2017 * */ public class TrainUnitActionTerran_Wraith extends TrainUnitBaseAction { /** * @param target * type: Integer */ public TrainUnitActionTerran_Wraith(Object target) { super(target); this.addToGameStates(GameState.Mineral_Units); this.addToGameStates(GameState.Gas_Units); this.addToGameStates(GameState.Expensive_Units); this.addToGameStates(GameState.Combat_Units); this.addToGameStates(GameState.Flying_Units); this.addToGameStates(GameState.FreeTrainingFacility_Terran_Starport); this.addToGameStates(GameState.SpecificUnit_Terran_Wraith); } // -------------------- Functions @Override public TypeWrapper defineRequiredType() { return TypeWrapper.generateFrom(UnitType.Terran_Starport); } @Override protected UnitType defineType() { return UnitType.Terran_Wraith; } }
26.065217
77
0.744787
f705819ec6dee851371a75445b38e3cc4b337788
16,879
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.editor; import android.content.Context; import android.graphics.Rect; import android.os.Parcel; import android.os.Parcelable; import android.provider.ContactsContract; import android.text.Editable; import android.text.InputType; import android.text.Spannable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.TtsSpan; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import com.android.contacts.R; import com.android.contacts.common.model.RawContactDelta; import com.android.contacts.common.compat.PhoneNumberUtilsCompat; import com.android.contacts.common.ContactsUtils; import com.android.contacts.common.model.ValuesDelta; import com.android.contacts.common.model.account.AccountType.EditField; import com.android.contacts.common.model.dataitem.DataKind; import com.android.contacts.common.util.PhoneNumberFormatter; /** * Simple editor that handles labels and any {@link EditField} defined for the * entry. Uses {@link ValuesDelta} to read any existing {@link RawContact} values, * and to correctly write any changes values. */ public class TextFieldsEditorView extends LabeledEditorView { private static final String TAG = TextFieldsEditorView.class.getSimpleName(); private EditText[] mFieldEditTexts = null; private ViewGroup mFields = null; private View mExpansionViewContainer; private ImageView mExpansionView; private boolean mHideOptional = true; private boolean mHasShortAndLongForms; private int mMinFieldHeight; private int mPreviousViewHeight; private int mHintTextColorUnfocused; public TextFieldsEditorView(Context context) { super(context); } public TextFieldsEditorView(Context context, AttributeSet attrs) { super(context, attrs); } public TextFieldsEditorView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** {@inheritDoc} */ @Override protected void onFinishInflate() { super.onFinishInflate(); setDrawingCacheEnabled(true); setAlwaysDrawnWithCacheEnabled(true); mMinFieldHeight = getContext().getResources().getDimensionPixelSize( R.dimen.editor_min_line_item_height); mFields = (ViewGroup) findViewById(R.id.editors); mHintTextColorUnfocused = getResources().getColor(R.color.editor_disabled_text_color); mExpansionView = (ImageView) findViewById(R.id.expansion_view); mExpansionViewContainer = findViewById(R.id.expansion_view_container); if (mExpansionViewContainer != null) { mExpansionViewContainer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPreviousViewHeight = mFields.getHeight(); // Save focus final View focusedChild = getFocusedChild(); final int focusedViewId = focusedChild == null ? -1 : focusedChild.getId(); // Reconfigure GUI mHideOptional = !mHideOptional; onOptionalFieldVisibilityChange(); rebuildValues(); // Restore focus View newFocusView = findViewById(focusedViewId); if (newFocusView == null || newFocusView.getVisibility() == GONE) { // find first visible child newFocusView = TextFieldsEditorView.this; } newFocusView.requestFocus(); EditorAnimator.getInstance().slideAndFadeIn(mFields, mPreviousViewHeight); } }); } } @Override public void editNewlyAddedField() { // Some editors may have multiple fields (eg: first-name/last-name), but since the user // has not selected a particular one, it is reasonable to simply pick the first. final View editor = mFields.getChildAt(0); // Show the soft-keyboard. InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { if (!imm.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)) { Log.w(TAG, "Failed to show soft input method."); } } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (mFieldEditTexts != null) { for (int index = 0; index < mFieldEditTexts.length; index++) { mFieldEditTexts[index].setEnabled(!isReadOnly() && enabled); } } if (mExpansionView != null) { mExpansionView.setEnabled(!isReadOnly() && enabled); } } private OnFocusChangeListener mTextFocusChangeListener = new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (getEditorListener() != null) { getEditorListener().onRequest(EditorListener.EDITOR_FOCUS_CHANGED); } // Rebuild the label spinner using the new colors. rebuildLabel(); } }; /** * Creates or removes the type/label button. Doesn't do anything if already correctly configured */ private void setupExpansionView(boolean shouldExist, boolean collapsed) { mExpansionView.setImageResource(collapsed ? R.drawable.ic_menu_expander_minimized_holo_light : R.drawable.ic_menu_expander_maximized_holo_light); mExpansionViewContainer.setVisibility(shouldExist ? View.VISIBLE : View.INVISIBLE); } @Override protected void requestFocusForFirstEditField() { if (mFieldEditTexts != null && mFieldEditTexts.length != 0) { EditText firstField = null; boolean anyFieldHasFocus = false; for (EditText editText : mFieldEditTexts) { if (firstField == null && editText.getVisibility() == View.VISIBLE) { firstField = editText; } if (editText.hasFocus()) { anyFieldHasFocus = true; break; } } if (!anyFieldHasFocus && firstField != null) { firstField.requestFocus(); } } } public void setValue(int field, String value) { mFieldEditTexts[field].setText(value); } @Override public void setValues(DataKind kind, ValuesDelta entry, RawContactDelta state, boolean readOnly, ViewIdGenerator vig) { super.setValues(kind, entry, state, readOnly, vig); // Remove edit texts that we currently have if (mFieldEditTexts != null) { for (EditText fieldEditText : mFieldEditTexts) { mFields.removeView(fieldEditText); } } boolean hidePossible = false; int fieldCount = kind.fieldList == null ? 0 : kind.fieldList.size(); mFieldEditTexts = new EditText[fieldCount]; for (int index = 0; index < fieldCount; index++) { final EditField field = kind.fieldList.get(index); final EditText fieldView = new EditText(getContext()); fieldView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); fieldView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.editor_form_text_size)); fieldView.setHintTextColor(mHintTextColorUnfocused); mFieldEditTexts[index] = fieldView; fieldView.setId(vig.getId(state, kind, entry, index)); if (field.titleRes > 0) { fieldView.setHint(field.titleRes); } int inputType = field.inputType; fieldView.setInputType(inputType); if (inputType == InputType.TYPE_CLASS_PHONE) { PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher( getContext(), fieldView, /* formatAfterWatcherSet =*/ false); fieldView.setTextDirection(View.TEXT_DIRECTION_LTR); } fieldView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); // Set either a minimum line requirement or a minimum height (because {@link TextView} // only takes one or the other at a single time). if (field.minLines > 1) { fieldView.setMinLines(field.minLines); } else { // This needs to be called after setInputType. Otherwise, calling setInputType // will unset this value. fieldView.setMinHeight(mMinFieldHeight); } // Show the "next" button in IME to navigate between text fields // TODO: Still need to properly navigate to/from sections without text fields, // See Bug: 5713510 fieldView.setImeOptions(EditorInfo.IME_ACTION_NEXT); // Read current value from state final String column = field.column; final String value = entry.getAsString(column); if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(kind.mimeType)) { fieldView.setText(PhoneNumberUtilsCompat.createTtsSpannable(value)); } else { fieldView.setText(value); } // Show the delete button if we have a non-empty value setDeleteButtonVisible(!TextUtils.isEmpty(value)); // Prepare listener for writing changes fieldView.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { // Trigger event for newly changed value onFieldChanged(column, s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals( getKind().mimeType) || !(s instanceof Spannable)) { return; } final Spannable spannable = (Spannable) s; final TtsSpan[] spans = spannable.getSpans(0, s.length(), TtsSpan.class); for (int i = 0; i < spans.length; i++) { spannable.removeSpan(spans[i]); } PhoneNumberUtilsCompat.addTtsSpan(spannable, 0, s.length()); } }); fieldView.setEnabled(isEnabled() && !readOnly); fieldView.setOnFocusChangeListener(mTextFocusChangeListener); if (field.shortForm) { hidePossible = true; mHasShortAndLongForms = true; fieldView.setVisibility(mHideOptional ? View.VISIBLE : View.GONE); } else if (field.longForm) { hidePossible = true; mHasShortAndLongForms = true; fieldView.setVisibility(mHideOptional ? View.GONE : View.VISIBLE); } else { // Hide field when empty and optional value final boolean couldHide = (!ContactsUtils.isGraphic(value) && field.optional); final boolean willHide = (mHideOptional && couldHide); fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE); hidePossible = hidePossible || couldHide; } mFields.addView(fieldView); } if (mExpansionView != null) { // When hiding fields, place expandable setupExpansionView(hidePossible, mHideOptional); mExpansionView.setEnabled(!readOnly && isEnabled()); } updateEmptiness(); } @Override public boolean isEmpty() { for (int i = 0; i < mFields.getChildCount(); i++) { EditText editText = (EditText) mFields.getChildAt(i); if (!TextUtils.isEmpty(editText.getText())) { return false; } } return true; } /** * Returns true if the editor is currently configured to show optional fields. */ public boolean areOptionalFieldsVisible() { return !mHideOptional; } public boolean hasShortAndLongForms() { return mHasShortAndLongForms; } /** * Populates the bound rectangle with the bounds of the last editor field inside this view. */ public void acquireEditorBounds(Rect bounds) { if (mFieldEditTexts != null) { for (int i = mFieldEditTexts.length; --i >= 0;) { EditText editText = mFieldEditTexts[i]; if (editText.getVisibility() == View.VISIBLE) { bounds.set(editText.getLeft(), editText.getTop(), editText.getRight(), editText.getBottom()); return; } } } } /** * Saves the visibility of the child EditTexts, and mHideOptional. */ @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.mHideOptional = mHideOptional; final int numChildren = mFieldEditTexts == null ? 0 : mFieldEditTexts.length; ss.mVisibilities = new int[numChildren]; for (int i = 0; i < numChildren; i++) { ss.mVisibilities[i] = mFieldEditTexts[i].getVisibility(); } return ss; } /** * Restores the visibility of the child EditTexts, and mHideOptional. */ @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mHideOptional = ss.mHideOptional; int numChildren = Math.min(mFieldEditTexts == null ? 0 : mFieldEditTexts.length, ss.mVisibilities == null ? 0 : ss.mVisibilities.length); for (int i = 0; i < numChildren; i++) { mFieldEditTexts[i].setVisibility(ss.mVisibilities[i]); } } private static class SavedState extends BaseSavedState { public boolean mHideOptional; public int[] mVisibilities; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); mVisibilities = new int[in.readInt()]; in.readIntArray(mVisibilities); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mVisibilities.length); out.writeIntArray(mVisibilities); } @SuppressWarnings({"unused", "hiding" }) public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public void clearAllFields() { if (mFieldEditTexts != null) { for (EditText fieldEditText : mFieldEditTexts) { // Update UI (which will trigger a state change through the {@link TextWatcher}) fieldEditText.setText(""); } } } }
38.53653
100
0.612062
fc2cfc98abd52b1391d3637e947558f3df06ce7e
1,498
package com.tomekl007.chapter_5; import org.junit.Ignore; import org.junit.Test; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; public class ExecutorServiceParameters { @Test @Ignore("saturate ") public void should_start_computations_and_saturate_executor() { //given ExecutorService executorService = Executors.newSingleThreadExecutor(); //when while (true) { executorService.submit(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { } }); } //then will fail with out-of-memory because queue is saturated } @Test public void should_reject_task_if_queue_is_full() { //given ExecutorService executorService = new ThreadPoolExecutor( 1, 1, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.AbortPolicy() ); //when assertThatThrownBy(() -> { for (int i = 0; i < 100; i++) { executorService.submit(() -> { try { Thread.sleep(1000); } catch (InterruptedException ignored) { } }); } }); } }
23.40625
74
0.638184
ca6a7a54506ffcd6452d2ed6b8e06bc962c25e5d
1,437
package de.vrees.heatpump.coolant; import org.apache.commons.math3.analysis.interpolation.DividedDifferenceInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialFunctionNewtonForm; /** * Diese Klasse bildet den Druck/Temperatur -Verlauf des Kuehlmittels R134a in einem Polynom 4-ter Ordnung ab. * * Im Niederdruck-Bereich von -10 bis +10 Grad Celsius ist die Abweichung kleiner als 0.02 Grad. * * Created by vrees on 13.02.16. */ public class InterpolationR134a { // double pressureBar[] = {1.421, 3.126, 6.694, 12.259}; // double temperature[] = {-5, 10, 30, 50}; double pressureBar[] = {0.997, 1.421, 1.913, 2.478, 3.126}; double temperature[] = {-10, -5, -0, 5, 10,}; private PolynomialFunctionNewtonForm polynom; public InterpolationR134a() { DividedDifferenceInterpolator divider = new DividedDifferenceInterpolator(); polynom = divider.interpolate(pressureBar, temperature); } /** * Berechnet zu dem gegeben Druck in bar die entsprechende Sättiungstemperarur des Kühlmittels R134a * * Beispiel 5°C entspricht 2.478 bar (über Normaldruck) * * @param druck in Bar relativ zum Normadruck * @return die Temperatur in Grad Celsius */ public double calcTemperatur(double druck) { return polynom.value(druck); } public PolynomialFunctionNewtonForm getPolynom() { return polynom; } }
29.326531
110
0.699374
c2f2e3e8ec421473523220d90a04cf11d61d1b48
2,287
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.convert.mojo.nucc; import java.io.File; import java.nio.file.Path; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import sh.isaac.api.coordinate.StampCoordinate; /** * * {@link NUCCImportMojoDirect} * * Goal which converts NUCC data ISAAC * * @author <a href="mailto:joel.kniaz.list@gmail.com">Joel Kniaz</a> * */ @Mojo(name = "convert-NUCC-to-ibdf", defaultPhase = LifecyclePhase.PROCESS_SOURCES) public class NUCCImportMojoDirect extends NUCCImportHK2Direct { /** * This constructor is for maven and HK2 and should not be used at runtime. You should * get your reference of this class from HK2, and then call the {@link #configure(File, Path, String, StampCoordinate)} method on it. */ public NUCCImportMojoDirect() { } }
34.651515
135
0.730652
7f76258a919ed7a65a0c510f8d2735b2cb6ffdae
1,277
/** * This class is generated by jOOQ */ package org.jooq.test.mysql2.generatedclasses.tables.pojos; /** * This class is generated by jOOQ. * * An unused table in the same schema. */ @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) @javax.persistence.Entity @javax.persistence.Table(name = "x_test_case_85", schema = "test2") public class XTestCase_85 implements java.io.Serializable { private static final long serialVersionUID = -323338308; private java.lang.Integer id; private java.lang.Integer xUnusedId; private java.lang.String xUnusedName; @javax.persistence.Id @javax.persistence.Column(name = "id", unique = true, nullable = false, precision = 10) public java.lang.Integer getId() { return this.id; } public void setId(java.lang.Integer id) { this.id = id; } @javax.persistence.Column(name = "x_unused_id", precision = 10) public java.lang.Integer getXUnusedId() { return this.xUnusedId; } public void setXUnusedId(java.lang.Integer xUnusedId) { this.xUnusedId = xUnusedId; } @javax.persistence.Column(name = "x_unused_name", length = 10) public java.lang.String getXUnusedName() { return this.xUnusedName; } public void setXUnusedName(java.lang.String xUnusedName) { this.xUnusedName = xUnusedName; } }
25.54
88
0.732185
1fdde804fc86d8814d5075df7275f50b4e6661f4
3,820
package de.bornemisza.ds.rest.security; import de.bornemisza.ds.rest.security.HashProvider; import de.bornemisza.ds.rest.security.DoubleSubmitToken; import org.junit.Before; import org.junit.Test; import org.primeframework.jwt.domain.JWT; import org.primeframework.jwt.domain.JWTException; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import de.bornemisza.ds.rest.exception.UnauthorizedException; public class DoubleSubmitTokenTest { private DoubleSubmitToken CUT; private HashProvider hashProvider; private final String cookie = "AuthSession=RmF6aWwgT25ndWRhcjo1QTM2RENDOTq5wOKqrLBx9hoE7O2faOEOl98vUA"; private final String cookieWithoutKey = "RmF6aWwgT25ndWRhcjo1QTM2Nzc5Rg=="; private final String cookieWithoutPrincipal = "AuthSession=b866f6e2-be02-4ea0-99e6-34f989629930; Version=1; Path=/; HttpOnly; Secure"; private final String cToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ3d3cuYm9ybmVtaXN6YS5kZSIsInN1YiI6IkZhemlsIE9uZ3VkYXIifQ.MJ6UDeTiOJai5DprYOBLntfh09uFI7GfeRS6klbk8Ic"; public DoubleSubmitTokenTest() { } @Before public void setUp() { hashProvider = mock(HashProvider.class); } @Test(expected=UnauthorizedException.class) public void checkTokenValidity_cookieVoid() { CUT = new DoubleSubmitToken(null, "cToken"); CUT.checkValidity(hashProvider); } @Test(expected=UnauthorizedException.class) public void checkTokenValidity_cTokenVoid() { CUT = new DoubleSubmitToken("Cookie", ""); CUT.checkValidity(hashProvider); } @Test public void checkValidity_invalidJWT() { CUT = new DoubleSubmitToken(cookie, cToken); when(hashProvider.decodeJasonWebToken(anyString())).thenThrow(new JWTException("invalid JWT - cannot decode")); try { CUT.checkValidity(hashProvider); fail(); } catch (UnauthorizedException ex) { assertTrue(ex.getMessage().startsWith("JWT invalid:")); } } @Test public void checkValidity_cookieWithoutPrincipal() { CUT = new DoubleSubmitToken(cookieWithoutPrincipal, cToken); try { CUT.checkValidity(hashProvider); fail(); } catch (UnauthorizedException ex) { assertEquals("Cookie invalid!", ex.getMessage()); } } @Test public void checkValidity_jwtWithoutSubject() { CUT = new DoubleSubmitToken(cookie, cToken); JWT jwt = new JWT(); when(hashProvider.decodeJasonWebToken(anyString())).thenReturn(jwt); try { CUT.checkValidity(hashProvider); fail(); } catch (UnauthorizedException ex) { assertEquals("JWT invalid!", ex.getMessage()); } } @Test public void checkValidity_principalSubjectMismatch() { CUT = new DoubleSubmitToken(cookie, cToken); JWT jwt = new JWT(); jwt.setSubject("Someone else"); when(hashProvider.decodeJasonWebToken(anyString())).thenReturn(jwt); try { CUT.checkValidity(hashProvider); } catch (UnauthorizedException ex) { assertEquals("Hash Mismatch!", ex.getMessage()); } } @Test public void checkValidity() { String principal = "Fazil Ongudar"; CUT = new DoubleSubmitToken(cookie, cToken); JWT jwt = new JWT(); jwt.setSubject(principal); when(hashProvider.decodeJasonWebToken(anyString())).thenReturn(jwt); String userName = CUT.checkValidity(hashProvider); assertEquals(principal, userName); CUT = new DoubleSubmitToken(cookieWithoutKey, cToken); userName = CUT.checkValidity(hashProvider); assertEquals(principal, userName); } }
34.107143
184
0.675654
e15d1d00afed03c30033e1f5f2d79b262f2b5c98
6,960
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bftv.fui.recycleview.widget; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bftv.fui.recycleview.R; import com.bftv.fui.recycleview.callback.OnLoadMoreListener; import com.bftv.fui.recycleview.model.User; import com.bftv.fui.recycleview.viewholder.FooterViewHolder; import com.bftv.fui.recycleview.viewholder.HeaderViewHolder; import com.bftv.fui.recycleview.viewholder.ItemViewHolder; import com.bftv.fui.recycleview.viewholder.LoadingViewHolder; import java.util.ArrayList; /** * Provide views to RecyclerView with data from mDataSet. */ public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final String TAG = "CustomAdapter"; private static final int VIEW_TYPE_ITEM = 0; private static final int VIEW_TYPE_LOADING = 1; private static final int VIEW_TYPE_HEADER = 2; private static final int VIEW_TYPE_FOOTER = 3; private boolean isLoading = false; private int visibleThreshold = 5; private int lastVisibleItem; private int totalItemCount; private OnLoadMoreListener mOnLoadMoreListener; private ArrayList<User> users = null; private RecyclerView.ViewHolder viewHolder = null; private View headerView,footerView,loadingView; private RecyclerView mRecyclerView = null; private LinearLayoutManager mLayoutManager = null; public CustomAdapter(ArrayList<User> users, RecyclerView recyclerView, LinearLayoutManager layoutManager) { this.users = users; this.mRecyclerView = recyclerView; this.mLayoutManager = layoutManager; // this.mManager = (GridLayoutManager) recyclerView.getLayoutManager(); // mManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { // @Override // public int getSpanSize(int position) { // return getItemViewType(position) == VIEW_LOADING ? mManager.getSpanCount() : 1; // } // }); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); totalItemCount = mLayoutManager.getItemCount(); lastVisibleItem = mLayoutManager.findLastVisibleItemPosition(); if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) { if (mOnLoadMoreListener != null) { showLoading(); mOnLoadMoreListener.onLoadMore(); } isLoading = true; } } }); } public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) { this.mOnLoadMoreListener = mOnLoadMoreListener; } public void setCustomView(View headerView,View footerView,View loadingView){ this.headerView = headerView; this.footerView = footerView; this.loadingView = loadingView; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { switch (viewType){ case VIEW_TYPE_HEADER: viewHolder = new HeaderViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_header, viewGroup, false)); break; case VIEW_TYPE_ITEM: viewHolder = new ItemViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.text_row_item, viewGroup, false)); break; case VIEW_TYPE_LOADING: viewHolder = new LoadingViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false)); break; case VIEW_TYPE_FOOTER: viewHolder = new FooterViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_footer, viewGroup, false)); break; default: break; } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Log.d(TAG, "Element " + position + " set."); User user = users.get(position); if (holder instanceof HeaderViewHolder){ }else if (holder instanceof ItemViewHolder){ ItemViewHolder userViewHolder = (ItemViewHolder) holder; userViewHolder.getTextView().setText(user.getName()); }else if (holder instanceof FooterViewHolder){ }else { LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder; loadingViewHolder.getProgressBar().setIndeterminate(true); } } @Override public int getItemCount() { return users == null ? 0 : users.size() + convertExtItemCount(); } public void setLoaded() { isLoading = false; } @Override public int getItemViewType(int position) { if (users.get(position) == null){ return VIEW_TYPE_HEADER; } if (users.get(position).getItemType() == 2){ return VIEW_TYPE_LOADING; } return VIEW_TYPE_ITEM; // return super.getItemViewType(position); } public void showLoading(){ User loading = new User(); loading.setItemType(2); users.add(loading); notifyItemInserted(users.size() - 1); } public void hideLoading(){ users.remove(users.size() - 1); notifyItemRemoved(users.size()); } public void loadMoreComplete(){ notifyDataSetChanged(); setLoaded(); } public void addItem(User item,int position){ users.add(position,item); notifyItemInserted(position); } /** * 计算多余的item数 * @return */ private final int convertExtItemCount(){ int extItem = 0; if (headerView != null){ extItem++; } if (loadingView != null){ extItem++; } if (footerView != null){ extItem++; } return extItem; } }
31.926606
152
0.655603
194227ff1909feedc1d54775b71aa8eafb2391c6
120
public class FirstProgram { public static void main(String[] args) { System.out.println("I start learning java!"); } }
17.142857
45
0.725
8b4a3385bc0b878c089e1293bbded9ffe514ab3f
3,975
package com.sample.springboot.data.mybatis.service.impl; import com.sample.springboot.data.mybatis.domain.second.SecondDO; import com.sample.springboot.data.mybatis.mapper.second.SecondMapper; import com.sample.springboot.data.mybatis.page.Page; import com.sample.springboot.data.mybatis.query.SecondQuery; import com.sample.springboot.data.mybatis.service.SecondService; import com.sample.springboot.data.mybatis.service.base.impl.BaseServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.weekend.WeekendSqls; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service public class SecondServiceImpl extends BaseServiceImpl<SecondDO> implements SecondService { private SecondMapper secondMapper; /** * 注入secondaryMapper(setter注入) * JSR-330写法 @Inject @Named("beanName") * Spring写法 @Autowired @Qualifier("beanName") */ @Autowired public void setSecondaryMapper(SecondMapper secondMapper) { // 将"secondaryMapper"注入BaseServiceImpl中 super.setMapper(secondMapper); // 将"secondaryMapper"注入SecondaryServiceImpl中 this.secondMapper = secondMapper; } @Override public List<SecondDO> findAll(SecondQuery query) { Example example = Example.builder(SecondDO.class) .where(buildWhereSqls(query)) .orderByAsc("id") .build(); return secondMapper.selectByExample(example); } @Override public List<SecondDO> findAll(SecondQuery query, int number, int size) { // 分页查询 startPage(number, size); Example example = Example.builder(SecondDO.class) .where(buildWhereSqls(query)) .orderByAsc("id") .build(); List<SecondDO> seconds = secondMapper.selectByExample(example); // 分页对象 int totalElements = secondMapper.selectCountByExample(example); Page page = new Page(number, size, totalElements); query.setPage(page); return seconds; } /** * 根据查询对象生成查询条件 * * @param query 查询对象 * @return {@link WeekendSqls} */ private WeekendSqls<SecondDO> buildWhereSqls(SecondQuery query) { WeekendSqls<SecondDO> sqls = WeekendSqls.custom(); // 无查询条件 if (null == query) { return sqls; } // String if(null != query.getSampleString()){ sqls.andLike(SecondDO::getSampleString, "%".concat(query.getSampleString()).concat("%")); } // Amount if(null != query.getMinAmount()){ sqls.andGreaterThan(SecondDO::getSampleAmount, query.getMinAmount()); } if(null != query.getMaxAmount()){ sqls.andLessThan(SecondDO::getSampleAmount, query.getMaxAmount()); } // Date if(null != query.getMinDate()){ sqls.andGreaterThan(SecondDO::getSampleDate, query.getMinDate()); } if(null != query.getMaxDate()){ sqls.andLessThan(SecondDO::getSampleDate, query.getMaxDate()); } // DateTime if(null != query.getMinDateTime()){ sqls.andGreaterThan(SecondDO::getSampleDateTime, query.getMinDateTime()); } if(null != query.getMaxDateTime()){ sqls.andLessThan(SecondDO::getSampleDateTime, query.getMaxDateTime()); } // Enums if(null != query.getSampleEnums() && query.getSampleEnums().length > 0){ sqls.andIn(SecondDO::getSampleEnum, Arrays.stream(query.getSampleEnums()).collect(Collectors.toSet())); } // Disable if(null != query.getDeleted() && query.getDeleted()){ sqls.andEqualTo(SecondDO::getDeleted, 1); } else { sqls.andEqualTo(SecondDO::getDeleted, 0); } return sqls; } }
34.565217
115
0.643019
2d3737888665d9fe450f7b27616256499e6aabd1
457
package com.octoperf.kraken.runtime.context.api.environment; import com.octoperf.kraken.runtime.context.entity.ExecutionContextBuilder; import com.octoperf.kraken.runtime.entity.environment.ExecutionEnvironmentEntry; import reactor.core.publisher.Mono; import java.util.List; import java.util.function.Function; public interface EnvironmentPublisher extends EnvironmentTester, Function<ExecutionContextBuilder, Mono<List<ExecutionEnvironmentEntry>>> { }
38.083333
139
0.85558
dddd24ec83a06279d4d3e3e33c08718a4b2bb6f6
1,179
package com.hbm.render.tileentity; import org.lwjgl.opengl.GL11; import com.hbm.main.ResourceManager; import com.hbm.tileentity.machine.TileEntityMachineCentrifuge; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; public class RenderCentrifuge extends TileEntitySpecialRenderer<TileEntityMachineCentrifuge> { @Override public boolean isGlobalRenderer(TileEntityMachineCentrifuge te) { return true; } @Override public void render(TileEntityMachineCentrifuge te, double x, double y, double z, float partialTicks, int destroyStage, float alpha) { GL11.glPushMatrix(); GL11.glTranslated(x + 0.5D, y, z + 0.5D); GlStateManager.enableLighting(); GlStateManager.enableLighting(); switch(te.getBlockMetadata()) { case 4: GL11.glRotatef(90, 0F, 1F, 0F); break; case 3: GL11.glRotatef(180, 0F, 1F, 0F); break; case 5: GL11.glRotatef(270, 0F, 1F, 0F); break; case 2: GL11.glRotatef(0, 0F, 1F, 0F); break; } bindTexture(ResourceManager.centrifuge_new_tex); ResourceManager.centrifuge_new.renderAll(); GL11.glPopMatrix(); } }
28.071429
134
0.741306
a3921bd15e9ec7e7cefc960e01f8094131687043
819
package de.helixdevs.deathchest.support.protection; import de.helixdevs.deathchest.api.protection.IProtectionService; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Arrays; public class CombinedProtectionService implements IProtectionService { private final IProtectionService[] services; public CombinedProtectionService(IProtectionService[] services) { this.services = services; } @Override public boolean canBuild(@NotNull Player player, @NotNull Location location, @NotNull Material material) { return Arrays.stream(services) .map(s -> s.canBuild(player, location, material)) .reduce(Boolean::equals) .orElse(true); } }
30.333333
109
0.726496
94a31d8526faabbb3f3748c4468a5087f82a993e
1,801
package com.arcturusmayer.memescreen; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; /** * Created by Arcturus Mayer on 05.11.2017. */ /** * Copyright 2017 Mikhaylov Vladislav 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. */ public class StudyingDialog extends DialogFragment { Button ok; public StudyingDialog(){ } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.study_dialog_layout, (ViewGroup) getActivity().findViewById(R.id.layout)); builder.setView(view); final Dialog diag = builder.create(); ok = view.findViewById(R.id.btnok); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { diag.cancel(); } }); return diag; } }
30.525424
120
0.7196
2ed2f43cf58748ee9966e6be5665040207007f3f
2,550
package com.jaeger.statusbarutil; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Window; import android.view.WindowManager; import com.jaeger.statusbardemo.R; import com.readystatesoftware.systembartint.SystemBarTintManager; /** * Created by lxp on 2015/12/29. * 整个app的Activity基类 */ public abstract class GentouBaseActivity extends FragmentActivity { private Boolean isRunning = false; /** * -初始化控件 */ protected abstract void findViews(); /** * -设置控件监听器 */ protected abstract void setListeners(); /** * -初始化数据 */ protected abstract void initData(); /** * -初始化控件数据 */ protected abstract void initViews(); /* * 标示activity的唯一值 * 在网络请求发起请求与取消请求,需要用到此value; */ protected abstract String getName(); @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); isRunning = true; } @Override protected void onPause() { super.onPause(); isRunning = false; } @Override protected void onStop() { super.onStop(); isRunning = false; } @Override protected void onCreate(Bundle savedInstanceState) { if (Build.VERSION.SDK_INT >= 19) { setTheme(R.style.style_tint_status_bar); } super.onCreate(savedInstanceState); initSystemBar(R.color.colorAccent); } private void initSystemBar(int color) { // Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT if (Build.VERSION.SDK_INT >= 19) { setTranslucentStatus(this, true); SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setNavigationBarTintEnabled(true); tintManager.setStatusBarTintResource(color); } } @TargetApi(19) private static void setTranslucentStatus(Activity activity, boolean on) { Window win = activity.getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } }
22.566372
78
0.637255
368475f466905de0ab804139064206959e461f39
1,958
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.git4idea.http; import org.jetbrains.annotations.NotNull; /** * This handler is called via XML RPC from {@link GitAskPassApp} when Git requests user credentials. * * @author Kirill Likhodedov */ public interface GitAskPassXmlRpcHandler { String GIT_ASK_PASS_HANDLER_ENV = "GIT_ASKPASS_HANDLER"; String GIT_ASK_PASS_PORT_ENV = "GIT_ASKPASS_PORT"; String HANDLER_NAME = GitAskPassXmlRpcHandler.class.getName(); /** * Get the username from the user to access the given URL. * @param token Access token. * @param url URL which Git tries to access. * @return The Username which should be used for the URL. */ // UnusedDeclaration suppressed: the method is used via XML RPC @SuppressWarnings("UnusedDeclaration") @NotNull String askUsername(String token, @NotNull String url); /** * Get the password from the user to access the given URL. * It is assumed that the username either is specified in the URL (http://username@host.com), or has been asked earlier. * @param token Access token. * @param url URL which Git tries to access. * @return The password which should be used for the URL. */ // UnusedDeclaration suppressed: the method is used via XML RPC @SuppressWarnings("UnusedDeclaration") @NotNull String askPassword(String token, @NotNull String url); }
35.6
122
0.733912
08d4c0033219f5ea10fc57054b9246f198884e08
11,035
/******************************************************************************* * Copyright (c) 2022 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. ******************************************************************************/ package org.eclipse.rdf4j.http.server.repository.handler; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE; import static org.eclipse.rdf4j.http.protocol.Protocol.BINDING_PREFIX; import static org.eclipse.rdf4j.http.protocol.Protocol.DEFAULT_GRAPH_PARAM_NAME; import static org.eclipse.rdf4j.http.protocol.Protocol.INCLUDE_INFERRED_PARAM_NAME; import static org.eclipse.rdf4j.http.protocol.Protocol.NAMED_GRAPH_PARAM_NAME; import static org.eclipse.rdf4j.http.protocol.Protocol.QUERY_LANGUAGE_PARAM_NAME; import static org.eclipse.rdf4j.http.protocol.Protocol.QUERY_PARAM_NAME; import java.io.IOException; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.common.lang.FileFormat; import org.eclipse.rdf4j.common.lang.service.FileFormatServiceRegistry; import org.eclipse.rdf4j.common.webapp.util.HttpServerUtil; import org.eclipse.rdf4j.http.protocol.Protocol; import org.eclipse.rdf4j.http.protocol.error.ErrorInfo; import org.eclipse.rdf4j.http.protocol.error.ErrorType; import org.eclipse.rdf4j.http.server.ClientHTTPException; import org.eclipse.rdf4j.http.server.HTTPException; import org.eclipse.rdf4j.http.server.ProtocolUtil; import org.eclipse.rdf4j.http.server.repository.BooleanQueryResultView; import org.eclipse.rdf4j.http.server.repository.GraphQueryResultView; import org.eclipse.rdf4j.http.server.repository.TupleQueryResultView; import org.eclipse.rdf4j.http.server.repository.resolver.RepositoryResolver; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.query.BooleanQuery; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.GraphQuery; import org.eclipse.rdf4j.query.GraphQueryResult; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.Query; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.UnsupportedQueryLanguageException; import org.eclipse.rdf4j.query.impl.SimpleDataset; import org.eclipse.rdf4j.query.resultio.BooleanQueryResultWriterRegistry; import org.eclipse.rdf4j.query.resultio.TupleQueryResultWriterRegistry; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.rio.RDFWriterRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.View; public class DefaultQueryRequestHandler extends AbstractQueryRequestHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public DefaultQueryRequestHandler(RepositoryResolver repositoryResolver) { super(repositoryResolver); } @Override protected Object evaluateQuery(Query query, long limit, long offset, boolean distinct) throws ClientHTTPException { if (query instanceof TupleQuery) { return evaluateQuery((TupleQuery) query, limit, offset, distinct); } else if (query instanceof GraphQuery) { return evaluateQuery((GraphQuery) query, limit, offset, distinct); } else if (query instanceof BooleanQuery) { return evaluateQuery((BooleanQuery) query, limit, offset, distinct); } else { throw new ClientHTTPException(SC_BAD_REQUEST, "Unsupported query type: " + query.getClass().getName()); } } protected Boolean evaluateQuery(BooleanQuery query, long limit, long offset, boolean distinct) { return query.evaluate(); } protected GraphQueryResult evaluateQuery(GraphQuery query, long limit, long offset, boolean distinct) { GraphQueryResult qqr = distinct ? QueryResults.distinctResults(query.evaluate()) : query.evaluate(); return QueryResults.limitResults(qqr, limit, offset); } protected TupleQueryResult evaluateQuery(TupleQuery query, long limit, long offset, boolean distinct) { TupleQueryResult tqr = distinct ? QueryResults.distinctResults(query.evaluate()) : query.evaluate(); return QueryResults.limitResults(tqr, limit, offset); } @Override protected View getViewFor(Query query) { if (query instanceof TupleQuery) { return TupleQueryResultView.getInstance(); } else if (query instanceof GraphQuery) { return GraphQueryResultView.getInstance(); } else if (query instanceof BooleanQuery) { return BooleanQueryResultView.getInstance(); } return null; } @Override protected FileFormatServiceRegistry<? extends FileFormat, ?> getResultWriterFor(Query query) { if (query instanceof TupleQuery) { return TupleQueryResultWriterRegistry.getInstance(); } else if (query instanceof GraphQuery) { return RDFWriterRegistry.getInstance(); } else if (query instanceof BooleanQuery) { return BooleanQueryResultWriterRegistry.getInstance(); } return null; } @Override protected String getQueryString(HttpServletRequest request, RequestMethod requestMethod) throws HTTPException { String queryString; if (requestMethod == RequestMethod.POST) { String mimeType = HttpServerUtil.getMIMEType(request.getContentType()); switch (mimeType) { case Protocol.SPARQL_QUERY_MIME_TYPE: // The query should be the entire body try { queryString = IOUtils.toString(request.getReader()); } catch (IOException e) { throw new HTTPException(HttpStatus.SC_BAD_REQUEST, "Error reading request message body", e); } break; case Protocol.FORM_MIME_TYPE: queryString = request.getParameter(QUERY_PARAM_NAME); break; default: throw new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported MIME type: " + mimeType); } } else { queryString = request.getParameter(QUERY_PARAM_NAME); } if (queryString == null) { throw new ClientHTTPException(SC_BAD_REQUEST, "Missing parameter: " + QUERY_PARAM_NAME); } return queryString; } @Override protected Query getQuery(HttpServletRequest request, RepositoryConnection repositoryCon, String queryString) throws IOException, HTTPException { QueryLanguage queryLn = getQueryLanguage(request.getParameter(QUERY_LANGUAGE_PARAM_NAME)); String baseIRI = request.getParameter(Protocol.BASEURI_PARAM_NAME); try { Query query = repositoryCon.prepareQuery(queryLn, queryString, baseIRI); setQueryParameters(request, repositoryCon, query); return query; } catch (UnsupportedQueryLanguageException e) { ErrorInfo errInfo = new ErrorInfo(ErrorType.UNSUPPORTED_QUERY_LANGUAGE, queryLn.getName()); throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString()); } catch (MalformedQueryException e) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, e.getMessage()); throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString()); } catch (RepositoryException e) { logger.error("Repository error", e); throw new ClientHTTPException(SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } protected void setQueryParameters(HttpServletRequest request, RepositoryConnection repositoryCon, Query query) throws ClientHTTPException { // determine if inferred triples should be included in query evaluation query.setIncludeInferred(getIncludeInferred(request)); int maxExecutionTime = getMaxExecutionTime(request); if (maxExecutionTime > 0) { query.setMaxExecutionTime(maxExecutionTime); } Dataset dataset = getDataset(request, repositoryCon.getValueFactory(), query); if (dataset != null) { query.setDataset(dataset); } // determine if any variable bindings have been set on this query. Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String parameterName = parameterNames.nextElement(); if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) { String bindingName = parameterName.substring(BINDING_PREFIX.length()); Value bindingValue = ProtocolUtil.parseValueParam(request, parameterName, repositoryCon.getValueFactory()); query.setBinding(bindingName, bindingValue); } } } protected int getMaxExecutionTime(HttpServletRequest request) throws ClientHTTPException { return ProtocolUtil.parseTimeoutParam(request); } protected boolean getIncludeInferred(HttpServletRequest request) throws ClientHTTPException { return getParam(request, INCLUDE_INFERRED_PARAM_NAME, true, Boolean.TYPE); } protected SimpleDataset getDataset(HttpServletRequest request, ValueFactory valueFactory, Query query) throws ClientHTTPException { String[] defaultGraphIRIs = request.getParameterValues(DEFAULT_GRAPH_PARAM_NAME); String[] namedGraphIRIs = request.getParameterValues(NAMED_GRAPH_PARAM_NAME); if (defaultGraphIRIs == null && namedGraphIRIs == null) { return null; } SimpleDataset dataset = new SimpleDataset(); if (defaultGraphIRIs != null) { for (String defaultGraphIRI : defaultGraphIRIs) { try { IRI iri = createIRIOrNull(valueFactory, defaultGraphIRI); dataset.addDefaultGraph(iri); } catch (IllegalArgumentException e) { throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal IRI for default graph: " + defaultGraphIRI); } } } if (namedGraphIRIs != null) { for (String namedGraphIRI : namedGraphIRIs) { try { IRI iri = createIRIOrNull(valueFactory, namedGraphIRI); dataset.addNamedGraph(iri); } catch (IllegalArgumentException e) { throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal IRI for named graph: " + namedGraphIRI); } } } return dataset; } protected QueryLanguage getQueryLanguage(String queryLanguageParamName) throws ClientHTTPException { if (queryLanguageParamName != null) { logger.debug("query language param = {}", queryLanguageParamName); QueryLanguage queryLn = QueryLanguage.valueOf(queryLanguageParamName); if (queryLn == null) { throw new ClientHTTPException(SC_BAD_REQUEST, "Unknown query language: " + queryLanguageParamName); } return queryLn; } else { return QueryLanguage.SPARQL; } } private IRI createIRIOrNull(ValueFactory valueFactory, String graphIRI) { if ("null".equals(graphIRI)) { return null; } return valueFactory.createIRI(graphIRI); } }
38.449477
116
0.77517
1a4631eba77dffbc7c09e31fbbe9c3c5f5a1e57f
385
package measurement; import com.AlphaMM.utils.DateUtils; import com.AlphaMM.utils.MyUtils; import org.junit.Test; public class MyUtilsTestTest { @Test public void test1() throws Exception { System.out.println(MyUtils.randomInt(999999)); } @Test public void test2() throws Exception { System.out.println(DateUtils.getNowTime("yyyyMMdd")); } }
21.388889
61
0.698701
0041ebcece38f0ee5505d7e2192ec1af5eb5b721
523
package com.maxplus1.demo.service; import com.maxplus1.demo.dao.test1db.Test1Dao; import com.maxplus1.demo.entity.Test1Pojo; import com.maxplus1.demo.service.remote.ITest1Service; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * Created by xiaolong.qiu on 2017/1/19. */ @Service public class Test1Service implements ITest1Service{ @Resource private Test1Dao test1Dao; @Override public Test1Pojo getTest1(Long id) { return test1Dao.getTest1(id); } }
20.92
54
0.755258
a6127915e56ba72f8a47a554c263f8478b281b91
1,467
package nl.ramondevaan.aoc2020.day24; import nl.ramondevaan.aoc2020.util.Parser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class PathParser implements Parser<String, List<Direction>> { @Override public List<Direction> parse(String toParse) { AtomicInteger index = new AtomicInteger(0); List<Direction> directions = new ArrayList<>(); while (index.get() < toParse.length()) { directions.add(parse(toParse, index)); } return Collections.unmodifiableList(directions); } private Direction parse(String toParse, AtomicInteger index) { char current = toParse.charAt(index.getAndIncrement()); char extra; switch (current) { case 'e': return Direction.EAST; case 'w': return Direction.WEST; case 'n': extra = toParse.charAt(index.getAndIncrement()); if (extra == 'e') { return Direction.NORTH_EAST; } return Direction.NORTH_WEST; case 's': extra = toParse.charAt(index.getAndIncrement()); if (extra == 'e') { return Direction.SOUTH_EAST; } return Direction.SOUTH_WEST; } throw new IllegalStateException(); } }
29.34
68
0.575324
1db241b14bfd42ee14512a442bf14b73b62c51d7
1,128
package sldevand.fr.listoo.model; import android.widget.TextView; import java.io.Serializable; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class Category extends RealmObject implements Serializable { @PrimaryKey private String name; private String description; private String uri; public Category() { super(); } public Category(String name) { this.name = name; } public Category(String name, String description) { this(name); this.description = description; } public Category(String name, String description,String uri) { this(name,description); this.uri=uri; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } }
18.8
67
0.631206
a1d68ebf4314aff36c58912899bf99af08b41e24
3,727
package com.blakebr0.extendedcrafting.compat.crafttweaker; import java.util.Arrays; import java.util.List; import com.blakebr0.extendedcrafting.crafting.CompressorRecipe; import com.blakebr0.extendedcrafting.crafting.CompressorRecipeManager; import crafttweaker.CraftTweakerAPI; import crafttweaker.IAction; import crafttweaker.api.item.IIngredient; import crafttweaker.api.item.IItemStack; import crafttweaker.api.oredict.IOreDictEntry; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.extendedcrafting.CompressionCrafting") public class CompressionCrafting { @ZenMethod public static void addRecipe(IItemStack output, IItemStack input, int inputCount, IItemStack catalyst, int powerCost) { CraftTweakerAPI.apply(new Add(new CompressorRecipe(toStack(output), toStack(input), inputCount, toStack(catalyst), false, powerCost))); } @ZenMethod public static void addRecipe(IItemStack output, IItemStack input, int inputCount, IItemStack catalyst, int powerCost, int powerRate) { CraftTweakerAPI.apply(new Add(new CompressorRecipe(toStack(output), toStack(input), inputCount, toStack(catalyst), false, powerCost, powerRate))); } @ZenMethod public static void remove(IItemStack target) { CraftTweakerAPI.apply(new Remove(toStack(target))); } private static class Add implements IAction { CompressorRecipe recipe; public Add(CompressorRecipe add) { this.recipe = add; } @Override public void apply() { CompressorRecipeManager.getInstance().getRecipes().add(this.recipe); } @Override public String describe() { return "Adding a Compression Crafting recipe for " + this.recipe.getOutput().getDisplayName(); } } private static class Remove implements IAction { ItemStack remove; public Remove(ItemStack remove) { this.remove = remove; } @Override public void apply() { CompressorRecipeManager.getInstance().removeRecipes(this.remove); } @Override public String describe() { return "Removing all Compression Crafting recipes for " + this.remove.getDisplayName(); } } private static ItemStack toStack(IItemStack item) { if (item == null) { return ItemStack.EMPTY; } else { Object internal = item.getInternal(); if (internal == null || !(internal instanceof ItemStack)) { CraftTweakerAPI.getLogger().logError("Not a valid item stack: " + item); } return (ItemStack) internal; } } private static Object toObject(IIngredient ingredient) { if (ingredient == null) { return null; } else { if (ingredient instanceof IOreDictEntry) { return toString((IOreDictEntry) ingredient); } else if (ingredient instanceof IItemStack) { return toStack((IItemStack) ingredient); } else { return null; } } } private static Object[] toObjects(IIngredient[] list) { if (list == null) return null; Object[] ingredients = new Object[list.length]; for (int x = 0; x < list.length; x++) { ingredients[x] = toActualObject(list[x]); } return ingredients; } private static List toList(IIngredient[] list) { return Arrays.asList(toObjects(list)); } private static Object toActualObject(IIngredient ingredient) { if (ingredient == null) { return null; } else { if (ingredient instanceof IOreDictEntry) { return OreDictionary.getOres(toString((IOreDictEntry) ingredient)); } else if (ingredient instanceof IItemStack) { return toStack((IItemStack) ingredient); } else { return null; } } } private static String toString(IOreDictEntry entry) { return ((IOreDictEntry) entry).getName(); } }
28.022556
148
0.738664
48ca4abc83319155e9896f504126d9ae2b005fe6
320
package com.leetcode.onlinejudge.common; /** * Created by Who on 2014/6/30. */ public class TreeLinkNode { public int val; public TreeLinkNode left, right, next; public TreeLinkNode(int x) { val = x; } @Override public String toString() { return String.valueOf(val); } }
16.842105
42
0.61875
1a57bb546ec1a7488089d35efe59e4b3b40ade92
1,182
package practice.string; import java.util.stream.Stream; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * <pre> * <h1>3. 문장 속 단어</h1> * <h1>설명</h1> * * 한 개의 문장이 주어지면 그 문장 속에서 가장 긴 단어를 출력하는 프로그램을 작성하세요. * * 문장속의 각 단어는 공백으로 구분됩니다. * * * <h1>입력</h1> * 첫 줄에 길이가 100을 넘지 않는 한 개의 문장이 주어집니다. 문장은 영어 알파벳으로만 구성되어 있습니다. * * * <h1>출력</h1> * 첫 줄에 가장 긴 단어를 출력한다. 가장 길이가 긴 단어가 여러개일 경우 문장속에서 가장 앞쪽에 위치한 * * 단어를 답으로 합니다. * </pre> */ @DisplayName("문자열 - 문장 속 단어") class WordInSentenceTest { private WordInSentence solve = new WordInSentence(); @MethodSource @ParameterizedTest void solution(final String sentence, final String expected) { final String actual = solve.solution(sentence); Assertions.assertThat(actual).isEqualTo(expected); } private static Stream<Arguments> solution() { return Stream.of( Arguments.of("it is time to study", "study"), Arguments.of("aa aaa aa bbb", "aaa") ); } }
24.122449
65
0.660745
66813b3f981c0faab7625fcd645cc1900519e55c
10,616
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jay.android.pages.audio; import android.content.Intent; import android.graphics.Color; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.SeekBar; import android.widget.TextView; import com.jay.android.R; import com.jay.android.base.BaseActivity; import com.jay.android.player.MediaPlayerHolder; import com.jay.android.player.PlaybackInfoListener; import com.jay.android.player.PlayerAdapter; /** * Allows playback of a single MP3 file via the UI. It contains a {@link MediaPlayerHolder} * which implements the {@link PlayerAdapter} interface that the activity uses to control * audio playback. */ public final class AudioPlayActivity extends BaseActivity { public static final String TAG = AudioPlayActivity.class.getSimpleName(); public static final String AUDIO_PATH = "AUDIO_PATH"; public static final String AUDIO_TITLE = "AUDIO_TITLE"; private SeekBar mSeekbarAudio; private ImageView mPlayOrPauseButton; private PlayerAdapter mPlayerAdapter; private boolean mUserIsSeeking = false; private TextView tvDuration; private float speedRate = 1.0f; private int speedIndex = 2; private float[] speedSet = {0.5f, 0.8f, 1.0f, 1.2f, 1.6f,2.0f}; private String[] speedSetDisplay = {"0.5x", "0.8x", "1.0x", "1.2x", "1.6x","2.0x"}; private float timeDivider = 1.0f; private int timeIndex = 2; private int[] timeSet = {1000, 3000, 5000, 7000, 10000,15000}; private String[] timeSetDisplay = {"1s", "3s", "5s", "7s", "10s","15s"}; @Override public int getContentViewId() { return R.layout.activity_audio_play; } @Override public String getPageTitle() { return getIntent().getStringExtra(AUDIO_TITLE); } @Override public boolean isShowFab() { return false; } @Override public void initView() { initializeUI(); initializeSeekbar(); initializePlaybackController(); } @Override protected void onStart() { super.onStart(); if (getIntent() != null) { mPlayerAdapter.loadMedia(getIntent().getStringExtra(AUDIO_PATH)); Log.d(TAG, "onStart: create MediaPlayer"); } } @Override protected void onStop() { super.onStop(); if (isChangingConfigurations() && mPlayerAdapter.isPlaying()) { Log.d(TAG, "onStop: don't release MediaPlayer as screen is rotating & playing"); } else { mPlayerAdapter.release(); Log.d(TAG, "onStop: release MediaPlayer"); } } private void initializeUI() { ImageView mBackButton = findViewById(R.id.button_back); ImageView mSkipButton = findViewById(R.id.button_skip); mPlayOrPauseButton = findViewById(R.id.button_play_pause); mSeekbarAudio = findViewById(R.id.seekbar_audio); tvDuration = findViewById(R.id.tv_duration); mBackButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { int progress = mSeekbarAudio.getProgress(); if (progress > timeSet[timeIndex]) { mSeekbarAudio.setProgress(progress - timeSet[timeIndex]); } else { mSeekbarAudio.setProgress(0); } mPlayerAdapter.goBack(timeSet[timeIndex]); } }); mSkipButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { int progress = mSeekbarAudio.getProgress(); if (progress + timeSet[timeIndex] < mSeekbarAudio.getMax()) { mSeekbarAudio.setProgress(progress + timeSet[timeIndex]); } else { mSeekbarAudio.setProgress(mSeekbarAudio.getMax()); } mPlayerAdapter.skip(timeSet[timeIndex]); } }); mPlayOrPauseButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { if (mPlayerAdapter.isPlaying()) { // mPlayOrPauseButton.setText("Play"); mPlayOrPauseButton.setImageResource(R.drawable.ic_play); mPlayerAdapter.pause(); } else { mPlayOrPauseButton.setImageResource(R.drawable.ic_pause); mPlayerAdapter.play(); } } }); final TextView time = findViewById(R.id.tv_divider_time); ImageView ivTimeMinus = findViewById(R.id.iv_time_left); ImageView ivTimeAdd = findViewById(R.id.iv_time_right); final TextView speed = findViewById(R.id.tv_speed); ImageView ivSpeedMinus = findViewById(R.id.iv_speed_left); ImageView ivSpeedAdd = findViewById(R.id.iv_speed_right); ivTimeMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (timeIndex <= 0) { timeIndex = 0; } else { timeIndex--; } time.setText(timeSetDisplay[timeIndex]); } }); ivTimeAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (timeIndex >= timeSet.length - 1) { timeIndex = timeSet.length - 1; } else { timeIndex++; } time.setText(timeSetDisplay[timeIndex]); } }); ivSpeedMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (speedIndex <= 0) { speedIndex = 0; } else { speedIndex--; } speed.setText(speedSetDisplay[speedIndex]); mPlayerAdapter.setSpeedRate(speedSet[speedIndex]); } }); ivSpeedAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (speedIndex >= speedSet.length - 1) { speedIndex = speedSet.length - 1; } else { speedIndex++; } speed.setText(speedSetDisplay[speedIndex]); mPlayerAdapter.setSpeedRate(speedSet[speedIndex]); } }); } private void initializePlaybackController() { MediaPlayerHolder mMediaPlayerHolder = new MediaPlayerHolder(this); Log.d(TAG, "initializePlaybackController: created MediaPlayerHolder"); mMediaPlayerHolder.setPlaybackInfoListener(new PlaybackListener()); mPlayerAdapter = mMediaPlayerHolder; Log.d(TAG, "initializePlaybackController: MediaPlayerHolder progress callback set"); } private void initializeSeekbar() { mSeekbarAudio.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { int userSelectedPosition = 0; @Override public void onStartTrackingTouch(SeekBar seekBar) { mUserIsSeeking = true; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { userSelectedPosition = progress; } } @Override public void onStopTrackingTouch(SeekBar seekBar) { mUserIsSeeking = false; mPlayerAdapter.seekTo(userSelectedPosition); } }); } private void updateDuration(int duration) { int min = duration / 60000; int sec = duration % 60000; sec /= 1000; tvDuration.setText(completedByZero(min)+":"+completedByZero(sec)); } private String completedByZero(int n){ if(n<10){ return "0"+n; }else { return String.valueOf(n); } } public class PlaybackListener extends PlaybackInfoListener { @Override public void onDurationChanged(int duration) { mSeekbarAudio.setMax(duration); updateDuration(duration); Log.d(TAG, String.format("setPlaybackDuration: setMax(%d)", duration)); } @Override public void onPositionChanged(int position) { if (!mUserIsSeeking) { mSeekbarAudio.setProgress(position); Log.d(TAG, String.format("setPlaybackPosition: setProgress(%d)", position)); } } @Override public void onStateChanged(@State int state) { String stateToString = PlaybackInfoListener.convertStateToString(state); onLogUpdated(String.format("onStateChanged(%s)", stateToString)); } @Override public void onPlaybackCompleted() { mPlayOrPauseButton.setImageResource(R.drawable.ic_play); } @Override public void onLogUpdated(String message) { log(message); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { } }
34.579805
100
0.572909
a7bb335b60b534f0179fa18b148211a8e81d2f61
2,798
// ============================================================================ // // Copyright (C) 2006-2016 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.commons.utils.data.text; import java.util.List; /** * DOC ocarbone class global comment. Detailled comment <br/> * * $Id$ * */ public class IndiceHelper { /** * Check the unicity of the newLabel in the list of existingLabel. Add or increase an indice if needed. * * @param String newLabel * @param List existingLabel2 * @return String */ public static String getIndexedLabel(String newLabel, List existingLabel2) { String[] existingLabel = new String[existingLabel2.size()]; for (int i = 0; i < existingLabel2.size(); i++) { existingLabel[i] = (String) existingLabel2.get(i); } return getIndexedString(newLabel, existingLabel); } /** * Check the unicity of the newLabel in the list of existingLabel. Add or increase an indice if needed. * * @param String Label * @param String[] existingLabel * @return String */ public static String getIndexedString(String string, String[] existingLabel) { int indicePosition = string.length(); // define the position (to create or increase the indice) for (int f = string.length() - 1; f >= 0; f--) { if (Character.isDigit(string.charAt(f))) { indicePosition = f; } else { f = 0; } } // validate the value is unique and indice when if needed while (!isUniqLabel(string, existingLabel)) { try { String indiceString = string.substring(indicePosition, string.length()); string = string.substring(0, indicePosition) + (Integer.parseInt(indiceString) + 1); } catch (Exception e) { string = string + "1"; //$NON-NLS-1$ } } return string; } private static boolean isUniqLabel(String label, String[] existingLabel) { if (existingLabel == null) { return true; } else { for (int i = 0; i < existingLabel.length; i++) { if (label.equals(existingLabel[i])) { i = existingLabel.length; return false; } } } return true; } }
32.16092
107
0.549678