text
stringlengths
10
2.72M
package models.rules; import java.util.Map; import models.grid.Cell; import models.grid.CellState; import models.grid.GridModel; /** * The class that defines the rules for the Game of Life simulation * @author Weston * */ public class RuleLife extends Rule { public RuleLife(Map<String, Integer> aStateIdsMap) { super(aStateIdsMap); } @Override public void calculateAndSetNextStates(GridModel grid) { for (Cell c: grid){ Cell[] neighbors = grid.getNeighbors(c); int livingNeighbors = 0; for (Cell neighbor: neighbors){ if (neighbor != null) livingNeighbors += neighbor.getStateID(); } // if (c.getStateID() == liveID){ if (c.getStateID() == super.getStateId("Live")){ if (livingNeighbors == 2 || livingNeighbors == 3){ c.setNextState(c.getState()); } else { c.setNextState(newDead()); } } else { if (livingNeighbors == 3){ c.setNextState(newLive()); } else { c.setNextState(c.getState()); } } } } private CellState newLive(){ // return new CellState(liveID, null); return new CellState(super.getStateId("Live"), null); } private CellState newDead(){ return new CellState(super.getStateId("Dead"), null); } @Override public void updateParameter(double aPercentage) { } @Override public double getParameter() { return 0; } }
package br.com.zup.zupacademy.daniel.mercadolivre.categoria; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping("/categoria") public class CategoriaController { @Autowired CategoriaRepository categoriaRepository; @PostMapping public void cadastraCategoria(@RequestBody @Valid CategoriaRequest categoriaRequest) { categoriaRepository.save(categoriaRequest.converte(categoriaRepository)); } }
package models; import java.util.Collection; import java.util.Comparator; import java.util.PriorityQueue; import exceptions.ElementNotAllowedException; import exceptions.ListSizeOverflownException; @SuppressWarnings("serial") public class ListaOrdenada<E> extends PriorityQueue<E> { private final byte MAX_SIZE = 100; public ListaOrdenada(Comparator<E> comp) { super(comp); } public boolean add(E elemento) throws ElementNotAllowedException, ListSizeOverflownException { if (elemento != null) { // Si contiene menos de 100 elementos, añade, si no lanza excepción if (this.size() <= MAX_SIZE) { return super.add(elemento); } else { throw new ListSizeOverflownException("Cola llena, máximo 100 elementos."); } } else { throw new ElementNotAllowedException("No pueden haber valores NULL."); } } public boolean addAll(Collection<? extends E> collection) throws ElementNotAllowedException, ListSizeOverflownException { if (collection.size() + this.size() <= MAX_SIZE) { return super.addAll(collection); } else { throw new ListSizeOverflownException("Cola llena, máximo 100 elementos."); } } }
package ru.job4j.array; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; public class UpArrayTest { @Test public void testOne() { int[] a = {5, 10, 15, 20, 50}; int[] b = {6, 7, 8, 18, 19, 23, 48, 63}; UpArray upArray = new UpArray(); int[] result = upArray.arr(a, b); int[] expect = {5, 6, 7, 8, 10, 15, 18, 19, 20, 23, 48, 50, 63}; assertThat(expect, is(result)); } @Test public void testTwo() { int[] a = {54, 68, 73, 80}; int[] b = {30, 35, 55}; UpArray upArray = new UpArray(); int[] result = upArray.arr(a, b); int[] expect = {30, 35, 54, 55, 68, 73, 80}; assertThat(expect, is(result)); } }
/** * 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.hadoop.mapred; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapred.ControlledMapReduceJob.ControlledMapReduceJobRunner; import org.apache.hadoop.mapreduce.server.tasktracker.TTConfig; /** * Test to verify the controlled behavior of a ControlledMapReduceJob. * */ public class TestControlledMapReduceJob extends ClusterMapReduceTestCase { static final Log LOG = LogFactory.getLog(TestControlledMapReduceJob.class); /** * Starts a job with 5 maps and 5 reduces. Then controls the finishing of * tasks. Signals finishing tasks in batches and then verifies their * completion. * * @throws Exception */ public void testControlledMapReduceJob() throws Exception { Properties props = new Properties(); props.setProperty(TTConfig.TT_MAP_SLOTS, "2"); props.setProperty(TTConfig.TT_REDUCE_SLOTS, "2"); startCluster(true, props); LOG.info("Started the cluster"); ControlledMapReduceJobRunner jobRunner = ControlledMapReduceJobRunner .getControlledMapReduceJobRunner(createJobConf(), 7, 6); jobRunner.start(); ControlledMapReduceJob controlledJob = jobRunner.getJob(); JobInProgress jip = getMRCluster().getJobTrackerRunner().getJobTracker().getJob( jobRunner.getJobID()); ControlledMapReduceJob.waitTillNTasksStartRunning(jip, true, 4); LOG.info("Finishing 3 maps"); controlledJob.finishNTasks(true, 3); ControlledMapReduceJob.waitTillNTotalTasksFinish(jip, true, 3); ControlledMapReduceJob.waitTillNTasksStartRunning(jip, true, 4); LOG.info("Finishing 4 more maps"); controlledJob.finishNTasks(true, 4); ControlledMapReduceJob.waitTillNTotalTasksFinish(jip, true, 7); ControlledMapReduceJob.waitTillNTasksStartRunning(jip, false, 4); LOG.info("Finishing 2 reduces"); controlledJob.finishNTasks(false, 2); ControlledMapReduceJob.waitTillNTotalTasksFinish(jip, false, 2); ControlledMapReduceJob.waitTillNTasksStartRunning(jip, false, 4); LOG.info("Finishing 4 more reduces"); controlledJob.finishNTasks(false, 4); ControlledMapReduceJob.waitTillNTotalTasksFinish(jip, false, 6); jobRunner.join(); } }
package JZOF; /** * Created by yang on 2017/3/22. */ /* 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, 使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分 ,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 */ public class OddAheadEven { public void reOrderArrayCantStaySeq(int[] array) { if (array == null) { return; } int start = 0; int end = array.length - 1; while (start < end) { while ((start < end) && (array[start] & 1) == 1) { start++; } while ((start < end) && (array[end] & 1) == 0) { end--; } if (start < end) { int temp = array[start]; array[start] = array[end]; array[end] = temp; } } System.out.println('f'); } public void reOrderArray(int[] array) { if (array == null) { return; } int[] odd = new int[array.length]; int[] even = new int[array.length]; int evenCount = 0; int oddCount = 0; for (int i = 0; i < array.length; i++) { if ((array[i] & 1) == 0) { even[evenCount] = array[i]; evenCount++;} else { odd[oddCount] = array[i]; oddCount++; } } for (int i = 0; i < oddCount; i++) { array[i] = odd[i]; } for (int i = 0; i < evenCount; i++) { array[i + oddCount] = even[i]; } } public static void main(String[] args) { int[] array = new int[]{7, 3, 2, 4, 5, 6, 8, 9}; new OddAheadEven().reOrderArray(array); } }
package com.bbb.composite.product.details; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestExecutionListeners.MergeMode; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.BodySpec; import org.springframework.web.client.RestTemplate; import com.bbb.composite.product.details.dto.AttributeDTO; import com.bbb.composite.product.details.dto.ProductCompositeDTO; import com.bbb.composite.product.details.dto.price.ProductPriceDTO; import com.bbb.composite.product.details.dto.price.SkuPriceDTO; import com.bbb.composite.product.details.dto.product.BrandDTO; import com.bbb.composite.product.details.dto.product.ProductDTO; import com.bbb.composite.product.details.dto.sku.ColorVariantDTO; import com.bbb.composite.product.details.dto.sku.SKUVariantValuesDTO; import com.bbb.composite.product.details.dto.sku.SizeVariantDTO; import com.bbb.composite.product.details.dto.sku.SkuDTO; import com.bbb.composite.product.details.services.client.PriceIntegrationServiceImpl; import com.bbb.composite.product.details.services.client.ProductIntegrationServiceImpl; import com.bbb.composite.product.details.services.client.SkuIntegrationServiceImpl; import com.bbb.core.cache.dto.CacheableDTO; import com.bbb.core.cache.manager.CoreCacheManager; import com.bbb.core.dto.BaseServiceDTO; import com.bbb.core.dto.ServiceStatus; import com.bbb.core.exceptions.DataNotFoundException; import com.bbb.core.utils.CoreUtils; /** * This Controller provides all product related actions. * @author skhur6 * */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }, mergeMode = MergeMode.MERGE_WITH_DEFAULTS) @TestPropertySource(locations = "classpath:bootstrap-test_local.properties") public class ProductDetailsControllerTest { @LocalServerPort private int port; @Autowired private WebTestClient webTestClient; @MockBean private LoadBalancerClient loadBalancerClient; @Before public void setup() { this.webTestClient = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) .responseTimeout(Duration.ofSeconds(15000)).build(); } /*@MockBean private CoreRestTemplate coreRestTemplate;*/ @MockBean private CoreCacheManager coreCacheManager; @MockBean private RestTemplate defaultRestTemplate; @Value("${product-microservice.ribbon.listOfServers}") private String productMSservers; @Value("${price-microservice.ribbon.listOfServers}") private String priceMSServers; @Value("${sku-microservice.ribbon.listOfServers}") private String skuMSServers; @Test public void testHealthController() { String uri = "/health"; this.webTestClient.get().uri(uri) .accept(MediaType.APPLICATION_JSON_UTF8).exchange() .expectStatus().isOk(); } /** * This method just creates the dummy data. * @return * @throws DataNotFoundException */ @Test public void getProductDetailsNoCacheTest() { String productId = "productId_4"; String siteId = "siteId_2"; String channel = "web"; List<String> childSKUs = new ArrayList<>(); childSKUs.add("240"); childSKUs.add("241"); ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>> productCompositeType = new ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>>() {}; mockRedisLoadNotExistant(productId, siteId, channel, childSKUs); mockProductServiceAndLB(productId, siteId, childSKUs); mockSkuServiceAndLB(siteId, childSKUs); mockProductPriceServiceAndLB(productId, siteId); mockSkuPriceServiceAndLB(siteId, childSKUs); String uri = "/product-details/site/" + siteId + "/product/" + productId; BodySpec<BaseServiceDTO<ProductCompositeDTO>, ?> bodySpec = this.webTestClient.get().uri(uri) .accept(MediaType.APPLICATION_JSON_UTF8).exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody(productCompositeType); assertNotNull(bodySpec); BaseServiceDTO<ProductCompositeDTO> responseBody = bodySpec.returnResult().getResponseBody(); assertNotNull(responseBody); assertEquals(responseBody.getServiceStatus(), ServiceStatus.SUCCESS); assertEquals(responseBody.getData().getProductId(), productId); } @Test public void getProductDetailsFromCacheTest() { String productId = "productId_4"; String siteId = "siteId_2"; String channel = "web"; List<String> childSKUs = new ArrayList<>(); childSKUs.add("240"); childSKUs.add("241"); ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>> productCompositeType = new ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>>() {}; mockRedisLoadExistant(productId, siteId, channel, childSKUs); mockProductServiceAndLB(productId, siteId, childSKUs); mockSkuServiceAndLB(siteId, childSKUs); mockProductPriceServiceAndLB(productId, siteId); mockSkuPriceServiceAndLB(siteId, childSKUs); String uri = "/product-details/site/" + siteId + "/product/" + productId + "?channel=" + channel; BodySpec<BaseServiceDTO<ProductCompositeDTO>, ?> bodySpec = this.webTestClient.get().uri(uri) .accept(MediaType.APPLICATION_JSON_UTF8).exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody(productCompositeType); assertNotNull(bodySpec); BaseServiceDTO<ProductCompositeDTO> responseBody = bodySpec.returnResult().getResponseBody(); assertNotNull(responseBody); assertEquals(responseBody.getServiceStatus(), ServiceStatus.SUCCESS); assertEquals(responseBody.getData().getProductId(), productId); } @Test public void getProductDetailsNegativeTest() { String productId = "10417205479"; String siteId = "siteId_2"; String channel = "web"; List<String> childSKUs = new ArrayList<>(); childSKUs.add("240"); childSKUs.add("241"); ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>> productCompositeType = new ParameterizedTypeReference<BaseServiceDTO<ProductCompositeDTO>>() {}; String uri = "/product-details/site/" + siteId + "/product/" + productId + "?channel=" + channel; BodySpec<BaseServiceDTO<ProductCompositeDTO>, ?> bodySpec = this.webTestClient.get().uri(uri) .accept(MediaType.APPLICATION_JSON_UTF8).exchange() .expectStatus().isNotFound() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody(productCompositeType); assertNotNull(bodySpec); BaseServiceDTO<ProductCompositeDTO> responseBody = bodySpec.returnResult().getResponseBody(); assertNotNull(responseBody); assertEquals(responseBody.getServiceStatus(), ServiceStatus.ERROR); } private void mockRedisLoadNotExistant(String productId, String siteId, String bbbChannel, List<String> childSKUs) { Mockito.when(coreCacheManager.getFromCacheSingle(Mockito.anyString(), Mockito.any())) .thenReturn(null); } private void mockRedisLoadExistant(String productId, String siteId, String bbbChannel, List<String> childSKUs) { String productDtoKey = this.getProductCacheKey(productId, siteId, bbbChannel); ResponseEntity<BaseServiceDTO<ProductDTO>> responseEntity = createProductDummyData(productId, childSKUs); BaseServiceDTO<ProductDTO> baseServiceDTO = responseEntity.getBody(); CacheableDTO<BaseServiceDTO<ProductDTO>> cacheableDTO = new CacheableDTO<>(); cacheableDTO.setKey(productDtoKey); cacheableDTO.setData(baseServiceDTO); Mockito.when(coreCacheManager.getFromCacheSingle(productDtoKey, ProductDTO.class)) .thenReturn(cacheableDTO); String productPriceCacheKey = this.getProductPriceCacheKey(siteId, productId, bbbChannel); ResponseEntity<BaseServiceDTO<ProductPriceDTO>> responseEntity2 = createProductPriceDummyData(productId, siteId); BaseServiceDTO<ProductPriceDTO> baseServiceDTO2 = responseEntity2.getBody(); CacheableDTO<BaseServiceDTO<ProductPriceDTO>> cacheableDTO2 = new CacheableDTO<>(); cacheableDTO2.setKey(productPriceCacheKey); cacheableDTO2.setData(baseServiceDTO2); Mockito.when(coreCacheManager.getFromCacheSingle(productPriceCacheKey, ProductPriceDTO.class)) .thenReturn(cacheableDTO2); String skuPriceCacheKey = this.getSkuPriceCacheKey(siteId, childSKUs, bbbChannel); ResponseEntity<BaseServiceDTO<List<SkuPriceDTO>>> responseEntity3 = createSkuPriceDummyData(siteId, childSKUs); BaseServiceDTO<List<SkuPriceDTO>> baseServiceDTO3 = responseEntity3.getBody(); CacheableDTO<BaseServiceDTO<List<SkuPriceDTO>>> cacheableDTO3 = new CacheableDTO<>(); cacheableDTO3.setKey(skuPriceCacheKey); cacheableDTO3.setData(baseServiceDTO3); Mockito.when(coreCacheManager.getFromCacheList(skuPriceCacheKey, SkuPriceDTO.class)) .thenReturn(cacheableDTO3); String skusCacheKey = this.getSkusCacheKey(siteId, childSKUs, bbbChannel); ResponseEntity<BaseServiceDTO<List<SkuDTO>>> responseEntity4 = createSkuDummyData(childSKUs); BaseServiceDTO<List<SkuDTO>> baseServiceDTO4 = responseEntity4.getBody(); CacheableDTO<BaseServiceDTO<List<SkuDTO>>> cacheableDTO4 = new CacheableDTO<>(); cacheableDTO4.setKey(skusCacheKey); cacheableDTO4.setData(baseServiceDTO4); Mockito.when(coreCacheManager.getFromCacheList(skusCacheKey, SkuDTO.class)) .thenReturn(cacheableDTO4); } private void mockProductServiceAndLB(String productId, String siteId, List<String> childSKUs) { String productUrl = mockLoadBalancerAndGetUrl(ProductIntegrationServiceImpl.CLIENT_ID, productMSservers , "/product/site/{siteId}/product/{productId}"); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(productId); ParameterizedTypeReference<BaseServiceDTO<ProductDTO>> RESPONSE_TYPE = new ParameterizedTypeReference<BaseServiceDTO<ProductDTO>>() {}; Mockito.when(defaultRestTemplate.exchange(productUrl, HttpMethod.GET, entity, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createProductDummyData(productId, childSKUs)); } private void mockSkuServiceAndLB(String siteId, List<String> childSKUs) { String skuUrl = mockLoadBalancerAndGetUrl(SkuIntegrationServiceImpl.CLIENT_ID , skuMSServers, "/sku/site/{siteId}/sku/{childSkus}"); List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(childSKUs); ParameterizedTypeReference<BaseServiceDTO<List<SkuDTO>>> RESPONSE_TYPE = new ParameterizedTypeReference<BaseServiceDTO<List<SkuDTO>>>() {}; Mockito.when(defaultRestTemplate.exchange(skuUrl, HttpMethod.GET, null, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createSkuDummyData(childSKUs)); } private void mockProductPriceServiceAndLB(String productId, String siteId) { String priceUrl = mockLoadBalancerAndGetUrl(PriceIntegrationServiceImpl.CLIENT_ID, skuMSServers, "/price/site/{siteId}/product/{productId}"); List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(productId); ParameterizedTypeReference<BaseServiceDTO<ProductPriceDTO>> RESPONSE_TYPE = new ParameterizedTypeReference<BaseServiceDTO<ProductPriceDTO>>() {}; Mockito.when(defaultRestTemplate.exchange(priceUrl, HttpMethod.GET, null, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createProductPriceDummyData(productId, siteId)); } private void mockSkuPriceServiceAndLB(String siteId, List<String> childSKUs) { String priceUrl = mockLoadBalancerAndGetUrl(PriceIntegrationServiceImpl.CLIENT_ID, skuMSServers, "/price/site/{siteId}/sku/{skuId}"); List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(childSKUs); ParameterizedTypeReference<BaseServiceDTO<List<SkuPriceDTO>>> RESPONSE_TYPE = new ParameterizedTypeReference<BaseServiceDTO<List<SkuPriceDTO>>>() {}; Mockito.when(defaultRestTemplate.exchange(priceUrl, HttpMethod.GET, null, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createSkuPriceDummyData(siteId, childSKUs)); } private String mockLoadBalancerAndGetUrl(String clientId, String serverHostNPort, String uri) { String[] serversList = serverHostNPort.split(","); String hostNPort = serversList[0]; String[] hostNPortArray = hostNPort.split(":"); String host = hostNPortArray[0]; int port = 0; if (hostNPortArray.length > 1) { port = Integer.parseInt(hostNPortArray[1]); } Mockito.when(loadBalancerClient.choose(clientId)).thenReturn(new DefaultServiceInstance(clientId, host, port, false)); return "http://" + host +":" + port + uri; } private ResponseEntity<BaseServiceDTO<ProductDTO>> createProductDummyData(String productId, List<String> childSKUs) { ProductDTO productDTO = createProductData(productId, childSKUs); BaseServiceDTO<ProductDTO> baseServiceDTO = new BaseServiceDTO<>(); baseServiceDTO.setData(productDTO); baseServiceDTO.setResponseSentTime(Instant.now()); baseServiceDTO.setServiceStatus(ServiceStatus.SUCCESS); baseServiceDTO.setPageSize(1); baseServiceDTO.setPageFrom(1); baseServiceDTO.setPageTo(1); return new ResponseEntity<BaseServiceDTO<ProductDTO>>(baseServiceDTO, HttpStatus.OK); } private ProductDTO createProductData(String productId, List<String> childSKUs) { ProductDTO productDTO = new ProductDTO(); productDTO.setProductId(productId); productDTO.setChildSKUs(childSKUs); BrandDTO brandDto = new BrandDTO(); brandDto.setBrandId("12432"); brandDto.setBrandDesc("Ralph Lauren"); brandDto.setBrandImage("/Image"); brandDto.setBrandName("Ralph Lauren"); productDTO.setBrandDTO(brandDto); productDTO.setProductAttributes(getAttributeList()); return productDTO; } private List<AttributeDTO> getAttributeList() { List<AttributeDTO> attributes = new ArrayList<>(); AttributeDTO attributeDto = new AttributeDTO(); attributeDto.setAttributeName("Shipping Msg"); attributeDto.setPlaceHolder("PDPP,PDPC"); attributeDto.setStartDate(Instant.now().minus(2, ChronoUnit.DAYS)); attributeDto.setEndDate(Instant.now().plus(2, ChronoUnit.DAYS)); attributes.add(attributeDto); AttributeDTO attributeDto1 = new AttributeDTO(); attributeDto1.setAttributeName("Single Day Delivery"); attributeDto1.setPlaceHolder("PDPP"); attributeDto1.setStartDate(Instant.now().minus(2, ChronoUnit.DAYS)); attributeDto1.setEndDate(Instant.now().plus(2, ChronoUnit.DAYS)); attributes.add(attributeDto1); return attributes; } private ResponseEntity<BaseServiceDTO<List<SkuDTO>>> createSkuDummyData(List<String> childSKUs) { List<SkuDTO> skuDtos = new ArrayList<>(); for (int i=0; i<2; i++) { SkuDTO skuDTO = new SkuDTO(); skuDTO.setSkuId("24"+i); SKUVariantValuesDTO skuVariantValues = new SKUVariantValuesDTO(); ColorVariantDTO colorVariantDto = new ColorVariantDTO(); colorVariantDto.setColorCode("RED"); colorVariantDto.setDisplayName("RED"); skuVariantValues.setColorVariant(colorVariantDto); SizeVariantDTO sizeVariantDTO = new SizeVariantDTO(); sizeVariantDTO.setSizeCode("Large"); sizeVariantDTO.setDisplayName("Large"); skuVariantValues.setSizeVariant(sizeVariantDTO); skuDTO.setSkuVariantValues(skuVariantValues); skuDtos.add(skuDTO); skuDTO.setSkuAttributes(getAttributeList()); } BaseServiceDTO<List<SkuDTO>> baseServiceDTO = new BaseServiceDTO<>(); baseServiceDTO.setData(skuDtos); baseServiceDTO.setResponseSentTime(Instant.now()); baseServiceDTO.setServiceStatus(ServiceStatus.SUCCESS); baseServiceDTO.setPageSize(1); baseServiceDTO.setPageFrom(1); baseServiceDTO.setPageTo(1); return new ResponseEntity<BaseServiceDTO<List<SkuDTO>>>(baseServiceDTO, HttpStatus.OK); } private ResponseEntity<BaseServiceDTO<ProductPriceDTO>> createProductPriceDummyData(String productId, String siteId) { ProductPriceDTO productPriceDTO = new ProductPriceDTO(); productPriceDTO.setProductId(productId); productPriceDTO.setSiteId(siteId); productPriceDTO.setProductLowListPrice(new BigDecimal(2.4)); productPriceDTO.setProductHighListPrice(new BigDecimal(5)); productPriceDTO.setProductLowSalePrice(new BigDecimal(2)); productPriceDTO.setProductHighSalePrice(new BigDecimal(4)); productPriceDTO.setPriceRangeDescription("%L - %H"); BaseServiceDTO<ProductPriceDTO> baseServiceDTO = new BaseServiceDTO<>(); baseServiceDTO.setData(productPriceDTO); baseServiceDTO.setResponseSentTime(Instant.now()); baseServiceDTO.setServiceStatus(ServiceStatus.SUCCESS); baseServiceDTO.setPageSize(1); baseServiceDTO.setPageFrom(1); baseServiceDTO.setPageTo(1); return new ResponseEntity<BaseServiceDTO<ProductPriceDTO>>(baseServiceDTO, HttpStatus.OK); } private ResponseEntity<BaseServiceDTO<List<SkuPriceDTO>>> createSkuPriceDummyData(String siteId, List<String> childSkus) { List<SkuPriceDTO> skuPriceDTOs = new ArrayList<>(); for (String childSku: childSkus){ SkuPriceDTO skuPriceDTO = new SkuPriceDTO(); skuPriceDTO.setSiteId(siteId); skuPriceDTO.setSkuId(childSku); skuPriceDTO.setSkuListPrice(new BigDecimal(10)); skuPriceDTO.setSkuSalePrice(new BigDecimal(8)); skuPriceDTOs.add(skuPriceDTO); } BaseServiceDTO<List<SkuPriceDTO>> baseServiceDTO = new BaseServiceDTO<>(); baseServiceDTO.setData(skuPriceDTOs); baseServiceDTO.setResponseSentTime(Instant.now()); baseServiceDTO.setServiceStatus(ServiceStatus.SUCCESS); baseServiceDTO.setPageSize(1); baseServiceDTO.setPageFrom(1); baseServiceDTO.setPageTo(1); return new ResponseEntity<BaseServiceDTO<List<SkuPriceDTO>>>(baseServiceDTO, HttpStatus.OK); } private String getProductCacheKey(String productId, String siteId, String bbbChannel) { StringBuilder sb = new StringBuilder(); sb.append("product-microservice").append("-siteId-").append(siteId).append("-productId-").append(productId); if (StringUtils.isNotBlank(bbbChannel)) { sb.append("-bbbChannel-").append(bbbChannel); } return sb.toString(); } private String getProductPriceCacheKey(String siteId, String productId, String bbbChannel) { StringBuilder sb = new StringBuilder(); sb.append("price-microservice").append("-siteId-").append(siteId) .append("-productId-").append(productId); if (StringUtils.isNotBlank(bbbChannel)) { sb.append("-bbbChannel-").append(bbbChannel); } return sb.toString(); } private String getSkuPriceCacheKey(String siteId, List<String> skus, String bbbChannel) { StringBuilder sb = new StringBuilder(); sb.append("price-microservice").append("-siteId-").append(siteId); if(CollectionUtils.isNotEmpty(skus)) { sb.append("-skuIds-"); for (int i=0; i< skus.size(); i++) { String sku = skus.get(i); sb.append(sku); if(i < (skus.size() - 1)) { sb.append("-"); } } } if (StringUtils.isNotBlank(bbbChannel)) { sb.append("-bbbChannel-").append(bbbChannel); } return sb.toString(); } private String getSkusCacheKey(String siteId, List<String> childSkus, String bbbChannel) { StringBuilder sb = new StringBuilder(); sb.append("sku-microservice").append("-siteId-").append(siteId); if(CollectionUtils.isNotEmpty(childSkus)) { sb.append("-skuIds-"); for (int i=0; i< childSkus.size(); i++) { String sku = childSkus.get(i); sb.append(sku); if(i < (childSkus.size() - 1)) { sb.append("-"); } } } if (StringUtils.isNotBlank(bbbChannel)) { sb.append("-bbbChannel-").append(bbbChannel); } return sb.toString(); } }
/* 异常-处理语句的其他格式 格式1 try{ }catch(){ }finally{ } 格式2 try{ }catch(){ } 格式3 try{ }finally{ } 注意: catch 是用于处理异常的。如果没有catch就代表异常没有被处理过, 如果该异常是编译时异常。那么必须被声明 */ class Demo{ public void method(){ // 不用throws, 问题在内部被解决,程序可以编译通过 try{ throw new Exception(); }catch(Exception e){ // 只要问题被解决,问题可以不声明;问题没有被解决就一定要声明出去; // (有catch就是解决问题) } } } class Demo{ public void method(){ try{ throw new Exception(); }catch(Exception e){ throw e; // 编译无法通过,虽然有catch,但是又把 问题抛了出去 } } } class Demo{ public void method(){ try{ throw new Exception(); }catch(Exception e){ try{ throw e; // 编译可以通过。e被处理了 } catch(Exception e_b){ } } } } class Demo{ public void method(){ try{ throw new Exception(); // 没有catch,要声明出去 } finally{ // 关资源。 } // 如果你在一个功能当中定义了一些必须要执行的代码的话, // 那么就用try finally的形式把一定要执行的代码存放在 finally 当中 } }
package com.mundo.core.support; import org.junit.Test; /** * StackPointerTest * * @author maodh * @since 04/02/2018 */ public class StackPointerTest { @Test public void printStackTrace() { StackPointer.printStackTrace("hello stack"); } }
package com.zhouyi.business.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * @author 李秸康 * @ClassNmae: SysUnitDto * @Description: TODO * @date 2019/6/21 18:01 * @Version 1.0 **/ @ApiModel(value = "部门分页条件对象模型") public class SysUnitDto extends PageDto implements Serializable { @ApiModelProperty(value = "排序的字段") private String field; //排序的字段 @ApiModelProperty(value = "上级部门编码") private String parentId; public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getField() { return field; } public void setField(String field) { this.field = field; } }
public class salException extends Exception{ public void salError(){ System.out.println("Salário tem que ser maior que R$ 950,00"); } }
package com.zpjr.cunguan.action.impl.setting; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.zpjr.cunguan.action.action.setting.ISmsSubscribeAction; import com.zpjr.cunguan.common.base.BaseAction; import com.zpjr.cunguan.common.retrofit.MyCallBack; import com.zpjr.cunguan.common.retrofit.PresenterCallBack; import java.util.Map; import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Path; /** * Description: 营销短信订阅-action * Autour: LF * Date: 2017/8/22 16:34 */ public class SmsSubscribeActionImpl extends BaseAction implements ISmsSubscribeAction { @Override public void isSubscribeSms(String userId, String flag, final PresenterCallBack callBack) { setAuthService(); Call<JsonObject> call = mService.isSubscribeSms(userId, flag); call.enqueue(new MyCallBack<JsonObject>() { @Override public void onSuccess(Response<JsonObject> response) { callBack.onSuccess(response.body()); } @Override public void onFail(String message) { callBack.onFail(message); } }); } }
package cn.droidlover.xdroid.demo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.util.Log; import android.widget.ImageView; import com.zhy.http.okhttp.callback.StringCallback; import java.io.File; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.droidlover.xdroid.demo.adapter.ShortVideoAdapter; import cn.droidlover.xdroid.demo.kit.AppKit; import cn.droidlover.xdroid.demo.kit.ThumbLoad; import cn.droidlover.xdroid.demo.model.MovieInfo; import cn.droidlover.xdroid.demo.net.JsonCallback; import cn.droidlover.xdroid.demo.net.NetApi; import okhttp3.Call; /** * Created by Administrator on 2017/5/28 0028. */ public class VideoManager extends Thread { private DBManager mDbManager = null; private User mUser = null; private int mReConnectNum = 0; private Map<String,MovieInfo.Item> mMovies = new HashMap<String,MovieInfo.Item>(); private Map<String,List<MovieInfo.Item> > mMovieSeries = new HashMap<String,List<MovieInfo.Item>>(); private Map<String ,List<MovieInfo.Item> > mTypeMovies = new HashMap<String,List<MovieInfo.Item> >(); private Map<String,ImageView> mThumbImageView = new HashMap<String,ImageView>(); private String mCurrentType = "0"; private int mLastType = 0; private int mCurrentPos = 0; private int mLastPos = 0; private boolean mStopDecodeThumb = false; private Map<String,ThumbCache> mMovieThumbCaches = new HashMap<String,ThumbCache>(); class ThumbCache{ Bitmap bitmap; String type; int pos; } private VideoManager(){ mDbManager = new DBManager(App.getContext()); mUser = User.getInstance(); //this.start(); }; @Override public void run() { while (!mStopDecodeThumb){ Log.i(App.TAG,"try decoder thumb once"); try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();} synchronized (mMovieThumbCaches){ if(!mTypeMovies.containsKey(mCurrentType)){ Log.e(App.TAG,"mTypeMovies do not contains key " + mCurrentType); try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} continue; } List<MovieInfo.Item> movies = mTypeMovies.get(mCurrentType); int pos = movies.size() - mCurrentPos - 1; if(mMovieThumbCaches.size() > 31){ for (String key : mMovieThumbCaches.keySet()) { ThumbCache thumbCache = mMovieThumbCaches.get(key); boolean needRecycle = false; if(!thumbCache.type.equals(mCurrentType) ){ needRecycle = true; } if(!needRecycle && thumbCache.pos > pos + 15 && thumbCache.pos < pos - 15){ needRecycle = true; } if(needRecycle){ thumbCache = mMovieThumbCaches.remove(key); if(!thumbCache.bitmap.isRecycled()){ thumbCache.bitmap.recycle(); } break; } } } boolean doDecodeThumb = false; for(int i = 0;i < 16;i++){ int curPos = pos - i; MovieInfo.Item item = null; if(curPos >= 0 && curPos < movies.size()){ item = movies.get(curPos); if(item != null){ if(!mMovieThumbCaches.containsKey(item.getMovie_id())){ doDecodeThumb = true; } } } if(!doDecodeThumb){ curPos = pos + i; if(curPos >= 0 && curPos < movies.size()){ item = movies.get(curPos); if(item != null){ if(!mMovieThumbCaches.containsKey(item.getMovie_id())){ doDecodeThumb = true; } } } } if(doDecodeThumb){ Bitmap bitmap = ThumbLoad.getInstance().getThumb(item.getMovie_id()); ThumbCache thumbCache = new ThumbCache(); thumbCache.bitmap = bitmap; thumbCache.pos = curPos; thumbCache.type = mCurrentType; mMovieThumbCaches.put(item.getMovie_id(),thumbCache); if(item.getSet_name() != null && item.getSet_name().length() > 0){ List<MovieInfo.Item> movieSets = mMovieSeries.get(item.getSet_name()); for(int j = 1;j < 4 && j < movieSets.size();j++){ MovieInfo.Item itemSet = movieSets.get(j); bitmap = ThumbLoad.getInstance().getThumb(itemSet.getMovie_id()); thumbCache = new ThumbCache(); thumbCache.bitmap = bitmap; thumbCache.pos = curPos; thumbCache.type = mCurrentType; mMovieThumbCaches.put(itemSet.getMovie_id(),thumbCache); } } break; } } if(!doDecodeThumb){ try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();} continue; }else{ try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} continue; } } } } public boolean getVideos(final int videoType, int id, final JsonCallback<MovieInfo> callback){ if(id == -1){ /*if(!getVideosFromLocal(videoType,callback)){ getVideosFromServer(videoType,10,callback); }*/ return getVideosFromLocal(videoType,callback); }else { getVideosFromServer(videoType,null,id,callback); } return true; } public void getSeriesVideos(String seriesName,int startId,final JsonCallback<MovieInfo> callback){ if(startId == -1){ if(mMovieSeries.containsKey(seriesName)){ List<MovieInfo.Item> movies = mMovieSeries.get(seriesName); MovieInfo movieInfo = new MovieInfo(); movieInfo.setResults(movies); callback.onResponse(movieInfo,0); } }else{ getVideosFromServer(0,seriesName,startId,callback); } } public static final class ComparatorEnShrineTimeMovieItem implements Comparator<MovieInfo.Item> { @Override public int compare(MovieInfo.Item object1, MovieInfo.Item object2) { return object1.getEnshrineTime().compareTo(object2.getEnshrineTime()); } } public void getEnShrineVideos(final JsonCallback<MovieInfo> callback){ MovieInfo movieInfo = new MovieInfo(); List<MovieInfo.Item> movies = new ArrayList<MovieInfo.Item>(); movieInfo.setResults(movies); for (Map.Entry<String, MovieInfo.Item> entry : mMovies.entrySet()){ MovieInfo.Item item = entry.getValue(); if(item.getIsEnshrine().equals("1")){ movies.add(item); } } Collections.sort(movies,new ComparatorEnShrineTimeMovieItem()); callback.onResponse(movieInfo,0); } public static final class ComparatorPlayTimeMovieItem implements Comparator<MovieInfo.Item> { @Override public int compare(MovieInfo.Item object1, MovieInfo.Item object2) { return object1.getPlayTime().compareTo(object2.getPlayTime()); } } public void getHasPlayVideos(final JsonCallback<MovieInfo> callback){ MovieInfo movieInfo = new MovieInfo(); List<MovieInfo.Item> movies = new ArrayList<MovieInfo.Item>(); movieInfo.setResults(movies); for (Map.Entry<String, MovieInfo.Item> entry : mMovies.entrySet()){ MovieInfo.Item item = entry.getValue(); if(item.getIsPlay().equals("1")){ movies.add(item); } } Collections.sort(movies, new ComparatorPlayTimeMovieItem()); callback.onResponse(movieInfo,0); } public void modifyMovieInfo(String movieId, Map<String,String> modifyMovieInfos){ Log.i(App.TAG,"modifyMovieInfo enter"); HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","modify_movie_info"); params.put("movie_id",movieId); MovieInfo.Item movieItem = mMovies.get(movieId); for (Map.Entry<String, String> entry : modifyMovieInfos.entrySet()) { if(entry.getKey().equals("title")){ movieItem.setTitle(entry.getValue()); } if(entry.getKey().equals("score")){ movieItem.setScore(entry.getValue()); } if(entry.getKey().equals("pic_score")){ movieItem.setPic_score(entry.getValue()); } if(entry.getKey().equals("value")){ movieItem.setValue(entry.getValue()); } if(entry.getKey().equals("sub_type1")){ movieItem.setSub_type1(entry.getValue()); } } mDbManager.update(movieId,modifyMovieInfos); for (Map.Entry<String, String> entry : modifyMovieInfos.entrySet()) { Log.i(App.TAG,"modifyMovieInfo Key = " + entry.getKey() + ", Value = " + entry.getValue()); params.put(entry.getKey(),entry.getValue()); } NetApi.invokeGet(params,null); } public boolean getVideoPraise(final String movieId, final User.GetVideoPraiseCallback callback){ StringCallback stringCallback = new StringCallback() { @Override public void onError(Call call, Exception e, int id) { e.printStackTrace(); } @Override public void onResponse(String response, int id) { callback.onGetVideoPraise(response); } }; HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","fetch_video_praise"); params.put("movie_id",movieId); NetApi.invokeGet(params,stringCallback); return true; } public boolean addVideoPraise(final String movieId){ HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","add_video_praise"); params.put("movie_id",movieId); NetApi.invokeGet(params,null); Map<String,String> mapMovieInfos = new HashMap<String,String>(); mapMovieInfos.put("isPraise","1"); mDbManager.update(movieId,mapMovieInfos); return true; } public boolean setEnshrine(final String movieId,String isEnshrine){ Map<String,String> mapMovieInfos = new HashMap<String,String>(); mapMovieInfos.put("isEnshrine",isEnshrine); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); String t = format.format(new Date()); mapMovieInfos.put("enshrineTime",t); mDbManager.update(movieId,mapMovieInfos); HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","set_enshrine_video"); params.put("movie_id",movieId); params.put("user_id",User.getInstance().getUserId()); params.put("enshrine",isEnshrine); NetApi.invokeGet(params,null); return true; } public boolean getPlayUrl(final String movieId, final User.GetPlayUrlCallback callback){ final JsonCallback<ShortVideoAdapter.GetPlayUrlResult> localCallback =new JsonCallback<ShortVideoAdapter.GetPlayUrlResult>() { @Override public void onFail(Call call, Exception e, int id) { e.printStackTrace(); boolean isSocketTimeoutException = e instanceof SocketTimeoutException; if(isSocketTimeoutException){ mReConnectNum++; if(mReConnectNum < 5){ AppKit.updateServerUrl(); getPlayUrl(movieId,callback); }else { callback.onGetPlayUrl(null); } }else { callback.onGetPlayUrl(null); } } @Override public void onResponse(ShortVideoAdapter.GetPlayUrlResult response, int id) { callback.onGetPlayUrl(response); if(response.state){ Map<String,String> mapMovieInfos = new HashMap<String,String>(); mapMovieInfos.put("isPlay","1"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); String t = format.format(new Date()); mapMovieInfos.put("playTime",t); mDbManager.update(movieId,mapMovieInfos); } } }; HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","fetch_play_url"); params.put("user_id",User.getInstance().getUserId()); params.put("signature", User.getInstance().getSignature()); params.put("movie_id",movieId); if(hasCache(movieId)){ params.put("isPay","true"); }else { params.put("isPay","false"); } NetApi.invokeGet(params,localCallback); return true; } public MovieInfo.Item getMovieInfoItem(String movieId){ if(mMovies.containsKey(movieId)){ return mMovies.get(movieId); } return null; } public List<MovieInfo.Item> getMovieSet(String setName){ if(mMovieSeries.containsKey(setName)){ return mMovieSeries.get(setName); } return null; } public void setThumbToImageView(String movieId,String type, int pos, ImageView imageView){ Log.i(App.TAG,"setThumbToImageView enter"); //synchronized (mMovieThumbCaches){ mCurrentPos = pos; mCurrentType = type; if(mMovieThumbCaches.containsKey(movieId)){ ThumbCache thumbCache = mMovieThumbCaches.get(movieId); imageView.setImageBitmap(thumbCache.bitmap); } // } Log.i(App.TAG,"setThumbToImageView leave"); } private boolean getVideosFromLocal(final int videoType,final JsonCallback<MovieInfo> callback){ Log.i(App.TAG,"getVideosFromLocal"); List<MovieInfo.Item> movies = mDbManager.query("" + videoType); List<MovieInfo.Item> movie2s = new ArrayList<MovieInfo.Item>(); List<MovieInfo.Item> movie3s = null; if(mTypeMovies.containsKey(videoType + "")){ movie3s = mTypeMovies.get(videoType + ""); }else{ movie3s = new ArrayList<MovieInfo.Item>(); mTypeMovies.put(videoType + "",movie3s); } for(int i = 0;i < movies.size();i++){ MovieInfo.Item item = movies.get(i); if(!mMovies.containsKey(item.getMovie_id())){ mMovies.put(item.getMovie_id(),item); } if(item.getSet_name() != null && item.getSet_name().length() > 0){ if(mMovieSeries.containsKey(item.getSet_name())){ List<MovieInfo.Item>movieItems = mMovieSeries.get(item.getSet_name()); movieItems.add(item); }else{ movie2s.add(item); movie3s.add(item); List<MovieInfo.Item>movieItems = new ArrayList<MovieInfo.Item>(); movieItems.add(item); mMovieSeries.put(item.getSet_name(),movieItems); } }else{ movie2s.add(item); movie3s.add(item); } } MovieInfo movieInfo = new MovieInfo(); movieInfo.setResults(movie2s); callback.onResponse(movieInfo,0); return movie2s.size() > 0; } private void getVideosFromServer(final int videoType,final String seriesVideoName,final int id_index, final JsonCallback<MovieInfo> callback){ final JsonCallback<MovieInfo> localCallback = new JsonCallback<MovieInfo>() { @Override public void onFail(Call call, Exception e, int id) { if(e instanceof SocketTimeoutException && mReConnectNum < 5){ mReConnectNum++; AppKit.updateServerUrl(); getVideosFromServer(videoType,seriesVideoName,id_index,callback); }else { callback.onFail(call,e,id); mReConnectNum = 0; } } @Override public void onResponse(MovieInfo response, int id) { if(response != null && !response.isError()){ List<MovieInfo.Item> movies = mDbManager.add(response.getResults()); List<MovieInfo.Item> movie2s = new ArrayList<MovieInfo.Item>(); List<MovieInfo.Item> movie3s = null; if(mTypeMovies.containsKey(videoType + "")){ movie3s = mTypeMovies.get(videoType + ""); }else{ movie3s = new ArrayList<MovieInfo.Item>(); mTypeMovies.put(videoType + "",movie3s); } for(int i = 0;i < movies.size();i++){ MovieInfo.Item item = movies.get(i); if(!mMovies.containsKey(item.getMovie_id())){ mMovies.put(item.getMovie_id(),item); } if(item.getSet_name() != null && item.getSet_name().length() > 0){ if(mMovieSeries.containsKey(item.getSet_name())){ List<MovieInfo.Item>movieItems = mMovieSeries.get(item.getSet_name()); movieItems.add(item); }else{ movie2s.add(item); movie3s.add(item); List<MovieInfo.Item>movieItems = new ArrayList<MovieInfo.Item>(); movieItems.add(item); mMovieSeries.put(item.getSet_name(),movieItems); } }else{ movie2s.add(item); movie3s.add(item); } } MovieInfo movieInfo = new MovieInfo(); if(seriesVideoName != null && seriesVideoName.length() > 0){ movieInfo.setResults(mMovieSeries.get(seriesVideoName)); }else{ movieInfo.setResults(movie2s); } callback.onResponse(movieInfo,id); } mReConnectNum = 0; } }; HashMap<String, String> params = new HashMap<String, String>(); params.put("request_type","fetch_video_info"); params.put("user_id",User.getInstance().getUserId()); params.put("signature", User.getInstance().getSignature()); params.put("video_type","" + videoType); params.put("id_index","" + id_index); if(seriesVideoName != null && seriesVideoName.length() > 0){ params.put("series_video_name","" + seriesVideoName); } NetApi.invokeGet(params,localCallback); } public boolean hasCache(String movieId){ String cachePathName = AppKit.getMediaCachePath() + "/" + movieId + ".data"; File file = new File(cachePathName); return file.exists(); } private static VideoManager mVideoManager = null; public static VideoManager getInstance(){ if(mVideoManager == null){ mVideoManager = new VideoManager(); return mVideoManager; } return mVideoManager; } private class DBHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; public DBHelper(Context context) { super(context, android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/XDroid/19porn_videos.db", null, DATABASE_VERSION); } //数据库第一次被创建时onCreate会被调用 @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS video_info" + "(id mediumint PRIMARY KEY,movie_id VARCHAR, title VARCHAR,score tinyint,pic_score tinyint,sub_type1 VARCHAR,type VARCHAR,duration VARCHAR, value VARCHAR, set_name VARCHAR,thumb_path VARCHAR,thumb_pos bigint,thumb_size int,thumb_key VARCHAR,grade int,isPraise int,isEnshrine int,isPlay int,enshrineTime VARCHAR,playTime VARCHAR)"); } //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //db.execSQL("ALTER TABLE person ADD COLUMN other STRING"); } } private class DBManager { private DBHelper helper; private SQLiteDatabase db; public DBManager(Context context) { helper = new DBHelper(context); db = helper.getWritableDatabase(); } public List<MovieInfo.Item> add(List<MovieInfo.Item> movies) { Log.i(App.TAG,"add movie size = " + movies.size()); List<MovieInfo.Item> results = new ArrayList<MovieInfo.Item>(); db.beginTransaction(); //开始事务 try { for (MovieInfo.Item movie : movies) { Cursor c = queryMovie(movie.getMovie_id()); if(c.getCount() == 0){ db.execSQL("INSERT INTO video_info VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", new Object[]{Integer.parseInt(movie.getId()), movie.getMovie_id(), movie.getTitle(),movie.getScore(),movie.getPic_score(),movie.getSub_type1(),movie.getType(), movie.getDuration(),movie.getValue(),movie.getSet_name(),movie.getThumb_url(),movie.getThumb_pos(),movie.getThumb_size(),movie.getThumb_key(),movie.getGrade(),movie.getIsPraise(),movie.getIsEnshrine(),movie.getIsPlay(),movie.getEnshrineTime(),movie.getPlayTime()}); results.add(movie); } } db.setTransactionSuccessful(); //设置事务成功完成 }catch (Exception e){ e.printStackTrace(); return results; } finally { db.endTransaction(); //结束事务 } return results; } public void update(String movieId, Map<String,String> modifyMovieInfos){ ContentValues cv = new ContentValues(); for (Map.Entry<String, String> entry : modifyMovieInfos.entrySet()) { cv.put(entry.getKey(), entry.getValue()); } String[] args = {movieId}; db.update("video_info",cv,"movie_id=?",args); } public List<MovieInfo.Item> query(String videoType) { ArrayList<MovieInfo.Item> movies = new ArrayList<MovieInfo.Item>(); Cursor c = queryTheCursor(videoType); while (c.moveToNext()) { MovieInfo.Item movie = new MovieInfo.Item(); movie.setId(c.getInt(c.getColumnIndex("id")) + ""); movie.setMovie_id(c.getString(c.getColumnIndex("movie_id"))); movie.setTitle(c.getString(c.getColumnIndex("title"))); movie.setDuration(c.getString(c.getColumnIndex("duration"))); movie.setValue(c.getString(c.getColumnIndex("value"))); movie.setThumb_key(c.getString(c.getColumnIndex("thumb_key"))); movie.setThumb_size(c.getString(c.getColumnIndex("thumb_size"))); movie.setThumb_pos(c.getString(c.getColumnIndex("thumb_pos"))); movie.setThumb_url(c.getString(c.getColumnIndex("thumb_path"))); movie.setSet_name(c.getString(c.getColumnIndex("set_name"))); movie.setType(c.getString(c.getColumnIndex("type"))); movie.setScore(c.getString(c.getColumnIndex("score"))); movie.setPic_score(c.getString(c.getColumnIndex("pic_score"))); movie.setSub_type1(c.getString(c.getColumnIndex("sub_type1"))); movie.setGrade(c.getString(c.getColumnIndex("grade"))); movie.setIsPraise(c.getString(c.getColumnIndex("isPraise"))); movie.setIsEnshrine(c.getString(c.getColumnIndex("isEnshrine"))); movie.setIsPlay(c.getString(c.getColumnIndex("isPlay"))); movie.setPlayTime(c.getString(c.getColumnIndex("playTime"))); movie.setEnshrineTime(c.getString(c.getColumnIndex("enshrineTime"))); movies.add(movie); } c.close(); return movies; } public void closeDB() { db.close(); } private Cursor queryTheCursor(String videoType) { Cursor c = db.rawQuery("SELECT * FROM video_info where type = ? order by id", new String[]{videoType}); return c; } private Cursor queryMovie(String movieID){ Cursor c = db.rawQuery("SELECT * FROM video_info where movie_id = ?", new String[]{movieID}); return c; } } }
import static java.lang.System.exit; import java.util.Scanner; import javax.swing.JOptionPane; import java.util.InputMismatchException; public class MainPerfectHash { public static void main(String[] args) { PerfectHash TicketDataBase = new PerfectHash(); int choice;///maybe chnage this` Scanner s=new Scanner(System.in); s.reset(); while(true){ s.reset(); System.out.println("Enter 1 to insert a new Ticket"); System.out.println("Enter 2 to fetch and Ticket"); System.out.println("Enter 3 to delete a Ticket"); System.out.println("Enter 4 to update a Ticket"); System.out.println("Enter 5 to exit the program"); //System.out.println("Enter your choice"); //vaildeinting correct input choice =0; s.reset(); System.out.print("Enter your choice: "); try { choice = s.nextInt(); } catch(InputMismatchException e) { System.out.println("Wrong kind of input!"); s.nextLine(); s.reset(); //choice = s.nextInt(); // } // switch(choice) { case 1: //System.out.println("Enter a ticket number"); //int tcktNum; //tcktNum = s.nextInt(); Listing l= new Listing(); l.input(); int id=l.getId(); //System.out.println("max is"+max); TicketDataBase.insert(l,id); //System.out.println("Wrong kind of input!"); break; // case 2: ////////////// //// System.out.println("Enter a ticket number from 2,000 to 100,000 to fetch"); int tcktNumToFetch; tcktNumToFetch = s.nextInt(); System.out.println(TicketDataBase.fetch(tcktNumToFetch)); ///// //////////// break; // case 3: System.out.println("Enter a ticket number from 2,000 to 100,000 to delete"); int tcktNumToD; tcktNumToD = s.nextInt(); System.out.println("inside case ticket number before preprocess"+tcktNumToD); TicketDataBase.delete(tcktNumToD); break; ///// case 4: System.out.println("Enter a ticket number from 2,000 to 100,000 to update"); int tcktNumToUpdate; tcktNumToUpdate = s.nextInt(); TicketDataBase.update(tcktNumToUpdate); break; case 5: exit(0); } } } }
package com.days.moment.qna.controller; import com.days.moment.common.dto.PageMaker; import com.days.moment.common.dto.PageRequestDTO; import com.days.moment.common.dto.PageResponseDTO; import com.days.moment.miniboard.dto.MiniDTO; import com.days.moment.qna.dto.QnaDTO; import com.days.moment.qna.service.QnaService; import com.days.moment.qna.service.QnaTimeService; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller @RequestMapping("/qna") @Log4j2 @RequiredArgsConstructor public class QnaController { private final QnaTimeService qnaTimeService; private final QnaService qnaService; @GetMapping("/time") public void getTime(Model model) { log.info("==================================="); log.info("==================================="); log.info("==================================="); model.addAttribute("time", qnaTimeService.getNow()); } @GetMapping(value = {"/write", "/writeAnswer"}) public void registerGet() { } @PostMapping("/write") public String registerPost(QnaDTO qnaDTO, RedirectAttributes redirectAttributes) { Long qnaId = qnaService.register(qnaDTO); redirectAttributes.addFlashAttribute("result", qnaId); if(qnaService.originModify(qnaDTO)){ log.info("modify success"); redirectAttributes.addFlashAttribute("result", "modified"); } return "redirect:/qna/list"; } @PostMapping("/writeAnswer") public String registerPostAnswer(QnaDTO qnaDTO, RedirectAttributes redirectAttributes) { Long qnaId = qnaService.register(qnaDTO); log.info("Answer register success================"); redirectAttributes.addFlashAttribute("result", qnaId); if(qnaService.answerModify(qnaDTO)){ log.info("modify success"); redirectAttributes.addFlashAttribute("result", "modified"); } return "redirect:/qna/list"; } @GetMapping("/list") public void getList(PageRequestDTO pageRequestDTO, Model model) { PageResponseDTO<QnaDTO> responseDTO = qnaService.getDTOList(pageRequestDTO); log.info("c getList.........................." + pageRequestDTO); model.addAttribute("dtoList", responseDTO.getDtoList()); int total = responseDTO.getCount(); int page = pageRequestDTO.getPage(); int size = pageRequestDTO.getSize(); model.addAttribute("pageMaker", new PageMaker(page, size, total)); } @GetMapping(value = {"/read"}) public void read(Long qnaId, PageRequestDTO pageRequestDTO, Model model) { model.addAttribute("qnaDTO", qnaService.read(qnaId)); } @PostMapping("/remove") public String remove(Long qnaId, RedirectAttributes redirectAttributes){ log.info("c remove:" + qnaId); if(qnaService.remove((qnaId))){ log.info("remove success"); redirectAttributes.addFlashAttribute("result", "success"); } return "redirect:/qna/list"; } }
package br.com.treinarminas.academico.Exercicios; // Exercicio de controle if{} else public class ImprimirPorExtenso { public static void main(String[] args) { int numero = 2; if (numero == 1) { System.out.println("Numero é = " + numero + "(um)"); } else if (numero == 2) { System.out.println("Numero é = " + numero+ "(dois)"); } else if (numero == 3) { System.out.println("Numero é = " + numero+ "(três)"); } else { System.out.println("Numero é = inválido"); } } }
package cn.edu.tju.http; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class URLsDecoder { /** * * @param s a String representing an URL * @return encoded URL */ public static String encodeURL(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new HttpException(e); } } /** * * @param s a String representing an URL * @return an UTF-8 decoded URL */ public static String decodeURL(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new HttpException(e); } } }
package com.uwetrottmann.trakt5.entities; import org.threeten.bp.OffsetDateTime; public class Comment { public Integer id; public Integer parent_id; public OffsetDateTime created_at; public OffsetDateTime updated_at; public String comment; public Boolean spoiler; public Boolean review; public Integer replies; public Integer likes; public Integer user_rating; public User user; // for posting public Movie movie; public Show show; public Episode episode; public Comment() { } /** * Build a movie comment. */ public Comment(Movie movie, String comment, boolean spoiler, boolean review) { this(comment, spoiler, review); this.movie = movie; } /** * Build a show comment. */ public Comment(Show show, String comment, boolean spoiler, boolean review) { this(comment, spoiler, review); this.show = show; } /** * Build an episode comment. */ public Comment(Episode episode, String comment, boolean spoiler, boolean review) { this(comment, spoiler, review); this.episode = episode; } /** * Build an updated comment. */ public Comment(String comment, boolean spoiler, boolean review) { this.comment = comment; this.spoiler = spoiler; this.review = review; } }
package com.example.recyclerview.data; public class SummaryData { String value; String meaning; public SummaryData(String value, String meaning) { this.value = value; this.meaning = meaning; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getMeaning() { return meaning; } public void setMeaning(String meaning) { this.meaning = meaning; } }
package com.ld.baselibrary.base; import androidx.annotation.NonNull; /** * Description:RecycleView多布局ItemViewModel是封装 */ public class MultiItemViewModel<VM extends BaseViewModel> extends ItemViewModel<VM> { // 多布局类型 protected Object multiType; // 多布局数据 protected Object sourcesData; public MultiItemViewModel(@NonNull VM viewModel) { super(viewModel); } public MultiItemViewModel(@NonNull VM viewModel, Object multiType) { super(viewModel); this.multiType = multiType; } public MultiItemViewModel(@NonNull VM viewModel, Object multiType, Object sourcesData) { super(viewModel); this.multiType = multiType; this.sourcesData = sourcesData; } public Object getItemType() { return multiType; } public void multiItemType(@NonNull Object multiType) { this.multiType = multiType; } public Object getSourcesData() { return sourcesData; } public void setSourcesData(Object sourcesData) { this.sourcesData = sourcesData; } }
package Archiver; /** * Created by wiewiogr on 08.06.17. */ public class Weather { String main; String description; String icon; int temperature; int humidity; int visibilty; int pressure; double windSpeed; int windDegree; int clouds; }
/* 1: */ package com.kaldin.setting.importdata.dto; /* 2: */ /* 3: */ public class ImportDataDTO /* 4: */ { /* 5: */ private String connctionURL; /* 6: */ private String password; /* 7: */ private String dbName; /* 8: */ private String driver; /* 9: */ private String userName; /* 10: */ /* 11: */ public String getConnctionURL() /* 12: */ { /* 13:15 */ return this.connctionURL; /* 14: */ } /* 15: */ /* 16: */ public void setConnctionURL(String connctionURL) /* 17: */ { /* 18:18 */ this.connctionURL = connctionURL; /* 19: */ } /* 20: */ /* 21: */ public String getDbName() /* 22: */ { /* 23:21 */ return this.dbName; /* 24: */ } /* 25: */ /* 26: */ public void setDbName(String dbName) /* 27: */ { /* 28:24 */ this.dbName = dbName; /* 29: */ } /* 30: */ /* 31: */ public String getDriver() /* 32: */ { /* 33:27 */ return this.driver; /* 34: */ } /* 35: */ /* 36: */ public void setDriver(String driver) /* 37: */ { /* 38:30 */ this.driver = driver; /* 39: */ } /* 40: */ /* 41: */ public String getPassword() /* 42: */ { /* 43:33 */ return this.password; /* 44: */ } /* 45: */ /* 46: */ public void setPassword(String password) /* 47: */ { /* 48:36 */ this.password = password; /* 49: */ } /* 50: */ /* 51: */ public String getUserName() /* 52: */ { /* 53:39 */ return this.userName; /* 54: */ } /* 55: */ /* 56: */ public void setUserName(String userName) /* 57: */ { /* 58:42 */ this.userName = userName; /* 59: */ } /* 60: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.setting.importdata.dto.ImportDataDTO * JD-Core Version: 0.7.0.1 */
package de.fhg.iais.roberta.visitor.hardware; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkAddRawData; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkAddTrainingsData; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkClassify; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkInitRawData; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkSetup; import de.fhg.iais.roberta.syntax.neuralnetwork.NeuralNetworkTrain; import de.fhg.iais.roberta.util.dbc.DbcException; public interface INeuralNetworkVisitor<V> { default V visitNeuralNetworkSetup(NeuralNetworkSetup<V> nn) { throw new DbcException("Not supported!"); } default V visitNeuralNetworkInitRawData(NeuralNetworkInitRawData<V> nn) { throw new DbcException("Not supported!"); } default V visitNeuralNetworkAddRawData(NeuralNetworkAddRawData<V> nn) { throw new DbcException("Not supported!"); } default V visitNeuralNetworkAddTrainingsData(NeuralNetworkAddTrainingsData<V> nn) { throw new DbcException("Not supported!"); } default V visitNeuralNetworkTrain(NeuralNetworkTrain<V> nn) { throw new DbcException("Not supported!"); } default V visitNeuralNetworkClassify(NeuralNetworkClassify<V> nn) { throw new DbcException("Not supported!"); } }
package com.dragon.system.quartz.utils; import com.dragon.common.exception.BadRequestException; import com.dragon.system.quartz.model.QuartzJobModel; import org.quartz.*; import org.quartz.impl.triggers.CronTriggerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; @Component public class QuartzManage { private static final Logger log = LoggerFactory.getLogger(QuartzManage.class); private static final String JOB_NAME_PREFIX = "TASK_"; private static final String TRIGGER_NAME_PREFIX = "TRIGGER_"; @Autowired private Scheduler scheduler; /** * 添加定时任务 * @param quartzJob */ public void addJob(QuartzJobModel quartzJob) { try { // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class).withIdentity(JOB_NAME_PREFIX + quartzJob.getId()).build(); // 构建触发器 Trigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_NAME_PREFIX + quartzJob.getId()) .startNow().withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression())).build(); // 设置数据到JobData中,执行的时候取出 cronTrigger.getJobDataMap().put(QuartzJobModel.JOB_KEY, quartzJob); // 重置启动时间 ((CronTriggerImpl) cronTrigger).setStartTime(new Date()); // 执行定时任务 scheduler.scheduleJob(jobDetail, cronTrigger); // 暂停任务 if (quartzJob.getIsPause()) { pauseJob(quartzJob); } } catch (Exception e) { log.error("创建定时任务失败", e); throw new BadRequestException("创建定时任务失败"); } } /** * 暂停一个job * * @param quartzJob */ public void pauseJob(QuartzJobModel quartzJob) { try { JobKey jobKey = JobKey.jobKey(JOB_NAME_PREFIX + quartzJob.getId()); scheduler.pauseJob(jobKey); } catch (Exception e) { log.error("定时任务暂停失败", e); throw new BadRequestException("定时任务暂停失败"); } } /** * 恢复一个job * @param quartzJob */ public void resumeJob(QuartzJobModel quartzJob) { try { TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_NAME_PREFIX + quartzJob.getId()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null) { addJob(quartzJob); } JobKey jobKey = JobKey.jobKey(JOB_NAME_PREFIX + quartzJob.getId()); scheduler.resumeJob(jobKey); } catch (Exception e){ log.error("恢复定时任务失败", e); throw new BadRequestException("恢复定时任务失败"); } } }
/* Primes calculation : need optimization tecnique, the complexity (and the time too) grow in an exponential way; it O(e^n) e^2000000 */ import java.util.*; public class SumPrimesMin2Mln{ public static void main(String args[]){ boolean isPrime=false; long sumPrime=0; for(int p=1; p<2000000; ++p){ isPrime=true; for(int d=2;d<p;++d){ if (p%d==0) isPrime=false; }//2° for if (isPrime) { sumPrime += (long)p; System.out.println("Is a prime : " + p + " and the sum is now : " + sumPrime); } }//1° for System.out.println("The total sum is : " + sumPrime); } }
/* * Copyright (C) 2011 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.deskclock; import java.lang.reflect.Method; import java.util.Timer; import java.util.TimerTask; import android.R.integer; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.preference.PreferenceManager; import android.provider.Settings; import android.service.dreams.DreamService; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextClock; import android.widget.TextView; import com.android.deskclock.Utils.ScreensaverMoveSaverRunnable; import com.android.deskclock.provider.Alarm; public class Screensaver extends DreamService { static final boolean DEBUG = false; static final String TAG = "DeskClock/Screensaver"; private View mContentView, mSaverView; private View mAnalogClock, mDigitalClock; private String mDateFormat; private String mDateFormatForAccessibility; private final Handler mHandler = new Handler(); private final ScreensaverMoveSaverRunnable mMoveSaverRunnable; //zzl private WindowManager mWindowManager; private WindowManager.LayoutParams param; // private FloatView mLayout; private LinearLayout linearLayout=null; private TextView textView; private TextView textView2; private int y_start; private int x_start; private int y_move; private int x_move; private SeekBar_vertical seekBar_Down_Up; int current_light ; private int move_count; private ImageView imageView_wifi; private TextView textView_battery; private ImageView imageView_battery; private TextView textView_iqi_message; private int[] wifi_signal = {R.drawable.i_wifi_0,R.drawable.i_wifi_1,R.drawable.i_wifi_2,R.drawable.i_wifi_3}; private int[] battery_signal = {R.drawable.i_battery_25,R.drawable.i_barrery_50,R.drawable.i_battery_75,R.drawable.i_battery_100}; private static final int BATTERY = 0x400 +1; private static final int WIFI = 0x400 +2; private static final int IQI_MESSAGE = 0x400 + 3; private Handler handler; private WifiBatteryReceiver wifiBatteryReceiver; private final ContentObserver mSettingsContentObserver = new ContentObserver(mHandler) { @Override public void onChange(boolean selfChange) { Utils.refreshAlarm(Screensaver.this, mContentView); } }; // Thread that runs every midnight and refreshes the date. private final Runnable mMidnightUpdater = new Runnable() { @Override public void run() { Utils.updateDateAddOld(Screensaver.this,mDateFormat, mDateFormatForAccessibility, mContentView); Utils.setMidnightUpdater(mHandler, mMidnightUpdater); } }; /** * Receiver to handle time reference changes. */ private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action != null && (action.equals(Intent.ACTION_TIME_CHANGED) || action.equals(Intent.ACTION_TIMEZONE_CHANGED))) { Utils.updateDateAddOld(Screensaver.this,mDateFormat, mDateFormatForAccessibility, mContentView); Utils.refreshAlarm(Screensaver.this, mContentView); Utils.setMidnightUpdater(mHandler, mMidnightUpdater); } } }; public Screensaver() { if (DEBUG) Log.d(TAG, "Screensaver allocated"); mMoveSaverRunnable = new ScreensaverMoveSaverRunnable(mHandler); } @Override public boolean dispatchTouchEvent(MotionEvent arg0) { // TODO Auto-generated method stub switch (arg0.getAction()) { case MotionEvent.ACTION_DOWN: //showView(); y_start =(int) arg0.getY(); x_start =(int) arg0.getX(); break; case MotionEvent.ACTION_MOVE: move_count ++; y_move = (int) arg0.getY(); x_move = (int) arg0.getX(); int dy = y_move - y_start; int dx = x_move - x_start; if(move_count > 10 && Math.abs(dy) > 10) showView(); if(Math.abs(dx)> 200){ if(linearLayout != null) mWindowManager.removeView(linearLayout); linearLayout = null; finish(); } if(dy > 0) current_light =current_light -20; else current_light = current_light +20; break; case MotionEvent.ACTION_UP: if(move_count<10) finish(); if(linearLayout != null) mWindowManager.removeView(linearLayout); linearLayout = null; move_count = 0; break; default: break; } if(current_light < 10) current_light = 10; if(current_light > 255 ) current_light = 255; if(linearLayout != null){ textView.setText(""); int temp = (int)(current_light/2.55); textView2.setText(""+temp); seekBar_Down_Up.setProgress(current_light); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = Float.valueOf(current_light) * (1f / 255f); getWindow().setAttributes(lp); android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, current_light); /* try { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); Class<?> pmClass = Class.forName(pm.getClass().getName()); Method method = pmClass.getDeclaredMethod("setBacklightBrightness", int.class); method.setAccessible(true); method.invoke(pm, current_light); } catch (Exception e) { e.printStackTrace(); } */ } return super.dispatchTouchEvent(arg0); } private void showView() { // mLayout = new FloatView(getApplicationContext()); // mLayout.setBackgroundResource(R.drawable.ic_launcher); if(linearLayout == null){ linearLayout = (LinearLayout) LayoutInflater.from(this).inflate( R.layout.screenlight, null); seekBar_Down_Up = (SeekBar_vertical) linearLayout.findViewById(R.id.seekBarDownUp); textView = (TextView) linearLayout.findViewById(R.id.textview_screenlight_num); textView2 = (TextView)linearLayout.findViewById(R.id.textview_screenlight_num_2); ContentResolver resolver = getContentResolver(); try{ current_light = android.provider.Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS); } catch(Exception e) { e.printStackTrace(); } //current_light = 1; textView.setText(""); int temp = (int)(current_light/2.55); textView2.setText(""+temp); seekBar_Down_Up.setProgress(current_light); mWindowManager = (WindowManager) getApplicationContext() .getSystemService(Context.WINDOW_SERVICE); param = new WindowManager.LayoutParams(); param.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; param.format = 1; param.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; param.flags = param.flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; param.flags = param.flags | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; param.alpha = 1.0f; param.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; param.x = 0; param.y = 30; param.width = 230; param.height = 470; mWindowManager.addView(linearLayout, param); } } @Override public void onCreate() { if (DEBUG) Log.d(TAG, "Screensaver created"); super.onCreate(); mDateFormat = getString(R.string.abbrev_wday_month_day_no_year); mDateFormatForAccessibility = getString(R.string.full_wday_month_day_no_year); } private void setBattery(int level){ if(75<level && level<=100 ) imageView_battery.setBackgroundResource(battery_signal[3]); if(50<level && level<=75 ) imageView_battery.setBackgroundResource(battery_signal[2]); if(25<level && level<=50 ) imageView_battery.setBackgroundResource(battery_signal[1]); if(0<level && level<=25 ) imageView_battery.setBackgroundResource(battery_signal[0]); if(level == 0) imageView_battery.setBackgroundColor(Color.TRANSPARENT); } private class WifiBatteryReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){ int level = intent.getIntExtra("level", 0); int scale = intent.getIntExtra("scale", 100); int num = (level*100)/scale; //String battery = num +"%"; int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); handler.obtainMessage(BATTERY, status,num).sendToTarget(); }else if(intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){ WifiInfo currentInfo = null; WifiManager mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); currentInfo = mWifiManager.getConnectionInfo(); ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info_wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (currentInfo != null && info_wifi.isConnected()) { int level = getlevel(currentInfo.getRssi()); handler.obtainMessage(WIFI, level).sendToTarget(); } }else if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){ WifiManager mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); if(!mWifiManager.isWifiEnabled()) imageView_wifi.setBackgroundColor(Color.TRANSPARENT); } } } private int getlevel(int rssi){ int level = 4; if (rssi <= 0 && rssi >= -50) { level = 3; } else if (rssi < -50 && rssi >= -70) { level = 2; } else if (rssi < -70 && rssi >= -80) { level = 1; } else if (rssi < -80 && rssi >= -100) { level = 0; } else { level = 4; } return level; } @Override public void onConfigurationChanged(Configuration newConfig) { if (DEBUG) Log.d(TAG, "Screensaver configuration changed"); super.onConfigurationChanged(newConfig); mHandler.removeCallbacks(mMoveSaverRunnable); layoutClockSaver(); //mHandler.post(mMoveSaverRunnable); } @Override public void onAttachedToWindow() { if (DEBUG) Log.d(TAG, "Screensaver attached to window"); super.onAttachedToWindow(); // We want the screen saver to exit upon user interaction. setInteractive(false); setFullscreen(true); layoutClockSaver(); // Setup handlers for time reference changes and date updates. IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); registerReceiver(mIntentReceiver, filter); Utils.setMidnightUpdater(mHandler, mMidnightUpdater); getContentResolver().registerContentObserver( Settings.System.getUriFor(Settings.System.NEXT_ALARM_FORMATTED), false, mSettingsContentObserver); mHandler.post(mMoveSaverRunnable); handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch(msg.what){ case BATTERY: int statue = msg.arg1; int num = msg.arg2; String battery = num+"%"; String charge = getResources().getString(R.string.charge); if(num < 18 && (statue != BatteryManager.BATTERY_STATUS_CHARGING || statue != BatteryManager.BATTERY_STATUS_FULL)) textView_battery.setText(charge+" "+battery); else textView_battery.setText(battery); String charging = getResources().getString(R.string.charging); String charged = getResources().getString(R.string.charged); if(statue == BatteryManager.BATTERY_STATUS_CHARGING) textView_battery.setText(charging+" "+battery); if(num == 100 && (statue == BatteryManager.BATTERY_STATUS_CHARGING || statue == BatteryManager.BATTERY_STATUS_FULL)) textView_battery.setText(charged+" "+battery); if(num == 0){ textView_battery.setText(""); } setBattery(num); break; case WIFI: int level = (Integer)msg.obj; imageView_wifi.setBackgroundResource(wifi_signal[level]); break; case IQI_MESSAGE: int i = (Integer)msg.obj; if(i== 0) textView_iqi_message.setVisibility(View.GONE); else { textView_iqi_message.setVisibility(View.VISIBLE); String format = getResources().getString(R.string.iqi_message); String number = String.format(format, " "+i+""); textView_iqi_message.setText(number); } break; } } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); wifiBatteryReceiver = new WifiBatteryReceiver(); registerReceiver(wifiBatteryReceiver, intentFilter); TimerTask timerTask = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub int num = queryMessage(); handler.obtainMessage(IQI_MESSAGE, num).sendToTarget(); } }; Timer timer = new Timer(); timer.schedule(timerTask, 500, 2000); } private int queryMessage(){ int num = 0; final Uri URI = Uri.parse("content://com.qiyi.minitv.video.messagecenter/itvcloud"); String select = "is_read=0"; ContentResolver cr = this.getContentResolver(); Cursor cursor = cr.query(URI, null, select, null, null); if (cursor == null) { return num; } try { if (cursor.moveToFirst()) { do { num = num + 1; } while (cursor.moveToNext()); } } finally { cursor.close(); } return num; } @Override public void onDetachedFromWindow() { if (DEBUG) Log.d(TAG, "Screensaver detached from window"); super.onDetachedFromWindow(); mHandler.removeCallbacks(mMoveSaverRunnable); getContentResolver().unregisterContentObserver(mSettingsContentObserver); // Tear down handlers for time reference changes and date updates. Utils.cancelMidnightUpdater(mHandler, mMidnightUpdater); unregisterReceiver(mIntentReceiver); unregisterReceiver(wifiBatteryReceiver); } private void setClockStyle() { Utils.setClockStyle(this, mDigitalClock, mAnalogClock, ScreensaverSettingsActivity.KEY_CLOCK_STYLE); mSaverView = findViewById(R.id.main_clock); boolean dimNightMode = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(ScreensaverSettingsActivity.KEY_NIGHT_MODE, false); Utils.dimClockView(false, mSaverView); setScreenBright(!dimNightMode); } private void layoutClockSaver() { setContentView(R.layout.desk_clock_saver); mDigitalClock = findViewById(R.id.digital_clock); mAnalogClock =findViewById(R.id.analog_clock); imageView_wifi = (ImageView)findViewById(R.id.imageview_wifi); textView_battery = (TextView)findViewById(R.id.textview_battery); imageView_battery = (ImageView)findViewById(R.id.imageview_battery); textView_iqi_message = (TextView)findViewById(R.id.textview_iqi_message); setClockStyle(); Utils.setTimeFormat(Screensaver.this,(TextClock)mDigitalClock, (int)getResources().getDimension(R.dimen.bottom_text_size)); mContentView = (View) mSaverView.getParent(); //mSaverView.setAlpha(0); mMoveSaverRunnable.registerViews(mContentView, mSaverView); Utils.updateDateAddOld(Screensaver.this,mDateFormat, mDateFormatForAccessibility, mContentView); Utils.refreshAlarm(Screensaver.this, mContentView); } }
package org.alienideology.jcord.event.channel.group.user; import org.alienideology.jcord.handle.user.IUser; import org.alienideology.jcord.internal.object.IdentityImpl; import org.alienideology.jcord.internal.object.channel.Channel; /** * @author AlienIdeology */ public class GroupUserLeaveEvent extends GroupUserEvent { public GroupUserLeaveEvent(IdentityImpl identity, int sequence, Channel channel, IUser user) { super(identity, sequence, channel, user); } }
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.urhive.panicbutton.models; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; public interface IdpProvider { /** * Retrieves the name of the IDP, for display on-screen. */ String getName(Context context); String getProviderId(); void setAuthenticationCallback(IdpCallback callback); void onActivityResult(int requestCode, int resultCode, Intent data); void startLogin(Activity activity); interface IdpCallback { void onSuccess(IdpResponse idpResponse, Bundle bundle); void onFailure(Bundle extra); } }
package tw.org.iii.java; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import tw.org.iii.myclass.Scooter; public class Brad68 { public static void main(String[] args) { Student s1 = new Student(90, 70, 50); System.out.println(s1.score()); System.out.println(s1.avg()); // 物件序列化 try { FileOutputStream fout = new FileOutputStream("dir1/s1.brad"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(s1); fout.flush(); fout.close(); System.out.println("OK"); } catch (Exception e) { e.printStackTrace(); } } } // JVM class Student implements Serializable { private int ch, eng, math; private Scooter scooter; Student(int ch, int eng, int math){ this.ch = ch; this.eng = eng; this.math = math; scooter = new Scooter(); scooter.setGear(4); scooter.upSpeed();scooter.upSpeed(); scooter.upSpeed();scooter.upSpeed(); System.out.println(scooter.getSpeed()); } double getScooterSpeed() {return scooter.getSpeed();} int score() {return ch + eng + math;} double avg() {return score() / 3.0 ;} }
package com.example.demo.entity; import lombok.AllArgsConstructor; import lombok.Data; import java.util.Date; @Data @AllArgsConstructor public class UserEntity { private String name; private String address; private Date date; }
/* * 文 件 名: Image.java * 描 述: Image.java * 时 间: 2013-6-17 */ package com.babyshow.image.bean; import java.util.Date; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * <一句话功能简述> <功能详细描述> * * @author ztc * @version [BABYSHOW V1R1C1, 2013-6-17] */ public class Image { /** * 照片ID */ private Integer id; /** * 照片code */ @JsonProperty("image_id") private String imageCode; /** * 所属用户code */ @JsonIgnore private String userCode; /** * 照片描述 */ @JsonProperty("image_description") private String description; /** * 照片被喜欢总次数 */ @JsonProperty("image_like_count") private Integer likeCount; /** * 创建时间 */ @JsonProperty("image_created_time") private Date createdTime; /** * 照片对应云存储Key */ @JsonIgnore private String urlKey; /** * 照片状态 */ @JsonIgnore private Integer status; /** * 照片访问地址 */ @JsonProperty("image_url") private String url; /** * 获取 description * * @return 返回 description */ public String getDescription() { return description; } /** * 设置 description * * @param 对description进行赋值 */ public void setDescription(String description) { this.description = description; } /** * 获取 createdTime * * @return 返回 createdTime */ public Date getCreatedTime() { return createdTime; } /** * 设置 createdTime * * @param 对createdTime进行赋值 */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 urlKey * * @return 返回 urlKey */ public String getUrlKey() { return urlKey; } /** * 设置 urlKey * * @param 对urlKey进行赋值 */ public void setUrlKey(String urlKey) { this.urlKey = urlKey; } /** * 获取 id * * @return 返回 id */ public Integer getId() { return id; } /** * 设置 id * * @param 对id进行赋值 */ public void setId(Integer id) { this.id = id; } /** * 获取 imageCode * * @return 返回 imageCode */ public String getImageCode() { return imageCode; } /** * 设置 imageCode * * @param 对imageCode进行赋值 */ public void setImageCode(String imageCode) { this.imageCode = imageCode; } /** * 获取 userCode * * @return 返回 userCode */ public String getUserCode() { return userCode; } /** * 设置 userCode * * @param 对userCode进行赋值 */ public void setUserCode(String userCode) { this.userCode = userCode; } /** * 获取 status * * @return 返回 status */ public Integer getStatus() { return status; } /** * 设置 status * * @param 对status进行赋值 */ public void setStatus(Integer status) { this.status = status; } /** * 获取 url * * @return 返回 url */ public String getUrl() { return url; } /** * 设置 url * * @param 对url进行赋值 */ public void setUrl(String url) { this.url = url; } /** * 获取 likeCount * @return 返回 likeCount */ public Integer getLikeCount() { return likeCount; } /** * 设置 likeCount * @param 对likeCount进行赋值 */ public void setLikeCount(Integer likeCount) { this.likeCount = likeCount; } }
package com.example.bhuva.store_buddy_group_31; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import static com.example.bhuva.store_buddy_group_31.MainActivity.db; public class Favorites extends AppCompatActivity { static SQLiteDatabase db; static String table_name = "fav_table"; AutoCompleteTextView search_Fav; Button add_fav, delete_fav; ListView fav_list; int item_pos; String item_name; ArrayList<String> prodList, prodNameList; ArrayAdapter adapter, adapter_prodcat; Cursor cursor, cursorProdName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.favorites); db = openOrCreateDatabase("CommoditiesDB.db", MODE_PRIVATE, null); add_fav = (Button) findViewById(R.id.add_fav); delete_fav = (Button) findViewById(R.id.del_fav); fav_list = (ListView) findViewById(R.id.fav_list); search_Fav = (AutoCompleteTextView) findViewById(R.id.autocomplete_favs); prodNameList = new ArrayList<String>(); cursorProdName = db.rawQuery("select * from "+ MainActivity.product_catalog_table +";", null); System.out.println(cursorProdName.toString()); if (cursorProdName.getCount() > 0) { cursorProdName.moveToFirst(); do { prodNameList.add(cursorProdName.getString(cursorProdName.getColumnIndex("item_name"))); } while (cursorProdName.moveToNext()); cursorProdName.close(); } prodList = new ArrayList<String>(); cursor = db.rawQuery("select * from "+ table_name +";", null); if (cursor.getCount() > 0) { cursor.moveToFirst(); do { prodList.add(cursor.getString(cursor.getColumnIndex("item_name"))); } while (cursor.moveToNext()); cursor.close(); } adapter_prodcat = new ArrayAdapter(Favorites.this, R.layout.listitem_layout_commodityrecentlist, prodNameList); adapter = new ArrayAdapter(Favorites.this, R.layout.listitem_layout_commodityrecentlist, prodList); search_Fav.setAdapter(adapter_prodcat); search_Fav.setThreshold(1); fav_list.setAdapter(adapter); add_fav.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // add item to table if(!search_Fav.getText().toString().equals("")) db.execSQL("insert into " + table_name + " values ('" + search_Fav.getText().toString() +"');"); else Toast.makeText(Favorites.this, "Please enter an item", Toast.LENGTH_SHORT).show(); prodList = new ArrayList<String>(); cursor = db.rawQuery("select * from "+ table_name +";", null); if (cursor.getCount() > 0) { cursor.moveToFirst(); do { prodList.add(cursor.getString(cursor.getColumnIndex("item_name"))); } while (cursor.moveToNext()); cursor.close(); } adapter = new ArrayAdapter(Favorites.this, R.layout.listitem_layout_commodityrecentlist, prodList); fav_list.setAdapter(adapter); //System.out.println("Added..."); } }); delete_fav.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //db = openOrCreateDatabase("CommoditiesDB.db", MODE_PRIVATE, null); fav_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) { item_pos = position; } }); item_name = (fav_list.getItemAtPosition(item_pos)).toString(); db.execSQL("delete from " + table_name + " where item_name = '" + item_name + "'"); Toast.makeText(Favorites.this, "Item: " + item_name + " has been deleted", Toast.LENGTH_SHORT).show(); prodList = new ArrayList<String>(); cursor = db.rawQuery("select * from "+ table_name +";", null); if (cursor.getCount() > 0) { cursor.moveToFirst(); do { prodList.add(cursor.getString(cursor.getColumnIndex("item_name"))); } while (cursor.moveToNext()); cursor.close(); } adapter = new ArrayAdapter(Favorites.this, R.layout.listitem_layout_commodityrecentlist, prodList); fav_list.setAdapter(adapter); } }); } }
package sellwin.domain; import java.util.*; import java.io.*; // SellWin http://sourceforge.net/projects/sellwincrm //Contact support@open-app.com for commercial help with SellWin //This software is provided "AS IS", without a warranty of any kind. /** * This class contains data about a product that will * be used to do quoting. */ public class Product implements Serializable { private long pk; private String group; private String line; private String name; private String modelNo; private Double cost; private Double price; private String desc; private String modifiedBy; private Date modifiedDate; public Product() { this("hi", "you", "dude"); } public Product(String g, String l, String n) { group = g; line = l; name = n; cost = new Double(0.00); price = new Double(0.00); modifiedDate = new Date(); } public void clear() { name = ""; group = ""; line = ""; } public final void setPK(long pk) { this.pk = pk; } public final void setGroup(String g) { group = g; } public final void setLine(String g) { line = g; } public final void setName(String name) { this.name = name; } public final void setModelNo(String no) { this.modelNo = no; } public final void setCost(Double d) { cost = d; } public final void setPrice(Double d) { price = d; } public final void setDesc(String s) { desc = s; } public final void setModifiedDate(Date d) { modifiedDate = d; } public final void setModifiedBy(String s) { modifiedBy = s; } public final long getPK() { return pk; } public final String getLine() { return line; } public final String getGroup() { return group; } public final String getName() { return name; } public final String getModelNo() { return modelNo; } public final Double getCost() { return cost; } public final Double getPrice() { return price; } public final String getDesc() { return desc; } public final String getModifiedBy() { return modifiedBy; } public final Date getModifiedDate() { return modifiedDate; } public final Product copy() { Product copy = new Product(new String(getGroup()), new String(getLine()), new String(getName())); if (modelNo != null) copy.modelNo = new String(modelNo); copy.price= new Double(price.doubleValue()); copy.cost = new Double(cost.doubleValue()); if (desc != null) copy.desc = new String(desc); copy.modifiedBy =new String(modifiedBy); copy.modifiedDate = new Date(modifiedDate.getTime()); return copy; } public final void print() { System.out.println("<<Product>>"); System.out.println("pk=["+getPK()+"]"); System.out.println("Name=["+getName()+"]"); System.out.println("Model No=["+getModelNo()+"]"); System.out.println("Group=["+getGroup()+"]"); System.out.println("Line=["+getLine()+"]"); System.out.println("Price="+getPrice()); System.out.println("Cost="+getCost()); System.out.println("Model No=["+getModelNo()+"]"); System.out.println("Desc=["+getDesc()+"]"); System.out.println("ModifiedBy=["+getModifiedBy()+"]"); System.out.println("ModifiedDate=["+getModifiedDate()+"]"); } }
package cn.canlnac.onlinecourse.presentation.internal.di.modules; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.interactor.GetCommentsInChatUseCase; import cn.canlnac.onlinecourse.domain.interactor.UseCase; import cn.canlnac.onlinecourse.domain.repository.ChatRepository; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import dagger.Module; import dagger.Provides; /** * 注入模块. */ @Module public class GetCommentsInChatModule { private final int chatId; private final Integer start; private final Integer count; private final String sort; public GetCommentsInChatModule( int chatId, Integer start, Integer count, String sort ) { this.chatId = chatId; this.start = start; this.count = count; this.sort = sort; } @Provides @PerActivity UseCase provideGetCommentsInChatUseCase(ChatRepository chatRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread){ return new GetCommentsInChatUseCase(chatId, start,count,sort, chatRepository, threadExecutor, postExecutionThread); } }
package android.support.v4.app; import android.app.Notification.Action; import android.app.Notification.Builder; import android.app.RemoteInput; final class aa { public static void a(Builder builder, ac$a ac_a) { Action.Builder builder2 = new Action.Builder(ac_a.getIcon(), ac_a.getTitle(), ac_a.getActionIntent()); if (ac_a.bz() != null) { for (RemoteInput addRemoteInput : ai.a(ac_a.bz())) { builder2.addRemoteInput(addRemoteInput); } } if (ac_a.getExtras() != null) { builder2.addExtras(ac_a.getExtras()); } builder.addAction(builder2.build()); } }
package org.training.dao.impl; import org.apache.log4j.Logger; import org.training.dao.ItemDAO; import org.training.dao.exception.DAOException; import org.training.model.entities.Item; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by nicko on 1/25/2017. */ public class ItemDAOImpl implements ItemDAO { private static final Logger logger = Logger.getLogger(ItemDAO.class); private Connection connection; private static final String SELECT_ONE_BY_ID = "SELECT * from item where idItem = ?"; private static final String SELECT_ALL = "SELECT * from item"; public static final String CREATE_ITEM = "INSERT INTO item (`title`, `price`, `weight`) VALUES (?,?,?)"; public ItemDAOImpl(Connection connection) { this.connection = connection; } @Override public List<Item> getAll() { List<Item> items = new ArrayList<>(); try (PreparedStatement statement = connection.prepareStatement(SELECT_ALL)) { ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { Item item = new Item.Builder() .setId(resultSet.getInt(1)) .setPrice(resultSet.getDouble(3)) .setName(resultSet.getString(2)) .setWeight(resultSet.getInt(4)) .build(); items.add(item); } return items; } catch (SQLException e) { logger.error("Error retrieving all items", e); throw new DAOException(e); } } @Override public Item findById(Integer id) { try (PreparedStatement statement = connection.prepareStatement(SELECT_ONE_BY_ID)) { statement.setInt(1, id); ResultSet resultSet = statement.executeQuery(); resultSet.next(); return new Item.Builder() .setId(resultSet.getInt(1)) .setPrice(resultSet.getDouble(3)) .setName(resultSet.getString(2)) .setWeight(resultSet.getInt(4)) .build(); } catch (SQLException e) { logger.error("Error retrieving item by id", e); throw new DAOException(e); } } @Override public void create(Item item) { try (PreparedStatement preparedStatement = connection.prepareStatement(CREATE_ITEM)) { preparedStatement.setString(1, item.getName()); preparedStatement.setDouble(2, item.getPrice()); preparedStatement.setInt(3, item.getWeight()); preparedStatement.executeUpdate(); } catch (SQLException e) { logger.error("Error creating item", e); throw new DAOException(e); } } }
package de.zarncke.lib.util; import java.util.Arrays; import java.util.HashSet; import junit.framework.TestSuite; import de.zarncke.lib.coll.HierarchicalMap; import de.zarncke.lib.err.GuardedTest; import de.zarncke.lib.struct.Lattice; import de.zarncke.lib.struct.PartialOrder; /** * Tests lattice related classes of util package. */ public class LatticeTest extends GuardedTest { public LatticeTest() { super(); } private static PartialOrder prefixOrder = new PartialOrder() { public boolean lessEqual(final Object a, final Object b) { if (a == Lattice.BOT) { return true; } if (b == Lattice.BOT) { return false; } return ((String) a).startsWith((String) b); } }; private static PartialOrder logicOrder = new PartialOrder() { public boolean lessEqual(final Object a, final Object b) { int aa = ((Number) a).intValue(); int bb = ((Number) b).intValue(); return (aa | bb) == aa; } }; public void testLattice() { // some basic lattice tests { Lattice set = new Lattice(Lattice.IMPLICIT_ORDER, Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(Integer.MIN_VALUE)); int[] ia = new int[] { Integer.MIN_VALUE, 10, -5, 0, 4, 1000, -50, -20, Integer.MAX_VALUE }; for (int i = 1; i < ia.length - 1; i++) { set.add(Integer.valueOf(ia[i])); } Arrays.sort(ia); for (int i = 1; i < ia.length - 1; i++) { assertEquals(new Object[] { Integer.valueOf(ia[i - 1]) }, set.getLower(Integer.valueOf(ia[i]))); assertEquals(new Object[] { Integer.valueOf(ia[i + 1]) }, set.getUpper(Integer.valueOf(ia[i]))); } } { Lattice set = new Lattice(prefixOrder, "", Lattice.BOT); set.add("aa"); set.add("ab"); set.add("a"); assertEquals(new Object[] { "aa", "ab" }, set.getLower("a")); assertEquals(new Object[] { "" }, set.getUpper("a")); assertEquals(new Object[] { "a" }, set.getUpper("aa")); assertEquals(new Object[] { "a" }, set.getUpper("ab")); assertEquals(new Object[] { Lattice.BOT }, set.getLower("ab")); } { Lattice set = new Lattice(logicOrder, Integer.valueOf(0), Integer.valueOf(-1)); set.add(Integer.valueOf(0x001)); set.add(Integer.valueOf(0x010)); set.add(Integer.valueOf(0x100)); set.add(Integer.valueOf(0x011)); set.add(Integer.valueOf(0x110)); set.add(Integer.valueOf(0x101)); assertEquals(new Object[] { Integer.valueOf(0) }, set.getUpper(Integer.valueOf(0x001))); assertEquals(new Object[] { Integer.valueOf(-1) }, set.getLower(Integer.valueOf(0x011))); assertEquals(new Object[] { Integer.valueOf(0x001), Integer.valueOf(0x100) }, set.getUpper(Integer.valueOf(0x101))); assertEquals(new Object[] { Integer.valueOf(0x011), Integer.valueOf(0x110), Integer.valueOf(0x101) }, set.getUpper(Integer.valueOf(0x111))); } /* { Lattice set = new Lattice(); set.add(TestA.class); set.add(TestK.class); set.add(TestL.class); set.add(TestB.class); set.add(TestC.class); assertEquals(set.getLower(TestC.class), new Object[] { TestB.class, TestL.class }); } { Lattice set = new Lattice(); set.add(TestA.class); set.add(TestK.class); set.add(TestB.class); set.remove(TestK.class); assertEquals(set.getLower(TestB.class), new Object[] { TestA.class }); assertEquals(set.getUpper(TestA.class), new Object[] { TestB.class }); } { Lattice set = new Lattice(); set.add(a); set.add(b); set.add(c); set.add(ab); set.add(ac); set.add(abc); set.add(abx); set.remove(ab); assertEquals(set.getUpper(a), new Object[] { ac, abx }); assertEquals(set.getUpper(b), new Object[] { abc, abx }); assertEquals(set.getUpper(c), new Object[] { ac }); assertEquals(set.getUpper(ac), new Object[] { abc }); } { Lattice set = new Lattice(); set.add(a); set.add(b); set.add(c); set.add(ab); set.add(ac); set.add(bc); assertEquals(set.getLower(Lattice.NONECLASS), new Object[] { ab, bc, ac }); assertEquals(set.getUpper(Object.class), new Object[] { a, b, c }); } { Comparator struc = Lattice.STRUCTURAL_ASSIGNABILITY; assertEquals(-1, struc.compare(TestA.class, TestA2.class)); assertEquals(-1, struc.compare(TestA2.class, TestA.class)); assertEquals(-1, struc.compare(TestB.class, TestB2.class)); assertEquals(-1, struc.compare(TestB2.class, TestB.class)); assertTrue(!TestA.class.isAssignableFrom(TestA2.class)); assertTrue(!TestA2.class.isAssignableFrom(TestA.class)); assertTrue(!TestB.class.isAssignableFrom(TestB2.class)); assertTrue(!TestB2.class.isAssignableFrom(TestB.class)); Lattice set = new Lattice(Lattice.STRUCTURAL_ASSIGNABILITY); set.add(TestA.class); set.add(TestA2.class); set.add(TestB.class); set.add(TestB2.class); assertEquals(new Object[] { TestA.class, TestA2.class }, set.getLower(TestB.class)); assertEquals(new Object[] { TestB.class, TestB2.class }, set.getUpper(TestA.class)); } */ } public static void testHierarchicalMap() { HierarchicalMap map = new HierarchicalMap( new Lattice(logicOrder, Integer.valueOf(0), Integer.valueOf(-1)), true); map.put(Integer.valueOf(0x001), "001"); map.put(Integer.valueOf(0x010), "010"); map.put(Integer.valueOf(0x100), "100"); map.put(Integer.valueOf(0x011), "011"); map.put(Integer.valueOf(0x110), "110"); map.put(Integer.valueOf(0x101), "101"); map.put(Integer.valueOf(0x111), "111"); assertTrue("001".equals(map.get(Integer.valueOf(0x001)))); assertTrue("010".equals(map.get(Integer.valueOf(0x010)))); assertTrue("100".equals(map.get(Integer.valueOf(0x100)))); assertTrue("011".equals(map.get(Integer.valueOf(0x011)))); assertTrue("110".equals(map.get(Integer.valueOf(0x110)))); assertTrue("101".equals(map.get(Integer.valueOf(0x101)))); assertTrue("111".equals(map.get(Integer.valueOf(0x111)))); assertTrue("010".equals(map.get(Integer.valueOf(0x10010)))); assertTrue("101".equals(map.get(Integer.valueOf(0x1101)))); assertTrue("111".equals(map.get(Integer.valueOf(0x11111)))); // test tie breaking //map.put(F.class, cmi); //assertSame(cmi, map.get(F.class)); } public static junit.framework.Test suite() { return new TestSuite(LatticeTest.class); } private static void assertEquals(final Object[] a, final Object[] b) { if (!new HashSet(Arrays.asList(a)) .equals(new HashSet(Arrays.asList(b)))) { throw new de.zarncke.lib.err.CantHappenException ("expected: " + Arrays.asList(a) + " but was: " + Arrays.asList(b)); } } }
package com.vilio.pcfs.glob; public enum GlobDict { //是否首次登录 first_login("1","首次登录"), un_first_login("0","非首次登录"), //是否锁定 hash_lock("0","用户锁定"), //短信业务类型 sms_login_type("00","登录短信验证码"), sms_borrow_type("01","借款短信验证码"), sms_login_pwd_type("02","忘记密码"), sms_trans_pwd_type("03","修改交易密码"), sms_authentication("04","身份验证"), //验证码是否有效 verify_effective("01","有效"), verify_invalid("00","无效"), verify_succ("02","验证通过(比如忘记密码,先验证一次验证码才能跳转到设置密码页面,设置新密码需要第二次验证验证码是否已经为验证通过状态)"), //验证码是否有效 baffle_switch_valid("1","有效"), baffle_switch_invalid("0","无效"), //登录类型 login_type_name("0","用户名密码登录"), login_type_mobile("1","手机密码登录"), login_type_email("2","邮箱密码登陆"), pwd_update_trans("0","修改密码"), pwd_first_trans("1","首次登录修改密码"), //交易密码标识 trans_pwd_exist("1","交易密码存在"), trans_pwd_unexist("0","交易密码不存在"), ; private String key; private String desc; GlobDict(String key, String desc) { this.key = key; this.desc = desc; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
package com.rofour.baseball.service.wallet; public interface WalletExceptionService { }
package com.example.fy.blog.util; /** * Created by fy on 2016/3/27. */ public class Contasts { public static final String BASE_URL = "http://git.oschina.net/api/v3/session"; public static final String URL_LOGIN = "account/login"; public static final String URL_REGISTER = ""; public static final String URL_GETBLOG = ""; public static final String URL_GETMYSELFBLOG = ""; public static final String URL_GETMYSELFCOLLECT = ""; public static final String URL_GETMYSELFCOMMENT = ""; public static final String URL_GETBLOGCOMMENT = ""; public static final String URL_SENDCOMMENT=""; public static final String SHARE_FILE_COOKIE = "share_cookies"; public static final String KEY_COOKIES ="Cookie"; public static final String KEY_USERNAME = "username"; public static final String KEY_PASSWORD = "password"; public static final String KEY_COOKIE = "Set-Cookies"; public static final String KEY_LOGIN_STATE = "login_state"; public static final String USER = "user"; public static final String PROP_KEY_USERNAME = "user.username"; public static final String PROP_KEY_PORTRAIT = "user.portrait"; public static final String PROP_KEY_NEWPORTRAIT = "user.new_portrait"; public static final int RESULT_USERNAME_ERROR = 1; public static final int RESULT_PASSWORD_ERROR = 2; }
public class Euclidean implements DistanceMeasure { public double calculateDistance(Unit unit1, Unit unit2){ int numOfVariables = unit1.getNumOfVariables(); double sum = 0; double unit1_var = 0; double unit2_var = 0; for (int i = 0; i < numOfVariables; i++){ unit1_var = unit1.getValue(i); unit2_var = unit2.getValue(i); sum += Math.pow((unit1_var - unit2_var), 2 ); } return Math.sqrt(sum); } }
package switch2019.project.domain.domainEntities.person; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import switch2019.project.domain.domainEntities.shared.Denomination; import static org.junit.jupiter.api.Assertions.*; class PersonNameTest { @Test void getPersonNameComplete() { //Arrange: PersonName personName = new PersonName("marTA gomES dE lEMos pInhEIro"); String expected = "Marta Gomes de Lemos Pinheiro"; //Act: String result = personName.getPersonName(); //Assert: assertEquals(expected, result); } @Test void getPersonNameNullCase() { //Arrange & Act try { new PersonName(null); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("The name can't be empty or null.", getTransactionsInDateRange.getMessage()); } } @Test void getPersonNameEmptyCase() { //Arrange & Act try { new PersonName(""); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("The name can't be empty or null.", getTransactionsInDateRange.getMessage()); } } @Test void getPersonNameRemoveExtraSpaces() { //Arrange: PersonName personName = new PersonName(" Marta Gomes de Lemos Pinheiro "); String expected = "Marta Gomes de Lemos Pinheiro"; //Act: String result = personName.getPersonName(); //Assert: assertEquals(expected, result); } @Test void getPersonNameCapitalizeEachWord() { //Arrange: PersonName personName = new PersonName("marTA gOmES lEmoS piNHEiRO"); String expected = "Marta Gomes Lemos Pinheiro"; //Act: String result = personName.getPersonName(); //Assert: assertEquals(expected, result); } @Test void getPersonNameExceptionalCases() { //Arrange: PersonName personName = new PersonName("marTA dA DE dO gomES dAS dOs lEMos pInhEIro"); String expected = "Marta da de do Gomes das dos Lemos Pinheiro"; //Act: String result = personName.getPersonName(); //Assert: assertEquals(expected, result); } @Test void getFirstAndLastName() { //Arrange: PersonName personName = new PersonName("marTA dA DE dO gomES dAS dOs lEMos pInhEIro"); String expected = "Marta Pinheiro"; //Act: String result = personName.getFirstAndLastName(); //Assert: assertEquals(expected, result); } @Test void personNameEqualsSameCase() { //Arrange: PersonName personName = new PersonName("Marta Gomes de Lemos Pinheiro"); PersonName personName2 = new PersonName("Marta Gomes de Lemos Pinheiro"); //Act: boolean result = personName.equals(personName2); //Assert: assertTrue(result); } @Test void personNameEqualsDifferentCase() { //Arrange: PersonName personName = new PersonName("marTA dA DE dO gomES dAS dOs lEMos pInhEIro"); PersonName personName2 = new PersonName("mArta DA de do gOmEs das DOs LeMoS PinheirO"); //Act: boolean result = personName.equals(personName2); //Assert: assertTrue(result); } @Test void personNameEqualsSameObject() { //Arrange: PersonName personName = new PersonName("Marta Gomes de Lemos Pinheiro"); //Act: boolean result = personName.equals(personName); //Assert: assertTrue(result); } @Test void personNameEqualsDifferentObject() { //Arrange: PersonName personName = new PersonName("Marta Pinheiro"); Denomination denomination = new Denomination("Just Testing"); //Act: boolean result = personName.equals(denomination); //Assert: assertFalse(result); } @Test void personNameEqualsNullObject() { //Arrange: PersonName personName = new PersonName("Marta Pinheiro"); PersonName personName2 = null; //Act: boolean result = personName.equals(personName2); //Assert: assertFalse(result); } /** * HashCode Tests: */ @Test @DisplayName("Happy Case - Same hashCode") void hashCodeVeridficationTestTrue() { //Arrange: PersonName personName1 = new PersonName("Francisca"); PersonName personName2 = new PersonName("Francisca"); //Act: boolean result = (personName1.hashCode() == personName2.hashCode()); //Assert: assertTrue(result); } @Test @DisplayName("False - Different hashCode") void hashCodeVeridficationTestFalse() { //Arrange: PersonName personName1 = new PersonName("Francisca"); PersonName personName2 = new PersonName("Francisco"); //Act: boolean result = (personName1.hashCode() == personName2.hashCode()); //Assert: assertFalse(result); } }
//**************** Oct 8***************** package JavaSessions; public class Car {// Car is a template //class variables or global variables String name; String model; int price; String color; public static void main(String[] args) { Car c1=new Car(); //c1 is the name/reference of the object //new Car() is the object c1.color="Blue"; c1.name="BMW"; c1.price=40000; c1.model="520d"; Car c2=new Car(); c2.color="White"; c2.name="Audi"; c2.price=48000; c2.model="Q7"; System.out.println(c1.name+ " "+ c1.color+ " "+ c1.price+ " "+c1.model); System.out.println(c2.name+ " "+ c2.color+ " "+ c2.price+ " "+c2.model); // no reference objects new Car().color="Black"; new Car().model="Honda"; //null reference object Car c3=new Car(); c3=null; System.gc(); } }
package TextStark; import java.util.Stack; public class TextStark { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("Java"); stack.push("C++"); stack.push("PHP"); System.out.println("栈中元素个数:" + stack.size()); System.out.println("栈顶元素:" + stack.peek()); System.out.println("出栈:" + stack.pop()); System.out.println("观察栈顶元素:" + stack.peek()); stack.pop(); stack.pop(); //stack.pop();EmptyStackException //System.out.println("观察栈顶元素:"+stack.peek());EmptyStackException if (stack.isEmpty()) { System.out.println("栈空了"); System.out.println("入栈:" + stack.push("MXM")); } else { System.out.println("出栈:" + stack.pop()); } System.out.println("观察栈顶元素:" + stack.peek()); } }
package com.fab.devportal.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fab.devportal.dao.ApiDescTbl; import com.fab.devportal.repo.APIDetailsRepository; @Service public class APIDetailsServiceImpl implements APIDetailsService{ @Autowired private APIDetailsRepository repository; public List<ApiDescTbl> findByApiName(String apiname){ return repository.findByApiName(apiname); } public Optional<ApiDescTbl> findById(Long id){ return repository.findById(id); } }
package com.rsm.yuri.projecttaxilivredriver.historicchatslist; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.rsm.yuri.projecttaxilivredriver.domain.FirebaseAPI; import com.rsm.yuri.projecttaxilivredriver.domain.FirebaseEventListenerCallback; import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.User; import com.rsm.yuri.projecttaxilivredriver.historicchatslist.events.HistoricChatsListEvent; import com.rsm.yuri.projecttaxilivredriver.lib.base.EventBus; import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.Driver; /** * Created by yuri_ on 13/01/2018. */ public class HistoricChatsListRepositoryImpl implements HistoricChatsListRepository { FirebaseAPI firebase; EventBus eventBus; public HistoricChatsListRepositoryImpl(FirebaseAPI firebase, EventBus eventBus) { this.firebase = firebase; this.eventBus = eventBus; } @Override public void subscribeForHistoricChatListUpdates() { /*firebase.checkForData(new FirebaseActionListenerCallback() {//addvalueEventListener @Override public void onSuccess() { } @Override public void onError(DatabaseError error) { if (error != null) { post(HistoricChatsListEvent.ERROR_EVENT, error.getMessage()); } else {//error==null não ha postagens(via FirebaseAPI.checkForData()) post(HistoricChatsListEvent.ERROR_EVENT, ""); } } });*/ firebase.subscribeForHistoricChatsListUpdates(new FirebaseEventListenerCallback() {//addChildEventListener @Override public void onChildAdded(DataSnapshot dataSnapshot) { String email = dataSnapshot.getKey(); email = email.replace("_","."); long online = ((Long)dataSnapshot.getValue()).longValue(); User user = new User(); user.setEmail(email); user.setStatus(online); post(HistoricChatsListEvent.onHistoricChatAdded, user); } @Override public void onChildChanged(DataSnapshot dataSnapshot){ String email = dataSnapshot.getKey(); email = email.replace("_","."); long online = ((Long)dataSnapshot.getValue()).longValue(); User user = new User(); user.setEmail(email); user.setStatus(online); post(HistoricChatsListEvent.onHistoricChatChanged, user); } @Override public void onChildMoved(DataSnapshot dataSnapshot){ } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { String email = dataSnapshot.getKey(); email = email.replace("_","."); long online = ((Long)dataSnapshot.getValue()).longValue(); User user = new User(); user.setEmail(email); user.setStatus(online); post(HistoricChatsListEvent.onHistoricChatRemoved, user); } @Override public void onCancelled(DatabaseError error) { post(HistoricChatsListEvent.ERROR_EVENT, error.getMessage()); } }); } @Override public void unSubscribeForHistoricChatListUpdates() { firebase.unSubscribeForHistoricChatsListUpdates(); } @Override public void changeUserConnectionStatus(int status) { firebase.changeUserConnectionStatus(status); } @Override public void getUrlPhotoUser(final User user) { firebase.getUrlPhotoDriver(user.getEmail(), new FirebaseEventListenerCallback(){ @Override public void onChildAdded(DataSnapshot dataSnapshot) { String url = (String) dataSnapshot.getValue(); User userUrlUpdated = user; userUrlUpdated.setUrlPhotoUser(url); post(HistoricChatsListEvent.onUrlPhotoDriverRetrived, userUrlUpdated); } @Override public void onChildChanged(DataSnapshot dataSnapshot) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot) { } @Override public void onCancelled(DatabaseError error) { post(HistoricChatsListEvent.ERROR_EVENT, error.getMessage()); } }); } @Override public void removeHistoricChat(String email) { firebase.removeHistoricChat(email); } @Override public void destroyHistoricChatListListener() { firebase.destroyHistoricChatsListener(); } private void post(int type, User user){ post(type, user, null); } private void post(int type, String error){ post(type, null, error); } private void post(int type, User user, String error){ HistoricChatsListEvent event = new HistoricChatsListEvent(); event.setEventType(type); event.setError(error); event.setUser(user); eventBus.post(event); } }
package at.xirado.bean.translation; import at.xirado.bean.data.LinkedDataObject; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.interactions.DiscordLocale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit; public class LocaleLoader { private static final Logger log = LoggerFactory.getLogger(LocaleLoader.class); public static final List<String> LANGUAGES = new ArrayList<>(); private static final Map<String, LinkedDataObject> LANGUAGE_MAP; static { Map<String, LinkedDataObject> m = new HashMap<>(); try (var is = LocaleLoader.class.getResourceAsStream("/assets/languages/list.txt")) { if (is == null) { throw new ExceptionInInitializerError("Could not initialize Language loader because list.txt does not exist!"); } for (var lang : new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)).lines().toList()) { var language = lang.trim(); LANGUAGES.add(language); } } catch (IOException e) { log.error("Could not initialize locale loader!"); throw new ExceptionInInitializerError(e); } for (String lang : LANGUAGES) { try (var is = LocaleLoader.class.getResourceAsStream("/assets/languages/" + lang)) { var name = lang.replace(".json", ""); LinkedDataObject json = LinkedDataObject.parse(is); if (json == null) continue; m.put(name, json.setMetadata(new String[]{name})); log.info("Successfully loaded locale {}", lang); } catch (Exception e) { log.error("Could not load locale '{}'!", lang, e); } } LANGUAGE_MAP = Collections.unmodifiableMap(m); } public static String[] getLoadedLanguages() { return (String[]) LANGUAGES.toArray(); } public static LinkedDataObject getForLanguage(String language) { var lang = LANGUAGE_MAP.get(language); if (lang == null) { return LANGUAGE_MAP.get("en_US"); } return lang; } public static LinkedDataObject ofGuild(Guild guild) { DiscordLocale locale = guild.getLocale(); String tag = locale.getLocale(); if (LANGUAGE_MAP.containsKey(tag)) { return LANGUAGE_MAP.get(tag); } else { return LANGUAGE_MAP.get("en_US"); } } public static boolean isValidLanguage(String lang) { return LANGUAGE_MAP.containsKey(lang); } public static String parseDuration(long seconds, LinkedDataObject languageJSON, String delimiter) { if (seconds == -1) { return languageJSON.getString("time.permanent"); } long days = TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - (days * 24); long minutes = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); long seconds1 = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); StringBuilder ges = new StringBuilder(); if (days != 0) { if (days == 1) { ges.append(days).append(" ").append(languageJSON.getString("time.day")).append(delimiter); } else { ges.append(days).append(" ").append(languageJSON.getString("time.days")).append(delimiter); } } if (hours != 0) { if (hours == 1) { ges.append(hours).append(" ").append(languageJSON.getString("time.hour")).append(delimiter); } else { ges.append(hours).append(" ").append(languageJSON.getString("time.hours")).append(delimiter); } } if (minutes != 0) { if (minutes == 1) { ges.append(minutes).append(" ").append(languageJSON.getString("time.minute")).append(delimiter); } else { ges.append(minutes).append(" ").append(languageJSON.getString("time.minutes")).append(delimiter); } } if (seconds1 != 0) { if (seconds1 == 1) { ges.append(seconds1).append(" ").append(languageJSON.getString("time.second")).append(delimiter); } else { ges.append(seconds1).append(" ").append(languageJSON.getString("time.seconds")).append(delimiter); } } String result = ges.toString(); return result.substring(0, result.length() - delimiter.length()); } }
package ladder.DynamicProgrammingII; /** * Given an integer array, adjust each integers so that the difference of every adjacent * integers are not greater than a given number target. * If the array before adjustment is A, the array after adjustment is B, * you should minimize the sum of |A[i]-B[i]| */ import java.util.ArrayList; public class MinimumAdjustmentCost { /** * @param A: An integer array. * @param target: An integer. */ public int MinAdjustmentCost(ArrayList<Integer> A, int target) { if (A == null || A.size() == 0) { return 0; } // f[i][j] 前i个数 第i个数调整为j, 满足相邻两数 <= target, 所需最小代价 int[][] f = new int[A.size() + 1][101]; for (int i = 0; i <= A.size(); i++) { for (int j = 0; j <= 100; j++) { f[i][j] = Integer.MAX_VALUE; } } for (int j = 0; j <= 100; j++) { f[0][j] = 0; } for (int i = 1; i <= A.size(); i++) { for (int j = 0; j <= 100; j++) { if (f[i - 1][j] != Integer.MAX_VALUE) { for (int k = 0; k <= 100; k++) { if (Math.abs(j - k) <= target) { if (f[i][k] > f[i - 1][j] + Math.abs(A.get(i - 1) - k)) { f[i][k] = f[i - 1][j] + Math.abs(A.get(i - 1) - k); } } } } } } int result = Integer.MAX_VALUE; for (int i = 0; i <= 100; i++) { result = Math.min(result, f[A.size()][i]); } return result; } public static void main(String[] args) { ArrayList<Integer> A = new ArrayList<>(); A.add(1); A.add(5); A.add(8); A.add(11); MinimumAdjustmentCost sol = new MinimumAdjustmentCost(); System.out.println(sol.MinAdjustmentCost(A, 2)); } }
package model.data_structures; public interface IListaSencillamenteEncadenada<T> { /** * Retornar el numero de elementos presentes en el arreglo * @return */ int darTamano( ); /** * Agregar un dato de forma compacta (en la primera casilla disponible) * Caso Especial: Si el arreglo esta lleno debe aumentarse su capacidad, agregar el nuevo dato y deben quedar multiples casillas disponibles para futuros nuevos datos. * @param nextLine nuevo elemento */ public void agregar(T dato ); /** * Eliminar un dato del arreglo. * Los datos restantes deben quedar "compactos" desde la posicion 0. * @param dato Objeto de eliminacion en el arreglo * @return dato eliminado */ void eliminar( T dato ); }
package com.a1tSign.techBoom.controller; import com.a1tSign.techBoom.data.dto.security.AuthResDTO; import com.a1tSign.techBoom.data.dto.security.LoginUserDTO; import com.a1tSign.techBoom.data.dto.security.RegisterUserDTO; import com.a1tSign.techBoom.security.JwtProvider; import com.a1tSign.techBoom.service.user.UserService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import static org.springframework.http.HttpStatus.CREATED; @RestController @RequestMapping ("api/v1/security") public class SecurityController { private final UserService userService; private final JwtProvider jwtProvider; public SecurityController(UserService userService, JwtProvider jwtProvider) { this.userService = userService; this.jwtProvider = jwtProvider; } @PostMapping ("/register") @ResponseStatus (CREATED) public void register(@RequestBody RegisterUserDTO dto) { userService.createNewUser(dto); } @PostMapping ("/login") @ResponseStatus(HttpStatus.OK) public AuthResDTO login(@RequestBody LoginUserDTO dto) { var user = userService.findByUsernameAndPassword(dto.getUsername(), dto.getPassword()); if (user == null) { throw new RuntimeException("Invalid username or password."); } var token = jwtProvider.generateToken(user.getUsername(), user.getRoles()); return new AuthResDTO(token); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.renu.controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author Atif Aslam */ @org.springframework.stereotype.Controller public class Controller { @RequestMapping(value = "/msg") public String success(){ return "msg"; } }
package com.marshalchen.ultimaterecyclerview.ui; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import in.srain.cube.views.ptr.PtrFrameLayout; /** * Created by cym on 15/3/21. */ public class CustomPtr extends PtrFrameLayout { public CustomPtr(Context context) { super(context); } public CustomPtr(Context context, AttributeSet attrs) { super(context, attrs); } public CustomPtr(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean dispatchTouchEvent(MotionEvent e) { return dispatchTouchEventSupper(e); } }
public class Farmer{ public Farmer(){ } }
package com.bluewise.testJava; /** * Created by wangshunchu on 15/12/28. */ public interface Istudent extends Iperson { public void sayClass(); }
/********************************************************************************************** * Distributed computing spring 2014 group 4 //Alex Ryder//Nick Champagne//Hue Moua// * //Daniel Gedge//Corey Jones// * Project 2 Peer2Peer client/server ***********************************************************************************************/ /********************************************************************************************** * This file opens as the client starts and associates with a server. ***********************************************************************************************/ import java.io.PrintStream; import java.net.*; import java.util.*; public class clientbackend extends Thread { public clientbackend() { } public void run() { Date date = new Date(); long initTime; long endTime; initTime = System.currentTimeMillis( ); try { System.out.println("preparing UDP broadcast"); byte senddata[] = "$$$".getBytes(); DatagramSocket clientN = new DatagramSocket(); clientN.setBroadcast(true); try { DatagramPacket sendPacket = new DatagramPacket(senddata, senddata.length, InetAddress.getByName("255.255.255.255"), 6785); clientN.send(sendPacket); System.out.println("broadcast to : 255.255.255.255"); } catch(Exception excep) { System.out.println("Failed to broadcast to : 255.255.255.255"); } for(Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { NetworkInterface networkInterface = (NetworkInterface)interfaces.nextElement(); if(!networkInterface.isLoopback() && networkInterface.isUp()) { Iterator i$ = networkInterface.getInterfaceAddresses().iterator(); while(i$.hasNext()) { InterfaceAddress interfaceAddress = (InterfaceAddress)i$.next(); InetAddress broadcast = interfaceAddress.getBroadcast(); if(broadcast != null) try { DatagramPacket sendPacket = new DatagramPacket(senddata, senddata.length, broadcast, 6785); clientN.send(sendPacket); System.out.println((new StringBuilder()).append("broadcast to : ").append(broadcast).toString()); } catch(Exception excep) { System.out.println("Error broadcast to : rest of broadcast pools"); } } } } System.out.println("Finished broadcasting"); byte recBuffer[] = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recBuffer, recBuffer.length); clientN.receive(receivePacket); String temp = (new String(receivePacket.getData())).trim(); if(temp.substring(0, 3).equals("%%%")) { clientNodeGui.serverAddy = receivePacket.getAddress().getHostAddress(); System.out.println((new StringBuilder()).append("Found server at ").append(clientNodeGui.serverAddy).append(":6666").toString()); } else { System.out.println((new StringBuilder()).append("recieved : ").append(temp).toString()); } clientN.close(); } catch(Exception excep) { System.out.println("failed on something major"); } endTime = System.currentTimeMillis( ); System.out.println("Associating with the server took "+(endTime-initTime)+" ms to complete"); } }
package eu.libal.cpptoolkit.gametheory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class CondorcetMethodTest { private CondorcetMethod condorcet; private List<String> DefaultVotingOptions; @Before public void setup() { DefaultVotingOptions = new ArrayList<>(); DefaultVotingOptions.add("A"); DefaultVotingOptions.add("B"); DefaultVotingOptions.add("C"); condorcet = new CondorcetMethod(DefaultVotingOptions); } @Test public void shouldNotThrowAnExceptionIfUsingOnlyValidOptions() throws Exception { condorcet.addRanking(Arrays.asList("A", "B", "C")); } @Test(expected = Exception.class) public void shouldThrownAnExceptionIfUsingInvalidOption() throws Exception { condorcet.addRanking(Arrays.asList("D")); } @Test public void shouldProduceExpectedVotingMatrix() throws Exception { condorcet.addRanking(Arrays.asList("A", "C", "B")); condorcet.addRanking(Arrays.asList("B")); condorcet.addRanking(Arrays.asList("A", "C")); condorcet.addRanking(Arrays.asList("B", "A", "C")); condorcet.addRanking(Arrays.asList("C", "A", "B")); int[][] mat = condorcet.votingMatrix(); Assert.assertEquals(3, mat[0][1]); Assert.assertEquals(3, mat[0][2]); Assert.assertEquals(2, mat[1][0]); Assert.assertEquals(2, mat[1][2]); Assert.assertEquals(1, mat[2][0]); Assert.assertEquals(3, mat[2][1]); } @Test public void shouldPickWinnerAsTheElementDominatingTheMostColumns() throws Exception { condorcet.addRanking(Arrays.asList("A", "C", "B")); condorcet.addRanking(Arrays.asList("B")); condorcet.addRanking(Arrays.asList("A", "C")); condorcet.addRanking(Arrays.asList("B", "A", "C")); condorcet.addRanking(Arrays.asList("C", "A", "B")); Assert.assertEquals("A", condorcet.pickWinner()); } // todo: should this throw an error if there is a tie? }
/* * Copyright (C) 2011 Make Ramen, 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 com.makeramen.segmented; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.RadioGroup; public class SegmentedRadioGroup extends RadioGroup { private int mBackgroundResId = R.drawable.segment_button; private int mBackgroundLeftResId = R.drawable.segment_radio_left; private int mBackgroundMiddleResId = R.drawable.segment_radio_middle; private int mBackgroundRightResId = R.drawable.segment_radio_right; public SegmentedRadioGroup(Context context) { super(context); } public SegmentedRadioGroup(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedRadioGroup); mBackgroundResId = a.getResourceId( R.styleable.SegmentedRadioGroup_android_background, R.drawable.segment_button); mBackgroundLeftResId = a.getResourceId( R.styleable.SegmentedRadioGroup_backgroundLeft, R.drawable.segment_radio_left); mBackgroundMiddleResId = a.getResourceId( R.styleable.SegmentedRadioGroup_backgroundMiddle, R.drawable.segment_radio_middle); mBackgroundRightResId = a.getResourceId( R.styleable.SegmentedRadioGroup_backgroundRight, R.drawable.segment_radio_right); a.recycle(); } @Override protected void onFinishInflate() { super.onFinishInflate(); updateButtonsStyle(); } public void updateButtonsStyle(){ int count = super.getChildCount(); if(count > 1){ super.getChildAt(0).setBackgroundResource(mBackgroundLeftResId); for(int i=1; i < count-1; i++){ super.getChildAt(i).setBackgroundResource(mBackgroundMiddleResId); } super.getChildAt(count-1).setBackgroundResource(mBackgroundRightResId); }else if (count == 1){ super.getChildAt(0).setBackgroundResource(mBackgroundResId); } } }
package com.littlecheesecake.redis.demo.controller; import com.littlecheesecake.redis.demo.annotation.RateLimiter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class RateController { @GetMapping("/rate/second/{id}") @RateLimiter(apiPath = "/rate/second", customerId = "{id}", unit = RateLimiter.UNIT.SECOND, limit = 2) public Object getRate(@PathVariable String id) { return "ok"; } @GetMapping("/rate/min/{id}") @RateLimiter(apiPath = "/rate/min", customerId = "{id}", unit = RateLimiter.UNIT.MINUTE, limit = 2) public Object getRateMin(@PathVariable String id) { return "ok"; } @GetMapping("/rate/hour/{id}") @RateLimiter(apiPath = "/rate/hour", customerId = "{id}", unit = RateLimiter.UNIT.HOUR, limit = 2) public Object getRateHour(@PathVariable String id) { return "ok"; } @GetMapping("/rate_free/{id}") public Object getRateFree(@PathVariable String id) { return "ok"; } }
/** Jake Written and maintained by Matthias Pueski Copyright (c) 2009 Matthias Pueski This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.pmedv.core.beans; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ApplicationWindowConfiguration", propOrder = { "title", "lastPerspectiveID", "x", "y", "width", "height", "statusbarVisible" }) public class ApplicationWindowConfiguration { private String title; private String lastPerspectiveID; private int x; private int y; private int height; private int width; private boolean statusbarVisible; /** * @return the lastPerspectiveID */ public String getLastPerspectiveID() { return lastPerspectiveID; } /** * @param lastPerspectiveID the lastPerspectiveID to set */ public void setLastPerspectiveID(String lastPerspectiveID) { this.lastPerspectiveID = lastPerspectiveID; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the x */ public int getX() { return x; } /** * @param x the x to set */ public void setX(int x) { this.x = x; } /** * @return the y */ public int getY() { return y; } /** * @param y the y to set */ public void setY(int y) { this.y = y; } /** * @return the height */ public int getHeight() { return height; } /** * @param height the height to set */ public void setHeight(int height) { this.height = height; } /** * @return the width */ public int getWidth() { return width; } /** * @param width the width to set */ public void setWidth(int width) { this.width = width; } /** * @return the statusbarVisible */ public boolean isStatusbarVisible() { return statusbarVisible; } /** * @param statusbarVisible the statusbarVisible to set */ public void setStatusbarVisible(boolean statusbarVisible) { this.statusbarVisible = statusbarVisible; } }
package com.google.android.exoplayer2.d; public final class b { public static boolean DEBUG = true; private static a apo = null; public static void a(a aVar) { apo = aVar; } public static void i(String str, String str2, Object... objArr) { if (apo != null) { apo.i(str, str2, objArr); } } public static void w(String str, String str2, Object... objArr) { if (apo != null) { apo.w(str, str2, objArr); } } public static void e(String str, String str2, Object... objArr) { if (apo != null) { apo.e(str, str2, objArr); } } }
package immersive.android.assembly.general.toolbarsandmenuslab; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; public class FaceTune extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_face_tune); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onNavigateUp(); } }); LinearLayout icon1 = (LinearLayout) findViewById(R.id.move); LinearLayout icon2 = (LinearLayout) findViewById(R.id.whiten); LinearLayout icon3 = (LinearLayout) findViewById(R.id.erase); LinearLayout icon4 = (LinearLayout) findViewById(R.id.help); icon1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(FaceTune.this, "Move Clicked", Toast.LENGTH_SHORT).show(); } }); icon2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(FaceTune.this, "Whiten Clicked", Toast.LENGTH_SHORT).show(); } }); icon3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(FaceTune.this, "Erase Clicked", Toast.LENGTH_SHORT).show(); } }); icon4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(FaceTune.this, "Help Clicked", Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.facetune_options, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.check_option: Toast.makeText(FaceTune.this, "Check Clicked", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } }
package com.framework.dao; import java.util.List; import java.util.Map; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.plugins.Page; import com.framework.model.ActReModel; public interface ActReModelMapper extends BaseMapper<ActReModel> { int deleteByPrimaryKey(String id); int insertSelective(ActReModel record); ActReModel selectByPrimaryKey(String id); int updateByPrimaryKeySelective(ActReModel record); int updateByPrimaryKey(ActReModel record); List<ActReModel> queryActReModelList(Page<ActReModel> mppage,Map<String, Object> params); }
package com.keithsmyth.testdealdetailsharness.map; import android.view.LayoutInflater; import android.view.ViewGroup; import com.keithsmyth.testdealdetailsharness.BaseFeatureController; import com.keithsmyth.testdealdetailsharness.R; import com.keithsmyth.testdealdetailsharness.model.Deal; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class MapFeature extends BaseFeatureController<MapModel, MapViewHolder> { @Override public List<MapModel> buildItems(Deal deal) { if (deal == null) { return emptyList(); } return singletonList(new MapModel(deal)); } @Override public MapViewHolder createViewHolder(ViewGroup parent, LayoutInflater inflater) { super.createViewHolder(parent, inflater); return new MapViewHolder(inflater.inflate(R.layout.map, parent, false)); } @Override public void bindViewHolder(MapViewHolder holder, MapModel mapModel) { super.bindViewHolder(holder, mapModel); } }
package com.elanelango.apps.twitterjoy.home; import android.content.Context; import android.content.Intent; import android.media.Image; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.elanelango.apps.twitterjoy.R; import com.elanelango.apps.twitterjoy.models.Tweet; import com.elanelango.apps.twitterjoy.models.User; import org.parceler.Parcels; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by eelango on 2/20/16. */ public class TweetsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<Tweet> tweets; public enum TweetType { TEXT(0); private int val; TweetType(int v) { val = v; } } public static class TextHolder extends RecyclerView.ViewHolder { @Bind(R.id.ivProfileImage) ImageView ivProfileImage; @Bind(R.id.tvName) TextView tvName; @Bind(R.id.tvScreenName) TextView tvScreenName; @Bind(R.id.tvText) TextView tvText; @Bind(R.id.tvTime) TextView tvTime; Context context; public TextHolder(Context context, View itemView) { super(itemView); this.context = context; ButterKnife.bind(this, itemView); } public void setTweet(final Tweet tweet) { tvName.setText(tweet.getUser().getName()); tvText.setText(tweet.getText()); tvTime.setText(tweet.getRelativeTime()); tvScreenName.setText("@" + tweet.getUser().getScreenName()); Glide.with(context) .load(tweet.getUser().getProfileImageUrl()) .into(ivProfileImage); ivProfileImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, ProfileActivity.class); i.putExtra("user", Parcels.wrap(User.class, tweet.getUser())); context.startActivity(i); } }); } } public TweetsAdapter(List<Tweet> tweets) { this.tweets = tweets; } @Override public int getItemViewType(int position) { return TweetType.TEXT.val; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater layoutInflater = LayoutInflater.from(context); View tweetView = layoutInflater.inflate(R.layout.item_tweet, parent, false); return new TextHolder(context, tweetView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Tweet tweet = tweets.get(position); TextHolder textHolder = (TextHolder) holder; textHolder.setTweet(tweet); } @Override public int getItemCount() { return tweets.size(); } public void addAll(List<Tweet> newTweets) { int position = tweets.size(); for (Tweet tweet : newTweets) { add(position, tweet); position++; } } public Tweet getLastTweet() { return get(tweets.size() - 1); } public Tweet getFirstTweet() { return get(0); } public Tweet get(int position) { int size = tweets.size(); if (size > 0) { return tweets.get(position); } else { return null; } } public void add(int position, Tweet tweet) { tweets.add(position, tweet); notifyItemInserted(position); } public void addAllToFront(List<Tweet> newTweets) { int position = newTweets.size() - 1; for (int i = position; i >= 0; i--) { add(0, newTweets.get(position)); } } }
package org.havryliuk.javaweb.model.exception; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MissingRequestParameterExceptionTest { @Test public void testMissingRequestParameterException() { String fieldName = "firstName"; MissingRequestParameterException e = new MissingRequestParameterException(fieldName); assertEquals(fieldName, e.getFieldName()); } }
package me.crafter.mc.multikillw; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; public class KillListener implements Listener { @EventHandler public void onPlayerDeath(PlayerDeathEvent event){ // Debug only if (Storage.debug){ DeathInfo.debug(event); } // Start final Map<String, String> info = DeathInfo.getDeathInfo(event); if (Storage.deathmessages){ event.setDeathMessage(Storage.getDeathMessage(info)); } if (Storage.combomessages){ Bukkit.getScheduler().runTask(Bukkit.getPluginManager().getPlugin("MultiKillW"), new Runnable(){ @Override public void run() { List<String> mkdmessages = MkdMessages.getMkdMessages(Bukkit.getPlayer(info.get("killername")), Bukkit.getPlayer(info.get("deadplayername"))); Storage.broadcastMessages(mkdmessages); } }); } } }
package com.allinpay.its.boss.framework.filter; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.allinpay.its.boss.framework.utils.ParameterRequestWrapper; /** * Class SpecialCharacterFilter * * @author 杨敏 * @version $Revision:0.1,$Date: 2011-10-21$ * * Description: 特殊字符过滤器 * * Function List: // 主要函数及其功能 * * 1. ------- * * History: // 历史修改记录 * * <author> <time> <version > <desc> * * 1. 杨敏 2011-10-21 0.1 创建 */ public class SpecialCharacterFilter implements Filter { public static List<String> whiteList; public static boolean isOpen; public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { req.setCharacterEncoding("UTF-8"); HttpServletRequest request = (HttpServletRequest) req; if ((!isOpen) || (dontFilter(request))) { chain.doFilter(req, res); return; } HashMap<String, String[]> m = new HashMap<String, String[]>(request.getParameterMap()); HashMap<String, String[]> mm = new HashMap<String, String[]>(); Enumeration<String> enu = request.getParameterNames(); if ((m.size() > 0) && (processParameters(m, enu, mm))) { ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper( request, mm); chain.doFilter(wrapRequest, res); } else { chain.doFilter(req, res); } } private boolean dontFilter(HttpServletRequest request) { String requestURL = request.getRequestURI(); for (String name : whiteList) { if (requestURL.indexOf(name) >= 0) { return true; } } return false; } public boolean processParameters(HashMap<String, String[]> m, Enumeration<?> enu, HashMap<String, String[]> mm) { if ((m != null) && (enu != null)) { while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); String[] values = (String[]) (String[]) m.get(key); for (int i = 0; i < values.length; i++) { if (values[i] != null) { values[i] = replaceSpecialChar(values[i]); } } mm.put(key, values); } } return true; } public static String replaceSpecialChar(String value) { value = value.replace("&", "&"); value = value.replace("<", "<"); value = value.replace(">", ">"); value = value.replace("\\", "\"); value = value.replace("\"", "“"); value = value.replace("'", "‘"); return value; } public static void main(String[] args) { System.out.println(replaceSpecialChar("\"'\\<>&")); } public void destroy() { } public void init(FilterConfig arg0) throws ServletException { String swicth = "on"; isOpen = true; if ((swicth != null) && (swicth.equals("off"))) { isOpen = false; } String[] s = { "", "" };// 白盒url,specialCharacterFilter.whiteList whiteList = new LinkedList<String>(); for (int i = 0; i < s.length; i++) { String value = s[i].trim(); if ((value == null) || (value.equals(""))) { continue; } whiteList.add(s[i].trim()); } } }
package exer; public class Test1 { public static void main(String[] args) { Test1 StringAsParamOfMethodDemo = new Test1(); StringAsParamOfMethodDemo.testA(); } private void testA() { String originalStr = "original"; System.out.println("Test A Begin:"); System.out.println("The outer String: " + originalStr); simpleChangeString(originalStr); System.out.println("The outer String after inner change: " + originalStr); System.out.println("Test A End."); System.out.println(); } public void simpleChangeString(String original) { original = original + " is changed!"; System.out.println("The changed inner String: " + original); } }
package com.qimou.sb.web.service; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.qimou.sb.web.entity.CustApplicationMan; import com.qimou.sb.web.entity.CustInventMan; import com.qimou.sb.web.entity.CustLinkMan; import com.qimou.sb.web.entity.Customer; import com.qimou.sb.web.mapper.CustomerDao; @Service // @Transactional public class CustomerService { @Autowired private CustomerDao customerDao; //列出 客户列表 public List<Customer> listCustomer(Map<Object, Object> conditionMap) { return customerDao.listCustomer(conditionMap); } //客户列表的总数量 public int customerNum(Map<Object, Object> conditionMap) { return customerDao.customerNum(conditionMap); } @Transactional public int addCustomer(Map<Object, Object> conditionMap) { return customerDao.addCustomer(conditionMap); } @Transactional public int updateCustomer(Map<Object, Object> conditionMap) { return customerDao.updateCustomer(conditionMap); } ////////////////////////////////////////////////////////////////////////// // 用于可编辑的下拉框,做模糊查询。 public List<Map<Object, Object>> listSimpleCustomer(Map<Object, Object> conditionMap){ return customerDao.listSimpleCustomer(conditionMap); } public List<CustApplicationMan> listCustApplicationman(Map<Object, Object> conditionMap){ return customerDao.listCustApplicationman(conditionMap); } public int custApplicationmanNum (Map<Object, Object> conditionMap){ return customerDao.custApplicationmanNum(conditionMap); } @Transactional public int addCustApplicationman (Map<Object, Object> conditionMap){ return customerDao.addCustApplicationman(conditionMap); } @Transactional public int updateCustApplicationman(Map<Object, Object> conditionMap){ return customerDao.updateCustApplicationman(conditionMap); } /////////////// public List<CustInventMan> listCustInventman(Map<Object, Object> conditionMap){ return customerDao.listCustInventman(conditionMap); } public int custInventmanNum (Map<Object, Object> conditionMap){ return customerDao.custInventmanNum(conditionMap); } @Transactional public int addCustInventman (Map<Object, Object> conditionMap){ return customerDao.addCustInventman(conditionMap); } @Transactional public int updateCustInventman(Map<Object, Object> conditionMap){ return customerDao.updateCustInventman(conditionMap); } /////////////// public List<CustLinkMan> listCustLinkman(Map<Object, Object> conditionMap){ return customerDao.listCustLinkman(conditionMap); } public int custLinkmanNum (Map<Object, Object> conditionMap){ return customerDao.custLinkmanNum(conditionMap); } @Transactional public int addCustLinkman (Map<Object, Object> conditionMap){ return customerDao.addCustLinkman(conditionMap); } @Transactional public int updateCustLinkman(Map<Object, Object> conditionMap){ return customerDao.updateCustLinkman(conditionMap); } }
package proyecto4; import java.io.*; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.util.*; public class graficador extends JFrame{ private int x; private int y; private int armonicos=1; private double cx; private double cy; private JPanel contentPane; public graficador(){ setTitle("Graficador"); setSize(600,400); setLocation(370,200); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); x=300; y=200; } public void coord(double cox,double coy){ cx=cox; cy=coy; } public void paint(Graphics g){ super.paint(g); g.setColor(Color.blue); //el tamaño del circulo sera de 2,2, la posicion se toma segun la funcion double auxx,auxy; while(true){ auxx=cx; auxy=cy; while(auxx==cx || auxy==cy); g.fillOval(300+(int)(auxx*300),y-100+(int)(y1*100),2,2); }//fin del while } /*public static void main(String[] args) { grafica g1=new grafica(); g1.setVisible(true); int armo=1; while(true){ Scanner leer=new Scanner(System.in); //System.out.println("Ingrese numero de armonicos: "); //armo=leer.nextInt(); g1.setArmonico(15); } }*/ }
package ru.android.messenger.view.interfaces; import ru.android.messenger.model.dto.response.FriendStatus; public interface UserInfoView extends ViewWithAlerts { void setFriendStatus(FriendStatus friendStatus); void setBlockStatus(boolean value); }
public class ReverseInteger { public int reverse(int x) { int res = 0; boolean isNegtive = x < 0 ? true : false; // leave last number to check overflow while (x/10 != 0) { res = 10 * res + x % 10; x /= 10; } int m = x % 10; // check overflow if ((!isNegtive && res > (Integer.MAX_VALUE - m)/10) || (isNegtive && res < (Integer.MIN_VALUE - m)/10)) { return 0; } res = 10 * res + m; return res; } public static void main(String args[]) { ReverseInteger sol = new ReverseInteger(); int[] nums = { 0, -0, // zero 10, -10, // end with zero 123, -123, // normal condition 1000000003, -1000000003, // overlow, and sign will change 1534236469, // overflow but sign will not chang 1463847412, -1463847412 // reverse between -2147483648 ~ 2147483647 }; int[] results = { 0, 0, // zero 1, -1, // no prefix zero 321, -321, // normal condition 0, 0, // return 0 when overflow 0, 2147483641, -2147483641 }; int count = nums.length; int failed = 0; int result; for (int i = 0; i < count; i++) { result = sol.reverse(nums[i]); if (result != results[i]) { failed++; System.out.println("Test: " + nums[i] + ", expect: " + results[i] + ", while returned: " + result); } } System.out.println("Test " + count + " cases: " + (count - failed) + " success, " + failed + " failed."); } }
package com.tencent.mm.plugin.chatroom; import com.tencent.mm.g.a.jv; import com.tencent.mm.g.a.jw; import com.tencent.mm.g.a.jx; import com.tencent.mm.g.a.jy; import com.tencent.mm.g.a.kc; import com.tencent.mm.g.a.rg; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; class d$6 extends c<rg> { final /* synthetic */ d hKI; d$6(d dVar) { this.hKI = dVar; this.sFo = rg.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { rg rgVar = (rg) bVar; if (rgVar.cbZ.cca.equals(jv.class.getName())) { if (rgVar.cbZ.bNI == 1) { d.a(this.hKI).cbp(); } else { d.a(this.hKI).aYG(); } } else if (rgVar.cbZ.cca.equals(jy.class.getName())) { if (rgVar.cbZ.bNI == 1) { d.b(this.hKI).cbp(); } else { d.b(this.hKI).aYG(); } } else if (rgVar.cbZ.cca.equals(jw.class.getName())) { if (rgVar.cbZ.bNI == 1) { d.c(this.hKI).cbp(); } else { d.c(this.hKI).aYG(); } } else if (rgVar.cbZ.cca.equals(jx.class.getName())) { if (rgVar.cbZ.bNI == 1) { d.d(this.hKI).cbp(); } else { d.d(this.hKI).aYG(); } } else if (rgVar.cbZ.cca.equals(kc.class.getName())) { if (rgVar.cbZ.bNI == 1) { d.e(this.hKI).cbp(); } else { d.e(this.hKI).aYG(); } } return false; } }
package misc; import java.io.Externalizable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * @author huangyongkang, created 2020-04-10 */ public class JustTest { private static Random random = new Random(); public static void main(String[] args) throws IOException, ClassNotFoundException { // List<Node> nodes = new ArrayList<>(); // // for (int i = 0; i < 10; i++) { // nodes.add(newNode()); // } // // nodes.sort(Comparator.comparing(Node::getSuccess)); // // nodes.forEach(Node::print); Node node = newNode(); node.print(); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/XM/test-node.txt")); oos.writeObject(node); oos.close(); File file = new File("/Users/XM/test-node.txt"); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); Node newNode = (Node)ois.readObject(); newNode.print(); } private static Node newNode() { Node node = new Node(); node.setSuccess(random.nextBoolean()); node.setCanToHistory(random.nextBoolean()); return node; } static class Node extends PrintDouble{ public Node() { } private Boolean success; private transient Boolean canToHistory; public void print() { System.out.println("success:" + success.toString() + " canToHistory:" + canToHistory); } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public Boolean getCanToHistory() { return canToHistory; } public void setCanToHistory(Boolean canToHistory) { this.canToHistory = canToHistory; } } }
package com.api.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.api.bean.FileAttBean; import com.api.conf.Configuration; import com.api.conf.DefaultConf; import com.api.conf.VarConstants; import com.api.filter.Authentication; import com.api.mapper.MonMapper; import com.api.parameter.MonParameter; import com.api.util.DatasourceMybatisSqlSession; import com.fasterxml.jackson.databind.ObjectMapper; import net.sf.json.JSONArray; @RestController public class UploadDownloadController { String fileRootDir = "/home/k8s/tomcat/tmp/"; // String fileRootDir = "D:/download/20190725/"; Configuration conf = null; @Authentication(validate=true) @RequestMapping(value="/api/file/upload",method=RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest request, HttpServletResponse resp) throws IOException{ conf = new Configuration(); conf.initialize(new File(System.getenv(VarConstants.VAR_SYSTEM_ENV_PATH_CONF_NAME))); DefaultConf.initialize(conf); fileRootDir = conf.get(VarConstants.VAR_FILE_ROOT_DIR); for (MultipartFile f : file) { if (f.isEmpty()) { System.out.println("no file upload."); } else { String fileName = f.getOriginalFilename(); //String path1 = request.getSession().getServletContext().getRealPath("image") + File.separator; //String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName; //System.out.println(path); File localFile = new File(fileRootDir+fileName); f.transferTo(localFile); } } return "[{\"dir\":\""+fileRootDir+"\"}]"; } @Authentication(validate=true) @RequestMapping("/api/file/download") public String download(String filePath,String fileName, HttpServletRequest request, HttpServletResponse response) { conf = new Configuration(); conf.initialize(new File(System.getenv(VarConstants.VAR_SYSTEM_ENV_PATH_CONF_NAME))); DefaultConf.initialize(conf); fileRootDir = conf.get(VarConstants.VAR_FILE_ROOT_DIR); if(filePath==null) { filePath=""; }else { filePath+="/"; } response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); try { InputStream inputStream = new FileInputStream(new File(fileRootDir+filePath + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "[{\"dir\":\""+fileRootDir+"\"}]"; } @Authentication(validate=true) @RequestMapping(value="/api/file/ls",method=RequestMethod.POST,produces="text/html;charset=UTF-8") @ResponseBody public String listLs(@RequestBody String jsonData,HttpServletRequest req, HttpServletResponse resp) { conf = new Configuration(); conf.initialize(new File(System.getenv(VarConstants.VAR_SYSTEM_ENV_PATH_CONF_NAME))); DefaultConf.initialize(conf); fileRootDir = conf.get(VarConstants.VAR_FILE_ROOT_DIR); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ObjectMapper mapper = new ObjectMapper(); Map m=null; try { m = mapper.readValue(jsonData, Map.class); } catch (IOException e) { e.printStackTrace(); } String id = (String) m.get("apid"); String dir = (String) m.get("dir"); if(dir==null||dir.trim().length()==0) { dir=""; }else { dir += "/"; } File[] list = new File(fileRootDir+dir).listFiles(); List lst = new ArrayList(); for(File file:list) { FileAttBean fab = new FileAttBean(); if(file.isFile()) { fab.setFiledir("f"); }else { fab.setFiledir("d"); } fab.setFileName(file.getName()); fab.setModifyTime(sdf.format(file.lastModified()*1000)); fab.setFileSize(file.length()+""); lst.add(fab); } JSONArray jsonarray = JSONArray.fromObject(lst); return jsonarray.toString(); } }
package cs455.scaling.server; import java.util.concurrent.atomic.AtomicLong; public class ServerStatus { private final AtomicLong clientsConnected = new AtomicLong(); private final AtomicLong packetsServed = new AtomicLong(); private final AtomicLong lastPacketCount = new AtomicLong(); private final AtomicLong lastStartTime = new AtomicLong(); private final long startTime; public ServerStatus() { lastStartTime.set(System.currentTimeMillis()); lastPacketCount.set(0); startTime = System.currentTimeMillis(); } public void addClient() { clientsConnected.incrementAndGet(); } public void removeClient() { clientsConnected.decrementAndGet(); } public void packetServed() { packetsServed.incrementAndGet(); } public long getClientCount() { return clientsConnected.get(); } public int getPacketsPerSecond() { // This is not entirely thread-safe, however, the worst that could happen is a packet or two gets added, // between grabbing the current start time and getting the packet count, since this is an average anyway // a packet or two should not make a difference, certainly not enough to accrue the overhead of a synchronize // block. long start = lastStartTime.getAndSet(System.currentTimeMillis()); return (int) (packetsServed.getAndSet(0) / ((System.currentTimeMillis() - start) / 1000)); } public TimeSpan getUptime() { return new TimeSpan(startTime, System.currentTimeMillis()); } }
package converter.Dto2Entity; import dao.CategoryDao; import dao.CategoryI18nDao; import dao.LocaleDao; import dto.CategoryDto; import entity.Category; import entity.CategoryI18n; import entity.Locale; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Component public class CategoryDto2CategoryConverter implements Converter<CategoryDto, Category> { private static final Logger LOGGER = Logger.getLogger(CategoryDto2CategoryConverter.class); @Autowired LocaleDao localeDao; @Autowired CategoryI18nDao categoryI18nDao; @Autowired CategoryDao categoryDao; @Override public Category convert(CategoryDto categoryDto) { Category category = categoryDto.getCategoryIdDto() != 0 ? categoryDao.read(categoryDto.getCategoryIdDto()) : new Category(); if (categoryDto.getLogo() != null) { try { category.setLogo(categoryDto.getLogo().getBytes()); } catch (IOException e) { LOGGER.error("error_field_upload_getBytes in categoryDto to category logo -img"); e.printStackTrace(); } } List<CategoryI18n> categoryI18nList = new ArrayList<>(); categoryI18nList.add(createI18N(categoryDto.getNameCategoryRus(), "ru", category)); categoryI18nList.add(createI18N(categoryDto.getNameCategoryEng(), "en", category)); category.setCategoryName(categoryI18nList); return category; } private CategoryI18n createI18N(String name, String locale, Category category) { Locale loc = localeDao.read(locale); CategoryI18n categoryI18n = new CategoryI18n(); if (category.getCategoryName() != null) { List<CategoryI18n> I18n = categoryI18nDao.getAll(loc); for (CategoryI18n categoryName : I18n) if (category.getCategoryId() == categoryName.getIdCategory().getCategoryId()) { categoryI18n = categoryName; } } categoryI18n.setLocaleCategoryI18n(loc); categoryI18n.setNameCategoryI18n(name); categoryI18n.setIdCategory(category); return categoryI18n; } }
package isden.mois.magellanlauncher.models; import android.support.v4.app.Fragment; public interface KeyDownListener { void onKeyDown(int keyCode); }
package com.example.jinliyu.shoppingapp_1.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.jinliyu.shoppingapp_1.R; public class AfterPaymentActivity extends AppCompatActivity { SharedPreferences sharedPreferences; String mobile, shipname, deliverAddr,billAddr,delivMobile,email,amount; TextView tvname, tvmobile, tvaddress, tvamount; Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_after_payment); sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); mobile = sharedPreferences.getString("mobile",""); shipname = sharedPreferences.getString("shipname",""); deliverAddr = sharedPreferences.getString("deliverAddr",""); billAddr = sharedPreferences.getString("billAddr",""); delivMobile = sharedPreferences.getString("delivMobile",""); email = sharedPreferences.getString("email",""); amount = sharedPreferences.getString("totalamount",""); tvname = findViewById(R.id.tvname); tvamount = findViewById(R.id.tvamount); tvaddress = findViewById(R.id.tvaddress); tvmobile = findViewById(R.id.tvmobile); btn = findViewById(R.id.gobackbtn); tvname.setText("Shipping Name: "+ shipname); tvaddress.setText("Shipping Address: " + deliverAddr); tvmobile.setText("Contact: "+ mobile); tvamount.setText("Total Amount: "+ amount); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AfterPaymentActivity.this, HomeActivity.class); startActivity(intent); } }); } }
/****************************************************************************** Write a program that Reverse an array using swaps (Page 17) given the Array Below; A={1,2,3,4,5,6,7,8,9} to B={9,8,7,6,5,4,3,2,1} *******************************************************************************/ public class ReverseArray { /*function swaps the array's first element with last element, second element with last second element and so on*/ static void reverse(int a[], int n) { int i, k, temp; for (i = 0; i < n / 2; i++) { temp = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = temp; } /*printing the reversed array*/ System.out.println("Reversed array is: "); for (k = 0; k < n; k++) { System.out.print(a[k] + " "); } } public static void main(String[] args) { int [] A = {1,2,3,4,5,6,7,8,9}; reverse(A, A.length); } }
import java.util.Locale; import java.util.Random; import java.util.Scanner; public class Dice { private final int MAX_VALUE = 6; private int rollValue; private boolean isDouble; private boolean isSecondDouble; public Dice() { // does this class need a constructor - should we do the thing we did in SDP for only allowing one instance? Singleton Pattern? this.isDouble = false; this.isSecondDouble = false; } private int roll() { Random rand = new Random(); int value = 1 + rand.nextInt(MAX_VALUE); return value; } public void nextPlayer() { isDouble = false; isSecondDouble = false; } public int getRollValue() { if(getIsDouble()){ System.out.println("\nYou rolled a double in your previous roll!"); } int totalRoll = 0; Scanner sc = new Scanner(System.in); String input; do{ System.out.println("Roll the dice by entering 'r' :"); input = sc.nextLine(); input = input.trim(); if(input.equalsIgnoreCase("r")){ break; } else{ System.out.println("Invalid input, please try again"); continue; } } while(true); int roll1 = roll(); System.out.print("You rolled a " + roll1); int roll2 = roll(); System.out.print(" and a " + roll2); totalRoll = roll1 + roll2; if (roll1 == roll2) { if (isDouble == true) { isSecondDouble = true; } else { isDouble = true; } } System.out.println(" = " + totalRoll + "\n"); rollValue = totalRoll; return totalRoll; } public boolean getIsDouble() { return isDouble; } public boolean getIsSecondDouble() { return isSecondDouble; } public void setIsDouble(boolean bool) { this.isDouble = bool; } public void setIsSecondDouble(boolean bool) { this.isSecondDouble = bool; } }
package com.smxknife.java2.bloom.test; import com.smxknife.java2.bloom.BloomHash; import com.smxknife.java2.bloom.JavaBitSetBloomFilter; /** * @author smxknife * 2021/4/13 */ public class JavaBitSetBloomFilterTest { public static void main(String[] args) { JavaBitSetBloomFilter filter = new JavaBitSetBloomFilter(new BloomHash[] { new BloomHash.DefaultBloomHash()}); filter.add(12); filter.add(20); System.out.println(filter.filter(10)); System.out.println(filter.filter(11)); System.out.println(filter.filter(12)); System.out.println(filter.filter(13)); System.out.println(filter.filter(20)); } }
package views; import controllers.Constant; import static controllers.Constant.COLOR_BACKGROUND_BUTTON; import static controllers.Constant.REGISTOR_FONT; import controllers.Events; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JSpinner; public class PanelRight extends JPanel{ public static final String REGISTOR_VOTES = "Registrar Votos"; private JComboBox jcbDepartment; private JSpinner jsVotesNumber; private JButton jbRegistor; public PanelRight(ArrayList<String> departaments, ActionListener controller) { setLayout(new GridLayout(3, 1)); jcbDepartment = new JComboBox(departaments.toArray()); jcbDepartment.setBackground(Color.decode(COLOR_BACKGROUND_BUTTON)); jcbDepartment.setFont(REGISTOR_FONT); add(jcbDepartment); jsVotesNumber = new JSpinner(); jsVotesNumber.setFont(REGISTOR_FONT); add(jsVotesNumber); jbRegistor = new JButton(REGISTOR_VOTES); jbRegistor.setBackground(Color.decode(Constant.COLOR_BACKGROUND_BUTTON)); jbRegistor.setFont(REGISTOR_FONT); jbRegistor.addActionListener(controller); jbRegistor.setActionCommand(Events.REGISTOR_VOTES.toString()); add(jbRegistor); } public int getVotesNumber() { return (Integer)jsVotesNumber.getValue(); } public String getDepartament() { return jcbDepartment.getSelectedItem().toString(); } public void cleanSpinn() { jsVotesNumber.setValue(0); } }
package com.example.behavioral.memento; /** * Copyright (C), 2020 * FileName: MementoPatternDemo * * @author: xieyufeng * @date: 2020/11/20 21:01 * @description: */ public class MementoPatternDemo { public static void main(String[] args) { CareTaker careTaker = new CareTaker(); Originator originator = new Originator("STATE #1"); careTaker.save(originator.saveMemento()); originator.setState("STATE #2"); originator.setState("STATE #3"); careTaker.save(originator.saveMemento()); originator.setState("STATE #4"); System.out.println("FIRST STATE:" + careTaker.get(0)); System.out.println("SECOND STATE:" + careTaker.get(1)); System.out.println("Originator state:" + originator.getState()); } }
package com.milano.architecture.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetProvider; import com.milano.bc.model.Corso; public class CorsoDAO implements DAOConstants { private CachedRowSet rowSet; public static CorsoDAO getFactory() throws SQLException { return new CorsoDAO(); } private CorsoDAO() throws SQLException { rowSet = RowSetProvider.newFactory().createCachedRowSet(); } public void createCorso(Connection conn, Corso c) throws SQLException { rowSet.setCommand(SELECT_CORSI); rowSet.execute(conn); rowSet.moveToInsertRow(); rowSet.updateInt(1, c.getCodice()); rowSet.updateString(2, c.getNome()); rowSet.updateDate(3, new java.sql.Date(c.getDataInizio().getTime())); rowSet.updateDate(4, new java.sql.Date(c.getDataFine().getTime())); rowSet.updateDouble(5, c.getCosto()); rowSet.updateString(6, c.getCommento()); rowSet.updateString(7, c.getAula()); rowSet.updateInt(8, c.getCodDocente()); rowSet.insertRow(); rowSet.moveToCurrentRow(); rowSet.acceptChanges(); } public void deleteCorso(Connection conn, int codCorso) throws SQLException { PreparedStatement ps = conn.prepareStatement(DELETE_CORSO); ps.setInt(1, codCorso); ps.execute(); conn.commit(); } public void updateCorso(Connection conn, Corso c) throws SQLException { PreparedStatement ps = conn.prepareStatement(UPDATE_CORSO); ps.setString(1, c.getNome()); ps.setDate(2, new java.sql.Date(c.getDataInizio().getTime())); ps.setDate(3, new java.sql.Date(c.getDataFine().getTime())); ps.setDouble(4, c.getCosto()); ps.setString(5, c.getCommento()); ps.setString(6, c.getAula()); ps.setInt(7, c.getCodDocente()); ps.setInt(8, c.getCodice()); ps.execute(); conn.commit(); } public Corso[] getCorsi(Connection conn) throws SQLException { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(SELECT_CORSI); rs.last(); Corso[] corsi = new Corso[rs.getRow()]; rs.beforeFirst(); for (int i = 0; rs.next(); i++) { Corso c = new Corso(); c.setCodice(rs.getInt(1)); c.setNome(rs.getString(2)); c.setDataInizio(rs.getDate(3)); c.setDataFine(rs.getDate(4)); c.setCosto(rs.getDouble(5)); c.setCommento(rs.getString(6)); c.setAula(rs.getString(7)); c.setCodDocente(rs.getInt(8)); corsi[i] = c; } rs.close(); return corsi; } public String getMigliorCorso(Connection conn) throws SQLException { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(SELECT_CORSI); int partecip = 0; String nomeCorso = ""; while (rs.next()) { PreparedStatement ps = conn.prepareStatement(COUNT_PARTECIP_BYID); ps.setInt(1, rs.getInt(1)); ResultSet rs2 = ps.executeQuery(); rs2.next(); int partecipantiCorso = rs2.getInt(1); if (partecipantiCorso > partecip) { partecip = partecipantiCorso; nomeCorso = rs.getString(2); } } return nomeCorso; } public Date getDataUltimoCorso(Connection conn) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT_DATA_ULTIMOCORSO); rs.next(); return rs.getDate(1); } public double getAvgCorso(Connection conn) throws SQLException { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(SELECT_CORSI); int sommaG = 0; int nCorsi = 0; while (rs.next()) { PreparedStatement ps = conn.prepareStatement(SELECT_DURATA_GG_CORSO); ps.setInt(1, rs.getInt(1)); ResultSet rs2 = ps.executeQuery(); rs2.next(); int durataCorso = rs2.getInt(1); int lavorativiCorso = durataCorso / 7; sommaG += durataCorso - (lavorativiCorso * 2); nCorsi++; } return sommaG / nCorsi; } public int getNumCommenti(Connection conn) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(COUNT_COMMENTI); rs.next(); return rs.getInt(1); } public Corso[] getCorsiDisp(Connection conn) throws SQLException { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(SELECT_CORSI); List<Corso> corsi = new ArrayList<Corso>(); while (rs.next()) { int codCorso = rs.getInt(1); long dataInizio = rs.getDate(3).getTime(); long dataOggi = new Date().getTime(); PreparedStatement ps = conn.prepareStatement(COUNT_PARTECIP_BYID); ps.setInt(1, codCorso); ResultSet rs2 = ps.executeQuery(); rs2.next(); int nPartecipanti = rs2.getInt(1); if (nPartecipanti < 13 && dataInizio > dataOggi) { PreparedStatement ps2 = conn.prepareStatement(SELECT_CORSI_BYID); ps2.setInt(1, codCorso); ResultSet rs3 = ps2.executeQuery(); rs3.next(); Corso c = new Corso(); c.setCodice(rs3.getInt(1)); c.setNome(rs3.getString(2)); c.setDataInizio(rs3.getDate(3)); c.setDataFine(rs3.getDate(4)); c.setCosto(rs3.getDouble(5)); c.setCommento(rs3.getString(6)); c.setAula(rs3.getString(7)); c.setCodDocente(rs3.getInt(8)); corsi.add(c); } } Corso[] arrayC = new Corso[corsi.size()]; for (int i = 0; i < arrayC.length; i++) { arrayC[i] = corsi.get(i); } return arrayC; } }
package com.zihui.cwoa.system.pojo; import java.util.List; public class sys_role { private Integer roleId; private String roleName; private Integer roleLevel; private String roleCode; private Integer roleParentId; private sys_role parentRole; private List<sys_users> users; private List<sys_menu> menus; public List<sys_menu> getMenus() { return menus; } public void setMenus(List<sys_menu> menus) { this.menus = menus; } public sys_role getParentRole() { return parentRole; } public void setParentRole(sys_role parentRole) { this.parentRole = parentRole; } public List<sys_users> getUsers() { return users; } public void setUsers(List<sys_users> users) { this.users = users; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName == null ? null : roleName.trim(); } public Integer getRoleLevel() { return roleLevel; } public void setRoleLevel(Integer roleLevel) { this.roleLevel = roleLevel; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode == null ? null : roleCode.trim(); } public Integer getRoleParentId() { return roleParentId; } public void setRoleParentId(Integer roleParentId) { this.roleParentId = roleParentId; } @Override public String toString() { return "sys_role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + ", roleLevel=" + roleLevel + ", roleCode='" + roleCode + '\'' + ", roleParentId=" + roleParentId + ", parentRole=" + parentRole + ", users=" + users + ", menus=" + menus + '}'; } }
package com.tencent.mm.plugin.appbrand.report.a; import com.tencent.mm.plugin.appbrand.page.p; public interface g extends f { public static final g grq = new 1(); a amJ(); a g(p pVar); boolean vr(String str); }
package com.qgil.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.qgil.common.pojo.DatatablesView; import com.qgil.mapper.QgilUserMapper; import com.qgil.pojo.QgilUser; import com.qgil.pojo.QgilUserExample; import com.qgil.pojo.QgilUserExample.Criteria; import com.qgil.service.QgilUserService; /** * 账户管理Service * @author 陈安一 * */ @Service public class QgilUserServiceImpl implements QgilUserService { @Autowired private QgilUserMapper qgiluserMapper; @Override public QgilUser getQgilUserByNamePassword(QgilUser manager) { if ("".equals(manager.getUsername()) || "".equals(manager.getPassword())) { return null; } // TODO Auto-generated method stub QgilUserExample gme = new QgilUserExample(); Criteria c = gme.createCriteria(); c.andUsernameEqualTo(manager.getUsername()); // Criteria criteria = gme.createCriteria(); List<QgilUser> list = qgiluserMapper.selectByExample(gme); if (list != null && list.size() > 0) { QgilUser mng = list.get(0); if (mng.getPassword().equals(manager.getPassword())) { return mng; } else { return null; } } return null; } @Override public QgilUser getQgilUserById(long parseLong) { QgilUser res = qgiluserMapper.selectByPrimaryKey(parseLong); return res; } @Override public QgilUser getQgilUserByName(String username) { QgilUserExample example = new QgilUserExample(); Criteria c = example.createCriteria(); c.andUsernameLike("%"+username+"%"); example.or(example.createCriteria().andRealnameLike("%"+username+"%")); List<QgilUser> res = qgiluserMapper.selectByExample(example); if (res != null && res.size() > 0) { return res.get(0); } return null; } @Override public int addQgilUser(QgilUser manager) { int res = qgiluserMapper.insert(manager); return res; } @Override public int editQgilUser(QgilUser manager) { int res = qgiluserMapper.updateByPrimaryKey(manager); return res; } @Override public int removeQgilUser(long id) { int res = qgiluserMapper.deleteByPrimaryKey(id); return res; } @Override public DatatablesView<?> getQgilUsersByPagedParam(QgilUser manager, Integer start, Integer pageSize) { // TODO Auto-generated method stub QgilUserExample gme = new QgilUserExample(); Criteria criteria = gme.createCriteria(); if (manager.getUsername() !=null && !"".equals(manager.getUsername())) { criteria.andUsernameLike("%"+manager.getUsername()+"%"); gme.or(gme.createCriteria().andRealnameLike("%"+manager.getUsername()+"%")); } int pageNum = (start/pageSize)+1; PageHelper.startPage(pageNum, pageSize); List<QgilUser> list = qgiluserMapper.selectByExample(gme); PageInfo<QgilUser> page = new PageInfo<>(list); DatatablesView result = new DatatablesView(); result.setData(list); result.setRecordsTotal((int)page.getTotal()); return result; } @Override public DatatablesView<?> getQgilUsersByParam(QgilUser manager) { // TODO Auto-generated method stub QgilUserExample gme = new QgilUserExample(); List<QgilUser> list = qgiluserMapper.selectByExample(gme); DatatablesView result = new DatatablesView(); result.setData(list); result.setRecordsTotal(list.size()); return result; } }
package LessonsJavaCore_14.Task_1; import java.util.*; import static MyClassesToWork.Print.print; public class main { public static void main(String[] args){ print("--------------\n" + " HashSet \n" + "--------------\n" + ""); Set<lessons14> lessons14Set = new HashSet<>(); for (int i = 0;i < 6;i++){ lessons14Set.add(new lessons14(randomString(),randomInt())); } for(lessons14 lessons14 : lessons14Set){ print(lessons14); } print("HashSet виводить елементи у випадковому порядку"); print("\n" + ""); print("--------------\n" + "LinkedHashSet \n" + "--------------\n" + ""); Set<lessons14> lessons14Set1 = new LinkedHashSet<>(); for (int i = 0;i < 6;i++){ lessons14Set1.add(new lessons14(randomString(),randomInt())); } for(lessons14 lessons14 : lessons14Set1){ print(lessons14); } print(""); print("LinkedHashSet виводить елементи в порядку їх додавання"); print("\n" + ""); print("--------------\n" + " TreeSet \n" + "--------------\n" + ""); Set<lessons14> lessons14Set2 = new TreeSet<>(); for (int i = 0;i < 6;i++){ lessons14Set2.add(new lessons14(randomString(),randomInt())); } for(lessons14 lessons14 : lessons14Set2){ print(lessons14); } print(""); print("TreeSet виводить елементи в порядку, перевизначення в Comparable (за замовчуванням)"); print("\n" + ""); print("--------------\n" + " TreeSet \n" + "--------------"); Set<lessons14> lessons14Set3 = new TreeSet<>(new compLesson14()); for (int i = 0;i < 6;i++){ lessons14Set3.add(new lessons14(randomString(),randomInt())); } for(lessons14 lessons14 : lessons14Set3){ print(lessons14); } print(""); print("TreeSet виводить елементи в порядку, перевизначення в Comparator"); } static int randomInt(){ Random random = new Random(); int i = random.nextInt(50)+1; return i; } static String randomString(){ Random random = new Random(); int i = random.nextInt(10)+1; if(i==1){ return "Aa"; }else if(i==2){ return "Bb"; }else if(i==3){ return "Cc"; }else if(i==4){ return "Dd"; }else if(i==5) { return "Gg"; }else if(i==6){ return "Ff"; }else if(i==7){ return "Hh"; }else if(i==9){ return "Ii"; }else { return "Jj"; } } }
package edu.iit.cs445.StateParking.Objects; import java.util.*; public class ReportOfAdmission extends Report { public ArrayList<ParkAdmDetail> admission_by_park = new ArrayList<ParkAdmDetail>(); public ReportOfAdmission() { this.id = 907; this.name = "Admission report"; this.StartDate = " "; this.EndDate = " "; this.total_admission = 0; } public ArrayList<ParkAdmDetail> getAdmission_by_park() { return admission_by_park; } public void addParkAdmission (int id, String name, int AdmCount) { ParkAdmDetail P = new ParkAdmDetail(id, name, AdmCount); admission_by_park.add(P); } public class ParkAdmDetail{ public int pid; public String name; public int AdmCount; public ParkAdmDetail(int id, String name, int AdmCount) { this.pid = id; this.name = name; this.AdmCount = AdmCount; } } }
import java.util.LinkedList; public class UnitTest { private static Store store = new Store(); public static void unitTest() { addItemsTest(); printItemsTest(); printItemsSortedTest(); searchItemSortedTest(); addCustomerTestTest(); printCustomersTest(); addItemToCartTest(); addToQueueTest(); runTest(); } private static void addItemsTest() { store.addItems(new Item("000", "64gb USB", 15.7, 50)); store.addItems(new Item("003", "Samsung 970EVO ", 150.7, 50)); store.addItems(new Item("001", "HDMI to DVI", 24.7, 50)); store.addItems(new Item("002", "128gb to DVI", 60.7, 50)); System.out.println("Stock added"); } private static void printItemsTest(){ System.out.println("Printing Stock"); store.printItem(); } private static void addCustomerTestTest(){ store.addNewCustomer(new Customer("0000000011236", "John Cena", "0000001", "Earth Home 1", "C1")); store.addNewCustomer(new Customer("0000000011233", "John Corner", "0000002", "Earth Home 2", "C2")); store.addNewCustomer(new Customer("0000000011234", "John Adam", "0000003", "Earth Home 3", "C3")); store.addNewCustomer(new Customer("0000000011238", "Michael Knight ", "0000004", "Earth Home 4", "C4")); store.addNewCustomer(new Customer("0000000011239", "Zill", "0000005", "Earth Home 5", "C5")); System.out.println("Customers added"); } private static void printCustomersTest(){ System.out.println("Printing Customers"); store.printCustomer(); } private static void printItemsSortedTest(){ System.out.println("Items After Sorting"); store.sortItems(); } private static void searchItemSortedTest(){ store.printItem(); System.out.println("Searching Item with 008"); Item res1 = store.searchItem("008"); if (res1 == null) System.out.println("Result not found"); else System.out.println(res1); System.out.println("Searching Item with 002"); Item res2 = store.searchItem("002"); if (res2 == null) System.out.println("Result not found"); else System.out.println(res2); } private static void addItemToCartTest(){ LinkedList<Item> items = new LinkedList<>(); items.add(new Item("000", "64gb USB", 15.7, 15)); items.add(new Item("003", "Samsung 970EVO ", 150.7, 5)); System.out.println("Adding Items in List 000,003"); System.out.println("Printing Queue"); System.out.println(store.addNewCustomerToQueue("C1", items)); } private static void addToQueueTest(){ LinkedList<Item> items = new LinkedList<>(); items.add(new Item("000", "64gb USB", 15.7, 15)); items.add(new Item("003", "Samsung 970EVO ", 150.7, 5)); System.out.println("Adding Items in List 000,003"); System.out.println("Printing Queue"); System.out.println(store.addNewCustomerToQueue("C1", items)); } private static void runTest(){ System.out.println("Running the process"); store.run(); } public static void main(String[] args) { unitTest(); } }
package arrays; /** * Leetcode 41. */ public class FirstMissingPositive { public static void main(String[] args) { } }
package com.eratoiklio.neighborscar.ride; import org.springframework.data.jpa.repository.JpaRepository; public interface RideRepository extends JpaRepository<Ride, Long>, RideRepositoryCustom { }
package br.edu.ifam.saf.relatorios; import android.util.Log; import br.edu.ifam.saf.SAFService; import br.edu.ifam.saf.api.data.ItemRelatorioResponse; import br.edu.ifam.saf.api.data.MensagemErroResponse; import br.edu.ifam.saf.util.ApiCallback; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class RelatoriosPresenter implements RelatoriosContract.Presenter { private RelatoriosContract.View view; private SAFService service; public RelatoriosPresenter(RelatoriosContract.View view, SAFService service) { this.view = view; this.service = service; } void fechMaisAlugados() { service.relatorioItensMaisAlugados() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new ApiCallback<ItemRelatorioResponse>() { @Override public void onSuccess(ItemRelatorioResponse response) { view.mostrarItensMaisAlugados(response.getItens()); } @Override public void onError(MensagemErroResponse mensagem) { Log.w("RelatorioPresenter", mensagem.join()); } @Override public boolean canExecute() { return view != null; } }); } void fetchMediaItensPorAluguel() { service.relatorioItensMaisAlugados() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new ApiCallback<ItemRelatorioResponse>() { @Override public void onSuccess(ItemRelatorioResponse response) { view.mostrarMediaDeItensPorAluguel(response.getItens().get(0)); } @Override public void onError(MensagemErroResponse mensagem) { Log.w("RelatorioPresenter", mensagem.join()); } @Override public boolean canExecute() { return view != null; } }); } void fetchUsuarioMaisFrequentes() { service.usuariosMaisFrequentes() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new ApiCallback<ItemRelatorioResponse>() { @Override public void onSuccess(ItemRelatorioResponse response) { view.mostrarUsuariosMaisFrequentes(response.getItens()); } @Override public void onError(MensagemErroResponse mensagem) { Log.w("RelatorioPresenter", mensagem.join()); } @Override public boolean canExecute() { return view != null; } }); } @Override public void start() { fechMaisAlugados(); fetchMediaItensPorAluguel(); fetchUsuarioMaisFrequentes(); } @Override public void destroy() { view = null; } }
package com.appdear.client.model; import java.io.Serializable; /** * 访问权限列表 * @author zqm * */ public class PermissionListInfo implements Serializable { /** * 权限编码 */ public String permcode = ""; /** * 权限中文描述 */ public String permdescch = ""; /** * 权限英文描述 */ public String permdescen = ""; /** * 权限类型 */ public int permtype; }
package main; import net.egork.utils.io.InputReader; import net.egork.utils.io.OutputWriter; public class TaskC { long h1, a1, x1, y1, x, p1; long h2, a2, x2, y2, y, p2; int m; int count; long calk_x(long h){ count++; if(count>m+21)return Integer.MAX_VALUE; if(h==a1)return 0; else return 1+calk_x((h*x1+y1)%m); } long calk_y(long h){ count++; if(count>m+21)return Integer.MAX_VALUE; if(h==a2)return 0; else return 1+calk_y((h*x2+y2)%m); } public void solve(int testNumber, InputReader in, OutputWriter out) { m = in.readInt(); h1 = in.readInt(); a1 = in.readInt(); x1 = in.readInt(); y1 = in.readInt(); h2 = in.readInt(); a2 = in.readInt(); x2 = in.readInt(); y2 = in.readInt(); count=0; x=calk_x(h1); if(x>=Integer.MAX_VALUE){ out.printLine("-1"); return; } count=0; y=calk_y(h2); if(y>=Integer.MAX_VALUE){ out.printLine("-1"); return; } //out.printLine(x+" "+p1+" "+y+" "+p2); count=0; p1=calk_x((a1*x1+y1)%m)+1; if(p1>=Integer.MAX_VALUE){ p1=Integer.MAX_VALUE; //out.printLine("-1"); //return; } count=0; p2=calk_y((a2*x2+y2)%m)+1; if(p2>=Integer.MAX_VALUE){ p2=Integer.MAX_VALUE; //out.printLine("-1"); // return; } if(p1==Integer.MAX_VALUE||p2==Integer.MAX_VALUE){ if(p1==Integer.MAX_VALUE&&p2==Integer.MAX_VALUE){ if(x==y){ out.print(x); return; } } else if(p1!=Integer.MAX_VALUE&&y>=x){// long nn=y-x; nn/=p1; if(nn*p1+x==y){ out.print(y); return; } else {//out.printLine("hic"); out.print(-1); return; } } else if(p2!=Integer.MAX_VALUE&&x>=y){ long nn=x-y; nn/=p2; if(nn*p2+y==x){ out.print(x); return; } else { out.print(-1); return; } } else { out.print(-1); return; } } for(int i=0;i<=1000111;i++){ long tem=x+i*p1; long t=tem-y; if(t<0)continue; long mm=t/p2; if(mm*p2+y==tem){ out.print(tem); return; } } for(int i=0;i<=1000111;i++){ long tem=y+i*p2; long t=tem-x; if(t<0)continue; long mm=t/p1; if(mm*p1+x==tem){ out.print(tem); return; } } out.print(-1); } }
package example.payroll; import java.util.Optional; import java.util.UUID; public interface PersonRepository { // ... Optional<Person> findByUuid(UUID uuid); // ... }
package cn.hrmzone.table; import cn.hrmzone.util.FileNameParser; import com.baidu.aip.ocr.AipOcr; import org.json.JSONArray; import org.json.JSONObject; import java.util.HashMap; public class TableOcr { private AipOcr client; private String imgPath; ExcelUtil excelUtil; String sheetName,fileName; public TableOcr(AipOcr client, String imgPath) { this.client = client; this.imgPath = imgPath; } /** * 解析图片表格数据,根据返回的json,获取row、col和内容,将数据存入响应的excel行和列 */ public void writeFile() { excelUtil=new ExcelUtil(imgPath); excelUtil.newSheet(imgPath); HashMap<String,String> options=new HashMap<String,String>(); options.put("language_type", "CHN_ENG"); options.put("detect_direction", "true"); JSONObject res=client.form(imgPath,options); /* 返回的json,是一个多层嵌套的json内容,需要先获取JSONArray,再从中获取一个jsonobject,再获取JSONArray。 可以通过格式化全部json内容,查看详细的分层格式 */ JSONArray bodyArray=res.getJSONArray("forms_result").getJSONObject(0).getJSONArray("body"); int len=bodyArray.length(); for(int i=0;i<len;i++) { JSONObject obj=bodyArray.getJSONObject(i); int row=obj.getInt("row"); int col=obj.getInt("column"); String words=obj.getString("words"); excelUtil.writeCell(row,col,words); } excelUtil.writeExcel(); } }
package top.wangruns.nowcoder.sword2offer; /** * * 题目描述 统计一个数字在排序数组中出现的次数 * * 分析 看看到了排序的数组中查找某一个值很自然的就想到了二分查找,这里可以先查找第一次和最后一次出现的位置 */ public class P37_数字在排序数组中出现的次数 { public int GetNumberOfK(int [] array , int k) { int l=0,r=array.length-1,firstIndex=1,lastIndex=0; //获取第一次出现的下标 while(l<=r) { int mid=(l+r)/2; if(array[mid]<k) l=mid+1; else if(array[mid]==k) { r=mid-1; firstIndex=mid; } else r=mid-1; } l=0;r=array.length-1; //获取第最后一次出现的下标 while(l<=r) { int mid=(l+r)/2; if(array[mid]<k) l=mid+1; else if(array[mid]==k) { l=mid+1; lastIndex=mid; } else r=mid-1; } return lastIndex-firstIndex+1; } }
package Deck; public enum Rank { ACE("ace", 11), TWO("two", 2), THREE("three", 3), FOUR("four", 4), FIVE("five", 5), SIX("six", 6), SEVEN("seven", 7), EIGHT("eight", 8), NINE("nine", 9), TEN("ten", 10), JACK("jack", 10), QUEEN("queen", 10), KING("king", 10); // variables protected final String rankName; protected final int value; Rank(String rankName, int value){ this.rankName = rankName; this.value = value; } public String getRankName(){ return rankName; } public int getValue(){ return value; } }