hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
1e0c681e3c6755bdf99c2a1e28d96a8017b3e47f | 554 | package ch.heigvd.amt.model;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MovieTest {
@Test
public void shouldCreateAMovie() {
Movie movie = Movie.builder()
.id(404)
.title("Not Found")
.year(2019)
.build();
assertNotNull(movie);
assertEquals(404, movie.getId());
assertEquals("Not Found", movie.getTitle());
assertEquals(2019, movie.getYear());
}
}
| 22.16 | 52 | 0.590253 |
be3e131f5247e23802c8f8d03746d6ed6b289daf | 873 | /*
* Given numRows, generate the first numRows of Pascal's triangle.
* For example, given numRows = 5,
* Return
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
*/
public class PascalTriangle {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0)
return result;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
result.add(list);
for (int i = 1; i < numRows; i++) {
List<Integer> next = new ArrayList<Integer>();
next.add(1);
for (int j = 1; j < list.size(); j++)
next.add(list.get(j - 1) + list.get(j));
next.add(1);
list = next;
result.add(list);
}
return result;
}
}
| 23.594595 | 68 | 0.484536 |
bf786d8692b93a30f5e46c6fe647d7c1fe836c99 | 1,846 | package models.client;
import java.util.*;
import javax.persistence.Column;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import play.Logger;
import models.orders.Orders;
@Entity
public class ClientReferalEarning extends Model{
@Id
public Long id;
@Column(nullable=false)
public double referal_earning_value;//values in US dollars
public Date date_earned;
//Model relationship
@ManyToOne
public ReferralCode referralCode;
@OneToOne
public Orders orders;
//constructor
public ClientReferalEarning(){}
public static Finder<Long, ClientReferalEarning> find() {
return new Finder<Long, ClientReferalEarning>(Long.class, ClientReferalEarning.class);
}
public void saveclientReferalEarning(){
if(id == null){
date_earned = new Date();
save();
}else{
update();
}
}
public static ClientReferalEarning getEarningByID(Long id){
return ClientReferalEarning.find().byId(id);
}
public static double getClientReferalEarning(String email){
double total_earning = 0.00;
Client client = Client.getClient(email);
ReferralCode referal_code = client.referralCode;
if(referal_code == null){
return 0.00;
}
//get a list of earning using the referal_code
List<ClientReferalEarning> clientReferalEarningList = new ArrayList<ClientReferalEarning>();
clientReferalEarningList = referal_code.clientReferalEarning;
if(clientReferalEarningList.isEmpty()){
return 0.00;
}
for(ClientReferalEarning ace: clientReferalEarningList){
total_earning = total_earning + ace.referal_earning_value;
}
return total_earning;
}
} | 27.147059 | 95 | 0.719935 |
96030962a9fe2800328bf9a4c5ac637264d55483 | 1,621 | /*
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.logging.eelf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.att.eelf.configuration.Configuration;
import org.junit.Test;
public class DroolsPdpMdcInfoTest {
/**
* Test method for {@link org.onap.policy.common.logging.eelf.DroolsPdpMdcInfo#getMdcInfo()}.
*/
@Test
public void testGetMdcInfo() {
DroolsPdpMdcInfo di = new DroolsPdpMdcInfo();
assertNotNull(di.getMdcInfo());
assertEquals("Policy.droolsPdp", di.getMdcInfo().get(Configuration.MDC_SERVICE_NAME));
}
}
| 37.697674 | 97 | 0.595928 |
f63e9c5b246352eb8a8c3b05ca8023c9cdd50a19 | 1,897 | package com.bfsi.mfi.vo;
import java.util.Date;
import com.bfsi.mfi.entity.MbsReqReceiverView;
public class MbsReqReceiverViewVO extends MaintenanceVO<MbsReqReceiverView>{
public MbsReqReceiverViewVO() {
entity = new MbsReqReceiverView();
}
public MbsReqReceiverViewVO(MbsReqReceiverView entity) {
super(entity);
}
public String getTxnDesc() {
return entity.getTxnDesc();
}
public void setTxnDesc(String txnDesc) {
entity.setTxnDesc(txnDesc);
}
public String getTxnCode() {
return entity.getTxnCode();
}
public void setTxnCode(String txnCode) {
entity.setTxnCode(txnCode);
}
public String getCbsAcRefNo() {
return entity.getCbsAcRefNo();
}
public void setCbsAcRefNo(String cbsAcRefNo) {
entity.setCbsAcRefNo(cbsAcRefNo);
}
public String getBranchCode() {
return entity.getBranchCode();
}
public void setBranchCode(String branchCode) {
entity.setBranchCode(branchCode);
}
public String getCustomerId() {
return entity.getCustomerId();
}
public void setCustomerId(String customerId) {
entity.setCustomerId(customerId);
}
public String getAgentId() {
return entity.getAgentId();
}
public void setAgentId(String agentId) {
entity.setAgentId(agentId);
}
public String getDeviceId() {
return entity.getDeviceId();
}
public void setDeviceId(String deviceId) {
entity.setDeviceId(deviceId);
}
public String getLocationCode() {
return entity.getLocationCode();
}
public void setLocationCode(String locationCode) {
entity.setLocationCode(locationCode);
}
public Date getTxnInitTime() {
return entity.getTxnInitTime();
}
public void setTxnInitTime(Date txnInitTime) {
entity.setTxnInitTime(txnInitTime);
}
public String getTxnStatusDesc() {
return entity.getTxnStatusDesc();
}
public void setTxnStatusDesc(String txnStatusDesc) {
entity.setTxnStatusDesc(txnStatusDesc);
}
}
| 19.161616 | 76 | 0.74117 |
c7acf1f164ff42c87320396c3c4d14033fedc349 | 3,350 | package io.kimmking.cache.tester;
import com.google.common.collect.Maps;
import io.kimmking.cache.entity.Author;
import io.kimmking.cache.entity.Order;
import io.kimmking.cache.service.AuthorService;
import io.kimmking.cache.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.*;
/**
* Copyright (C) 2021 ShangHai IPS Information Technology Co.,Ltd.
* <p>
* All right reserved.
* <p>
* This software is the confidential and proprietary information of IPS
* Company of China. ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the terms
* of the contract agreement you entered into with IPS inc.
* <p>
*
* @Description: redis cache 测试
* @ClassName: MybatisCacheTest
* @Auther: nydia.lhq
* @Date: 2021/7/13 16:13
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class RedisCacheTest {
@Autowired
Jedis jedis;
@Autowired
OrderService orderService;
//缓存穿透 大量并发请求找不到缓存的数据,直接查库
@Test
public void cacheThrough(){
int count = 0;
int i = 1;
for(;;){
if(i > 20)
break;
count ++;
String ordder_id = jedis.get("author_id");
if(ordder_id == null || "".equals(ordder_id)){
Order order = orderService.find(1);
if(order != null)
ordder_id = order.getId().toString();
}
System.out.println(ordder_id);
System.out.println("i=" + i);
i++;
}
System.out.println("count=" + count);
}
//缓存击穿
@Test
public void cacheBreakdown() throws Exception{
jedis.psetex("key", 20000, "我是redis的值");
int i = 0;
for(;;){
if(i > 20)break;
Thread.sleep(20000);
String ordder_id = jedis.get("author_id");
Order order = orderService.find(1);
if(order != null) ordder_id = order.getId().toString();
System.out.println(String.format("i的值%s", ordder_id));
i ++;
}
}
//缓存雪崩
@Test
public void cacheAvalanche(){
int timeout = 10000;
//存储大量cache
int i = 6;
for(;;){
if(i > 6)break;
jedis.psetex(String.valueOf(i), timeout, orderService.find(i).getOrderNo());
i ++;
}
List<String> keys = Arrays.asList("key1","key2","key3","key4","key5");
keys.parallelStream().forEach(e -> jedis.psetex(e, 10000, e + "-val"));
try {
Thread.sleep(timeout);
}catch (InterruptedException e){
e.printStackTrace();
}
//同时取这些失效的cache
Set<Integer> set = new HashSet<>(Arrays.asList(1,2,3,4,5,6));
set.parallelStream().forEach(e -> {
if(jedis.get(String.valueOf(e)) == null){
Order order = orderService.find(e);
}
});
}
}
| 27.235772 | 88 | 0.597313 |
0c4239fa5000c144d3c68220e445e8c6afe78590 | 3,378 | package gg.projecteden.nexus.features.store.perks.autosort.commands;
import gg.projecteden.nexus.Nexus;
import gg.projecteden.nexus.features.listeners.TemporaryListener;
import gg.projecteden.nexus.framework.commands.models.CustomCommand;
import gg.projecteden.nexus.framework.commands.models.annotations.Path;
import gg.projecteden.nexus.framework.commands.models.annotations.Permission;
import gg.projecteden.nexus.framework.commands.models.events.CommandEvent;
import gg.projecteden.nexus.models.autosort.AutoSortUser;
import gg.projecteden.nexus.models.autosort.AutoSortUser.AutoTrashBehavior;
import gg.projecteden.nexus.models.autosort.AutoSortUserService;
import gg.projecteden.nexus.utils.ItemUtils.ItemStackComparator;
import gg.projecteden.nexus.utils.StringUtils;
import gg.projecteden.nexus.utils.Utils;
import lombok.NonNull;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import static gg.projecteden.nexus.utils.ItemUtils.isNullOrAir;
@Permission("store.autosort")
public class AutoTrashCommand extends CustomCommand {
private final AutoSortUserService service = new AutoSortUserService();
private AutoSortUser user;
public AutoTrashCommand(@NonNull CommandEvent event) {
super(event);
if (isPlayerCommandEvent())
user = service.get(player());
}
@Path("materials")
void materials() {
new AutoTrashMaterialEditor(user);
}
@Path("behavior [behavior]")
void behavior(AutoTrashBehavior behavior) {
if (behavior == null) {
send("Current behavior is " + camelCase(user.getAutoTrashBehavior()));
return;
}
user.setAutoTrashBehavior(behavior);
service.save(user);
send(PREFIX + "Auto Trash behavior set to " + camelCase(behavior));
}
public static class AutoTrashMaterialEditor implements TemporaryListener {
private static final String TITLE = StringUtils.colorize("&eAuto Trash");
private final AutoSortUser user;
@Override
public Player getPlayer() {
return user.getOnlinePlayer();
}
public AutoTrashMaterialEditor(AutoSortUser user) {
this.user = user;
Inventory inv = Bukkit.createInventory(null, 6 * 9, TITLE);
inv.setContents(user.getAutoTrashInclude().stream()
.map(ItemStack::new)
.sorted(new ItemStackComparator())
.toArray(ItemStack[]::new));
Nexus.registerTemporaryListener(this);
user.getOnlinePlayer().openInventory(inv);
}
@EventHandler
public void onChestClose(InventoryCloseEvent event) {
if (event.getInventory().getHolder() != null) return;
if (!Utils.equalsInvViewTitle(event.getView(), TITLE)) return;
if (!event.getPlayer().equals(user.getOnlinePlayer())) return;
Set<Material> materials = Arrays.stream(event.getInventory().getContents())
.filter(item -> !isNullOrAir(item))
.map(ItemStack::getType)
.collect(Collectors.toSet());
user.setAutoTrashInclude(materials);
new AutoSortUserService().save(user);
user.sendMessage(StringUtils.getPrefix("AutoTrash") + "Automatically trashing " + materials.size() + " materials");
Nexus.unregisterTemporaryListener(this);
event.getPlayer().closeInventory();
}
}
}
| 33.445545 | 118 | 0.772647 |
810a0433fee49efd1b664c085cdbaa80f28ee2e7 | 1,316 | package org.knowm.xchange.loyalbit.service;
import java.io.IOException;
import javax.crypto.Mac;
import javax.ws.rs.FormParam;
import org.knowm.xchange.service.BaseParamsDigest;
import net.iharder.Base64;
import si.mazi.rescu.RestInvocation;
public class LoyalbitDigest extends BaseParamsDigest {
private final String clientId;
private final byte[] apiKey;
private LoyalbitDigest(String secretKeyHex, String clientId, String apiKeyHex) throws IOException {
super(secretKeyHex.getBytes(), HMAC_SHA_256);
this.clientId = clientId;
this.apiKey = apiKeyHex.getBytes();
}
public static LoyalbitDigest createInstance(String secretKeyBase64, String clientId, String apiKey) {
try {
return secretKeyBase64 == null ? null : new LoyalbitDigest(secretKeyBase64, clientId, apiKey);
} catch (IOException e) {
throw new IllegalArgumentException("Error parsing API key or secret", e);
}
}
@Override
public String digestParams(RestInvocation restInvocation) {
Mac mac256 = getMac();
mac256.update(restInvocation.getInvocationUrl().getBytes());
mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
mac256.update(clientId.getBytes());
mac256.update(apiKey);
return Base64.encodeBytes(mac256.doFinal());
}
} | 31.333333 | 103 | 0.75076 |
52b485c99dd030748b6e8676caeb180148ccbebb | 758 | package org.bouncycastle.openpgp.operator;
import org.bouncycastle.openpgp.PGPException;
public abstract class PGPSecretKeyDecryptorWithAAD
extends PBESecretKeyDecryptor
{
public PGPSecretKeyDecryptorWithAAD(char[] passPhrase, PGPDigestCalculatorProvider calculatorProvider)
{
super(passPhrase, calculatorProvider);
}
@Override
public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
throws PGPException
{
return recoverKeyData(encAlgorithm, key, iv, null, keyData, keyOff, keyLen);
}
public abstract byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] aad, byte[] keyData, int keyOff, int keyLen) throws PGPException;
}
| 32.956522 | 155 | 0.737467 |
be3f97584785fa7403308413f6fe5b6f594e739b | 1,392 | /*
* GlobalMilesECommerceAPILib
*
* This file was automatically generated for Global Miles by APIMATIC v2.0 ( https://apimatic.io ).
*/
package com.globalmiles.api.ecommerce.models;
import java.util.*;
public class StartMilePaymentRequestBuilder {
//the instance to build
private StartMilePaymentRequest startMilePaymentRequest;
/**
* Default constructor to initialize the instance
*/
public StartMilePaymentRequestBuilder() {
startMilePaymentRequest = new StartMilePaymentRequest();
}
/**
* An identifier for online store.
*/
public StartMilePaymentRequestBuilder storeCode(String storeCode) {
startMilePaymentRequest.setStoreCode(storeCode);
return this;
}
/**
* A token that is representing a Global Miles user for the current session.
*/
public StartMilePaymentRequestBuilder userToken(String userToken) {
startMilePaymentRequest.setUserToken(userToken);
return this;
}
/**
* An amount of payment.
*/
public StartMilePaymentRequestBuilder amount(Amount amount) {
startMilePaymentRequest.setAmount(amount);
return this;
}
/**
* Build the instance with the given values
*/
public StartMilePaymentRequest build() {
return startMilePaymentRequest;
}
} | 27.84 | 100 | 0.662356 |
8b7bfe8f5cff10aca48c551c60f7d977afd5b1bb | 367 | package me.gigawartrex.smalladditions.exceptions;
/**
* Exception for when no filename was specified.
*
* @author Paul Ferlitz
*/
public class NoFileNameException extends Exception
{
/**
* Class constructor.
*/
public NoFileNameException()
{
super("NO specific FILENAME declared! Can't access any files.");
}
}
| 20.388889 | 73 | 0.640327 |
69056273740e54815200a07ef9f701b3cde28bb2 | 4,274 | package com.NowakArtur97.WorldOfManga.feature.user;
import com.NowakArtur97.WorldOfManga.feature.manga.inUserList.MangaInUserListStatus;
import com.NowakArtur97.WorldOfManga.feature.manga.details.Manga;
import com.NowakArtur97.WorldOfManga.feature.manga.inUserList.MangaInUserList;
import com.NowakArtur97.WorldOfManga.feature.manga.rating.MangaRating;
import lombok.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "user", schema = "world_of_manga")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
@Setter(value = AccessLevel.PRIVATE)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "is_enabled")
private boolean isEnabled;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
@JoinTable(name = "user_role", schema = "world_of_manga", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private final Set<Role> roles = new HashSet<>();
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@ToString.Exclude
private final Set<MangaRating> mangasRatings = new HashSet<>();
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@ToString.Exclude
private final Set<MangaInUserList> mangaList = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH})
@JoinTable(name = "favourite_manga", schema = "world_of_manga", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "manga_id"))
@ToString.Exclude
private final Set<Manga> favouriteMangas = new HashSet<>();
void addRole(Role role) {
this.getRoles().add(role);
}
public MangaRating addMangaRating(Manga manga, int rating) {
MangaRating mangaRating = new MangaRating(manga, this, rating);
this.getMangasRatings().add(mangaRating);
manga.getMangasRatings().add(mangaRating);
return mangaRating;
}
public Manga addMangaToFavourites(Manga manga) {
this.getFavouriteMangas().add(manga);
manga.getUserWithMangaInFavourites().add(this);
return manga;
}
public void removeMangaFromFavourites(Manga manga) {
this.getFavouriteMangas().remove(manga);
manga.getUserWithMangaInFavourites().remove(this);
}
public MangaInUserList addMangaToList(Manga manga, MangaInUserListStatus status) {
MangaInUserList mangaInList = new MangaInUserList(manga, this, status);
this.getMangaList().add(mangaInList);
manga.getUsersWithMangaInList().add(mangaInList);
return mangaInList;
}
public void removeMangaFromList(MangaInUserList manga) {
this.getMangaList().remove(manga);
manga.setUser(null);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return isEnabled() == user.isEnabled() &&
Objects.equals(getId(), user.getId()) &&
Objects.equals(getUsername(), user.getUsername()) &&
Objects.equals(getPassword(), user.getPassword()) &&
Objects.equals(getEmail(), user.getEmail()) &&
Objects.equals(getFirstName(), user.getFirstName()) &&
Objects.equals(getLastName(), user.getLastName());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getUsername(), getPassword(), getEmail(), getFirstName(), getLastName(), isEnabled());
}
}
| 31.426471 | 123 | 0.677819 |
8b62f2303400fe751ac8d082b7cebd69bda6319f | 357 | /*
* @lc app=leetcode.cn id=1470 lang=java
*
* [1470] 重新排列数组
*/
// @lc code=start
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] arr = new int[n + n];
for (int i = 0; i < n; i++) {
arr[i + i] = nums[i];
arr[i + i + 1] = nums[n + i];
}
return arr;
}
}
// @lc code=end
| 16.227273 | 45 | 0.434174 |
41e9dd03d2f746820dfc907841f7818ff2f70b08 | 897 | package poussecafe.runtime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import poussecafe.exception.PousseCafeException;
public class Configuration {
private Map<String, Object> values = new HashMap<>();
void add(String key,
Object value) {
if(values.containsKey(key)) {
throw new PousseCafeException("Key " + key + " has already a value");
}
if(value == null) {
throw new PousseCafeException("Value cannot be null");
}
values.put(key, value);
}
@SuppressWarnings("unchecked")
public <T> Optional<T> value(String key) {
return Optional.ofNullable((T) values.get(key));
}
public void addAll(Map<String, Object> configuration) {
for(var entry : configuration.entrySet()) {
add(entry.getKey(), entry.getValue());
}
}
}
| 26.382353 | 81 | 0.618729 |
3d3040c506e35f7c52149615ea5c5febf282ad18 | 10,160 | package com.kobylynskyi.graphql.codegen.kotlin;
import com.kobylynskyi.graphql.codegen.TestUtils;
import com.kobylynskyi.graphql.codegen.model.GeneratedLanguage;
import com.kobylynskyi.graphql.codegen.model.MappingConfig;
import com.kobylynskyi.graphql.codegen.utils.Utils;
import org.hamcrest.core.StringContains;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;
import static com.kobylynskyi.graphql.codegen.TestUtils.assertSameTrimmedContent;
import static com.kobylynskyi.graphql.codegen.TestUtils.getFileByName;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
class GraphQLCodegenGitHubTest {
private final File outputBuildDir = new File("build/generated");
private final File outputktClassesDir = new File("build/generated/com/github/graphql");
private final MappingConfig mappingConfig = new MappingConfig();
private static String getFileContent(File[] files, String fileName) throws IOException {
return Utils.getFileContent(getFileByName(files, fileName).getPath());
}
@BeforeEach
void init() {
mappingConfig.setGenerateParameterizedFieldsResolvers(false);
mappingConfig.setPackageName("com.github.graphql");
mappingConfig.setGeneratedLanguage(GeneratedLanguage.KOTLIN);
mappingConfig.setGenerateToString(true);
mappingConfig.setGenerateApis(true);
mappingConfig.setGenerateClient(true);
mappingConfig.setGenerateEqualsAndHashCode(true);
}
@AfterEach
void cleanup() {
Utils.deleteDir(outputBuildDir);
}
@Test
void generate_MultipleInterfacesPerType() throws Exception {
mappingConfig.putCustomTypeMappingIfAbsent("Int!", "Int");
mappingConfig.putCustomTypeMappingIfAbsent("Boolean!", "Boolean");
mappingConfig.setUseOptionalForNullableReturnTypes(true);
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/Commit.kt.txt"),
getFileByName(files, "Commit.kt"));
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/ProfileOwner.kt.txt"),
getFileByName(files, "ProfileOwner.kt"));
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/AcceptTopicSuggestionMutationResponse.kt.txt"),
getFileByName(files, "AcceptTopicSuggestionMutationResponse.kt"));
}
@Test
void generate_ClassNameWithSuffix_Prefix() throws Exception {
mappingConfig.setModelNamePrefix("Github");
mappingConfig.setModelNameSuffix("TO");
mappingConfig.setGenerateImmutableModels(false);
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
// verify proper class name for GraphQL interface
assertThat(getFileContent(files, "GithubActorTO.kt"),
StringContains.containsString("interface GithubActorTO"));
// verify proper class name for GraphQL enum
assertThat(getFileContent(files, "GithubIssueStateTO.kt"),
StringContains.containsString("enum class GithubIssueStateTO"));
// verify proper class name for GraphQL union
assertThat(getFileContent(files, "GithubAssigneeTO.kt"),
StringContains.containsString("interface GithubAssigneeTO"));
// verify proper class name for GraphQL input
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/GithubAcceptTopicSuggestionInputTO.kt.txt"),
getFileByName(files, "GithubAcceptTopicSuggestionInputTO.kt"));
// verify proper class name for GraphQL type and references to interfaces/types/unions for GraphQL type
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/GithubCommitTO.kt.txt"),
getFileByName(files, "GithubCommitTO.kt"));
}
@Test
void generate_Client_ConditionalFragments() throws Exception {
mappingConfig.setGenerateClient(true);
mappingConfig.setGenerateApis(false);
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/SearchResultItemConnectionResponseProjection.kt.txt"),
getFileByName(files, "SearchResultItemConnectionResponseProjection.kt"));
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/SearchResultItemResponseProjection.kt.txt"),
getFileByName(files, "SearchResultItemResponseProjection.kt"));
}
@Test
void generate_ResponseWithPrimitiveType() throws Exception {
mappingConfig.putCustomTypeMappingIfAbsent("Int!", "Int");
mappingConfig.putCustomTypeMappingIfAbsent("Int", "Int?");
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/primitive-query-response-type.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/VersionQueryResponse_int.kt.txt"),
getFileByName(files, "VersionQueryResponse.kt"));
}
@Test
void generate_ktList() throws Exception {
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/AddLabelsToLabelableInput.kt.txt"),
getFileByName(files, "AddLabelsToLabelableInput.kt"));
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/AddLabelsToLabelableMutationRequest.kt.txt"),
getFileByName(files, "AddLabelsToLabelableMutationRequest.kt"));
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/AddLabelsToLabelableMutationResolver.kt.txt"),
getFileByName(files, "AddLabelsToLabelableMutationResolver.kt"));
assertSameTrimmedContent(
new File("src/test/resources/expected-classes/kt/AddLabelsToLabelableMutationResponse.kt.txt"),
getFileByName(files, "AddLabelsToLabelableMutationResponse.kt"));
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/AddLabelsToLabelablePayload.kt.txt"),
getFileByName(files, "AddLabelsToLabelablePayload.kt"));
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/CodesOfConductQueryResolver.kt.txt"),
getFileByName(files, "CodesOfConductQueryResolver.kt"));
}
@Test
void generate_Var_Field() throws Exception {
mappingConfig.setGenerateImmutableModels(false);
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/Commit_Var_Field.kt.txt"),
getFileByName(files, "Commit.kt"));
}
@Test
void generate_CustomFieldsResolvers() throws Exception {
mappingConfig.setModelNamePrefix("Github");
mappingConfig.setModelNameSuffix("TO");
mappingConfig.setGenerateDataFetchingEnvironmentArgumentInApis(true);
mappingConfig.setFieldsWithResolvers(Collections.singleton("AcceptTopicSuggestionPayload.topic"));
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/github.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File(
"src/test/resources/expected-classes/kt/field-resolver/" +
"GithubAcceptTopicSuggestionPayloadTO.kt.txt"),
getFileByName(files, "GithubAcceptTopicSuggestionPayloadTO.kt"));
assertSameTrimmedContent(new File(
"src/test/resources/expected-classes/kt/field-resolver/" +
"AcceptTopicSuggestionPayloadResolver.kt.txt"),
getFileByName(files, "AcceptTopicSuggestionPayloadResolver.kt"));
}
@Test
void generate_RequestWithDefaultValue() throws Exception {
mappingConfig.setGenerateBuilder(true);
mappingConfig.setGenerateClient(true);
new KotlinGraphQLCodegen(singletonList("src/test/resources/schemas/kt/default.graphqls"),
outputBuildDir, mappingConfig, TestUtils.getStaticGeneratedInfo()).generate();
File[] files = Objects.requireNonNull(outputktClassesDir.listFiles());
assertSameTrimmedContent(new File("src/test/resources/expected-classes/kt/default/" +
"FriendsQueryRequest.kt.txt"),
getFileByName(files, "FriendsQueryRequest.kt"));
}
} | 50.049261 | 119 | 0.718799 |
1e95f5ff66faf9739f50a8e2772559a995ec9ece | 4,656 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2004, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------
* ScatterPlotDemo2.java
* ---------------------
* (C) Copyright 2002-2004, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: ScatterPlotDemo2.java,v 1.11 2004/04/26 19:12:03 taqua Exp $
*
* Changes
* -------
* 14-Oct-2002 : Version 1 (DG);
*
*/
package org.jfree.chart.demo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYDotRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
/**
* A demo scatter plot.
*
*/
public class ScatterPlotDemo2 extends ApplicationFrame {
/**
* A demonstration application showing a scatter plot.
*
* @param title the frame title.
*/
public ScatterPlotDemo2(final String title) {
super(title);
final XYDataset dataset = new SampleXYDataset2();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
chartPanel.setVerticalAxisTrace(true);
chartPanel.setHorizontalAxisTrace(true);
// chartPanel.setVerticalZoom(true);
// chartPanel.setHorizontalZoom(true);
setContentPane(chartPanel);
}
// ****************************************************************************
// * JFREECHART DEVELOPER GUIDE *
// * The JFreeChart Developer Guide, written by David Gilbert, is available *
// * to purchase from Object Refinery Limited: *
// * *
// * http://www.object-refinery.com/jfreechart/guide.html *
// * *
// * Sales are used to provide funding for the JFreeChart project - please *
// * support us so that we can continue developing free software. *
// ****************************************************************************
/**
* Creates a chart.
*
* @param dataset the dataset.
*
* @return The chart.
*/
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart chart = ChartFactory.createScatterPlot(
"Scatter Plot Demo",
"X", "Y", dataset,
PlotOrientation.HORIZONTAL,
true, // legend
false, // tooltips
false // urls
);
final XYPlot plot = chart.getXYPlot();
plot.setRenderer(new XYDotRenderer());
final NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
domainAxis.setAutoRangeIncludesZero(false);
return chart;
}
/**
* Starting point for the demonstration application.
*
* @param args ignored.
*/
public static void main(final String[] args) {
final ScatterPlotDemo2 demo = new ScatterPlotDemo2("Scatter Plot Demo 2");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
| 36.375 | 92 | 0.588918 |
8b10632f8637ed131c3a7ba9f6b0e846e19d5740 | 7,390 | /*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.engine;
import com.google.common.collect.ImmutableList;
import io.confluent.ksql.KsqlExecutionContext;
import io.confluent.ksql.ddl.commands.DdlCommandExec;
import io.confluent.ksql.function.FunctionRegistry;
import io.confluent.ksql.internal.KsqlEngineMetrics;
import io.confluent.ksql.logging.processing.ProcessingLogContext;
import io.confluent.ksql.metastore.MetaStore;
import io.confluent.ksql.metastore.MetaStoreImpl;
import io.confluent.ksql.metastore.MutableMetaStore;
import io.confluent.ksql.metrics.StreamsErrorCollector;
import io.confluent.ksql.parser.KsqlParser.ParsedStatement;
import io.confluent.ksql.parser.KsqlParser.PreparedStatement;
import io.confluent.ksql.parser.tree.ExecutableDdlStatement;
import io.confluent.ksql.parser.tree.Query;
import io.confluent.ksql.parser.tree.QueryContainer;
import io.confluent.ksql.query.QueryId;
import io.confluent.ksql.schema.registry.SchemaRegistryUtil;
import io.confluent.ksql.services.ServiceContext;
import io.confluent.ksql.util.KsqlConfig;
import io.confluent.ksql.util.PersistentQueryMetadata;
import io.confluent.ksql.util.QueryIdGenerator;
import io.confluent.ksql.util.QueryMetadata;
import java.io.Closeable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KsqlEngine implements KsqlExecutionContext, Closeable {
private static final Logger log = LoggerFactory.getLogger(KsqlEngine.class);
private final AtomicBoolean acceptingStatements = new AtomicBoolean(true);
private final Set<QueryMetadata> allLiveQueries = ConcurrentHashMap.newKeySet();
private final KsqlEngineMetrics engineMetrics;
private final ScheduledExecutorService aggregateMetricsCollector;
private final String serviceId;
private final ServiceContext serviceContext;
private final EngineContext primaryContext;
public KsqlEngine(
final ServiceContext serviceContext,
final ProcessingLogContext processingLogContext,
final FunctionRegistry functionRegistry,
final String serviceId
) {
this(
serviceContext,
processingLogContext,
serviceId,
new MetaStoreImpl(functionRegistry),
KsqlEngineMetrics::new);
}
KsqlEngine(
final ServiceContext serviceContext,
final ProcessingLogContext processingLogContext,
final String serviceId,
final MutableMetaStore metaStore,
final Function<KsqlEngine, KsqlEngineMetrics> engineMetricsFactory
) {
this.primaryContext = EngineContext.create(
serviceContext,
processingLogContext,
metaStore,
new QueryIdGenerator(),
this::unregisterQuery);
this.serviceContext = Objects.requireNonNull(serviceContext, "serviceContext");
this.serviceId = Objects.requireNonNull(serviceId, "serviceId");
this.engineMetrics = engineMetricsFactory.apply(this);
this.aggregateMetricsCollector = Executors.newSingleThreadScheduledExecutor();
this.aggregateMetricsCollector.scheduleAtFixedRate(
() -> {
try {
this.engineMetrics.updateMetrics();
} catch (final Exception e) {
log.info("Error updating engine metrics", e);
}
},
1000,
1000,
TimeUnit.MILLISECONDS
);
}
public int numberOfLiveQueries() {
return allLiveQueries.size();
}
@Override
public Optional<PersistentQueryMetadata> getPersistentQuery(final QueryId queryId) {
return primaryContext.getPersistentQuery(queryId);
}
public List<PersistentQueryMetadata> getPersistentQueries() {
return ImmutableList.copyOf(primaryContext.getPersistentQueries().values());
}
public boolean hasActiveQueries() {
return !primaryContext.getPersistentQueries().isEmpty();
}
@Override
public MetaStore getMetaStore() {
return primaryContext.getMetaStore();
}
public DdlCommandExec getDdlCommandExec() {
return primaryContext.getDdlCommandExec();
}
public String getServiceId() {
return serviceId;
}
public void stopAcceptingStatements() {
acceptingStatements.set(false);
}
public boolean isAcceptingStatements() {
return acceptingStatements.get();
}
@Override
public KsqlExecutionContext createSandbox() {
return new SandboxedExecutionContext(primaryContext);
}
@Override
public List<ParsedStatement> parse(final String sql) {
return primaryContext.parse(sql);
}
@Override
public PreparedStatement<?> prepare(final ParsedStatement stmt) {
return primaryContext.prepare(stmt);
}
@Override
public ExecuteResult execute(
final PreparedStatement<?> statement,
final KsqlConfig ksqlConfig,
final Map<String, Object> overriddenProperties
) {
final ExecuteResult result = EngineExecutor
.create(primaryContext, ksqlConfig, overriddenProperties)
.execute(statement);
result.getQuery().ifPresent(this::registerQuery);
return result;
}
@Override
public void close() {
allLiveQueries.forEach(QueryMetadata::close);
engineMetrics.close();
aggregateMetricsCollector.shutdown();
}
/**
* Determines if a statement is executable by the engine.
*
* @param statement the statement to test.
* @return {@code true} if the engine can execute the statement, {@code false} otherwise
*/
public static boolean isExecutableStatement(final PreparedStatement<?> statement) {
return statement.getStatement() instanceof ExecutableDdlStatement
|| statement.getStatement() instanceof QueryContainer
|| statement.getStatement() instanceof Query;
}
private void registerQuery(final QueryMetadata query) {
allLiveQueries.add(query);
engineMetrics.registerQuery(query);
}
private void unregisterQuery(final QueryMetadata query) {
final String applicationId = query.getQueryApplicationId();
if (!query.getState().equalsIgnoreCase("NOT_RUNNING")) {
throw new IllegalStateException("query not stopped."
+ " id " + applicationId + ", state: " + query.getState());
}
if (!allLiveQueries.remove(query)) {
return;
}
if (query.hasEverBeenStarted()) {
SchemaRegistryUtil
.cleanUpInternalTopicAvroSchemas(applicationId, serviceContext.getSchemaRegistryClient());
serviceContext.getTopicClient().deleteInternalTopics(applicationId);
}
StreamsErrorCollector.notifyApplicationClose(applicationId);
}
}
| 32.844444 | 100 | 0.752503 |
067371882bcd9831dd343a1527f17631107f2fd4 | 3,575 | package org.ovirt.engine.core.utils.kerberos;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/*
* Exception during configure domains. If this exception occurred its probably because
* DB errors. This class define handling of configure exceptions
*/
public class ManageDomainsResult extends Exception {
private static final long serialVersionUID = -2897637328396868452L;
private ManageDomainsResultEnum enumResult;
private int exitCode;
private String detailedMessage;
private final static Logger log = Logger.getLogger(ManageDomainsResult.class);
/**
* This constructor is present exception without additional params. we use this one without additional info, only
* enum result type with default detailed massage.
* @param enumResult
* - enum result type
*/
public ManageDomainsResult(ManageDomainsResultEnum enumResult) {
this.exitCode = enumResult.getExitCode();
this.detailedMessage = enumResult.getDetailedMessage();
this.enumResult = enumResult;
}
/**
* This constructor gets params for enum result and defaultMsg for a case that params are wrong or include
* misleading variables (like empty string)
* @param enumResult
* - the error to publish
* @param defaultMsg
* - default output when error found in input.
* @param params
* - enumResult additional params
*/
public ManageDomainsResult(String defaultMsg, ManageDomainsResultEnum enumResult, String... params) {
this.exitCode = enumResult.getExitCode();
this.enumResult = enumResult;
boolean validParams = true;
// setting detailed message
// check params validation
if (params.length == 0) {
log.debug("Wrong exception's params recevied.");
validParams = false;
}
else {
// Verify parameters value
for (String param : params) {
if (StringUtils.isEmpty(param)) {
log.debug("Got null value.");
validParams = false;
}
}
}
// if all ok. we have params verified
if (validParams) {
this.detailedMessage = String.format(enumResult.getDetailedMessage(), params);
}
else {
if (StringUtils.isEmpty(defaultMsg)) {
this.detailedMessage = enumResult.getDetailedMessage() +
": One of the parameters for this error is null and no default message to show";
}
else {
this.detailedMessage = defaultMsg;
}
}
}
public ManageDomainsResult(ManageDomainsResultEnum enumResult, String... params) {
this("", enumResult, params);
}
public int getExitCode() {
return exitCode;
}
public void setExitCode(int exitCode) {
this.exitCode = exitCode;
}
public String getDetailedMessage() {
return detailedMessage;
}
public String getMessage() {
return detailedMessage;
}
public void setDetailedMessage(String detailedMessage) {
this.detailedMessage = detailedMessage;
}
public ManageDomainsResultEnum getEnumResult() {
return enumResult;
}
public void setEnumResult(ManageDomainsResultEnum enumResult) {
this.enumResult = enumResult;
}
public boolean isSuccessful() {
return enumResult == ManageDomainsResultEnum.OK;
}
}
| 32.207207 | 117 | 0.632727 |
6be785bba0ac419b076683160a260d7b1609ecad | 7,221 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.saga.omega.connector.grpc.tcc;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.Lists;
import io.grpc.ManagedChannel;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.testing.GrpcCleanupRule;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.servicecomb.saga.omega.connector.grpc.AlphaClusterConfig;
import org.apache.servicecomb.saga.omega.connector.grpc.core.LoadBalanceContext;
import org.apache.servicecomb.saga.omega.connector.grpc.core.LoadBalanceContextBuilder;
import org.apache.servicecomb.saga.omega.connector.grpc.core.TransactionType;
import org.apache.servicecomb.saga.omega.context.ServiceConfig;
import org.apache.servicecomb.saga.omega.transaction.SagaMessageSender;
import org.apache.servicecomb.saga.omega.transaction.tcc.CoordinateMessageHandler;
import org.apache.servicecomb.saga.omega.transaction.tcc.TccMessageHandler;
import org.apache.servicecomb.saga.omega.transaction.tcc.TccMessageSender;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class LoadBalanceContextBuilderTest {
@Rule
public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
private final AlphaClusterConfig clusterConfig = mock(AlphaClusterConfig.class);
private final TccMessageHandler tccMessageHandler = mock(CoordinateMessageHandler.class);
private final String serverName = uniquify("serviceName");
private final ServiceConfig serviceConfig = new ServiceConfig(serverName);
protected final String[] addresses = {"localhost:8080", "localhost:8090"};
private LoadBalanceContextBuilder tccLoadBalanceContextBuilder;
private LoadBalanceContextBuilder sagaLoadBalanceContextBuilder;
@Before
public void setup() throws IOException {
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder.forName("localhost:8080").directExecutor().build().start());
grpcCleanup.register(InProcessServerBuilder.forName("localhost:8090").directExecutor().build().start());
when(clusterConfig.getAddresses()).thenReturn(Lists.newArrayList(addresses));
when(clusterConfig.getTccMessageHandler()).thenReturn(tccMessageHandler);
tccLoadBalanceContextBuilder =
new LoadBalanceContextBuilder(TransactionType.TCC, clusterConfig, serviceConfig, 30);
sagaLoadBalanceContextBuilder =
new LoadBalanceContextBuilder(TransactionType.SAGA, clusterConfig, serviceConfig, 30);
}
@After
public void teardown() {
}
@Test
public void buildTccLoadBalanceContextWithoutSsl() {
when(clusterConfig.isEnableSSL()).thenReturn(false);
LoadBalanceContext loadContext = tccLoadBalanceContextBuilder.build();
assertThat(loadContext.getPendingTaskRunner().getReconnectDelay(), is(30));
assertThat(loadContext.getSenders().size(), is(2));
assertThat(loadContext.getSenders().keySet().iterator().next(), instanceOf(TccMessageSender.class));
assertThat(loadContext.getSenders().values().iterator().next(), is(0l));
assertThat(loadContext.getChannels().size(), is(2));
loadContext.getSenders().keySet().iterator().next().close();
shutdownChannels(loadContext);
}
@Test
public void buildTccLoadBalanceContextWithSsl() {
when(clusterConfig.isEnableSSL()).thenReturn(true);
when(clusterConfig.getCert()).thenReturn(getClass().getClassLoader().getResource("client.crt").getFile());
when(clusterConfig.getCertChain()).thenReturn(getClass().getClassLoader().getResource("ca.crt").getFile());
when(clusterConfig.getKey()).thenReturn(getClass().getClassLoader().getResource("client.pem").getFile());
LoadBalanceContext loadContext = tccLoadBalanceContextBuilder.build();
assertThat(loadContext.getPendingTaskRunner().getReconnectDelay(), is(30));
assertThat(loadContext.getSenders().size(), is(2));
assertThat(loadContext.getSenders().keySet().iterator().next(), instanceOf(TccMessageSender.class));
assertThat(loadContext.getSenders().values().iterator().next(), is(0l));
assertThat(loadContext.getChannels().size(), is(2));
shutdownChannels(loadContext);
}
@Test(expected = IllegalArgumentException.class)
public void throwExceptionWhenAddressIsNotExist() {
when(clusterConfig.getAddresses()).thenReturn(new ArrayList<String>());
tccLoadBalanceContextBuilder.build();
}
@Test
public void buildSagaLoadBalanceContextWithoutSsl() {
LoadBalanceContext loadContext = sagaLoadBalanceContextBuilder.build();
assertThat(loadContext.getPendingTaskRunner().getReconnectDelay(), is(30));
assertThat(loadContext.getSenders().size(), is(2));
assertThat(loadContext.getSenders().keySet().iterator().next(), instanceOf(SagaMessageSender.class));
assertThat(loadContext.getSenders().values().iterator().next(), is(0l));
assertThat(loadContext.getChannels().size(), is(2));
loadContext.getSenders().keySet().iterator().next().close();
shutdownChannels(loadContext);
}
@Test
public void buildSagaLoadBalanceContextWithSsl() {
when(clusterConfig.isEnableSSL()).thenReturn(true);
when(clusterConfig.getCert()).thenReturn(getClass().getClassLoader().getResource("client.crt").getFile());
when(clusterConfig.getCertChain()).thenReturn(getClass().getClassLoader().getResource("ca.crt").getFile());
when(clusterConfig.getKey()).thenReturn(getClass().getClassLoader().getResource("client.pem").getFile());
LoadBalanceContext loadContext = sagaLoadBalanceContextBuilder.build();
assertThat(loadContext.getPendingTaskRunner().getReconnectDelay(), is(30));
assertThat(loadContext.getSenders().size(), is(2));
assertThat(loadContext.getSenders().keySet().iterator().next(), instanceOf(SagaMessageSender.class));
assertThat(loadContext.getSenders().values().iterator().next(), is(0l));
assertThat(loadContext.getChannels().size(), is(2));
shutdownChannels(loadContext);
}
private void shutdownChannels(LoadBalanceContext loadContext) {
for (ManagedChannel each : loadContext.getChannels()) {
each.shutdownNow();
}
}
}
| 49.458904 | 111 | 0.773993 |
e0f3fcc93d35f200770ff41be9353b80301c13fd | 8,625 | package com.example.soundroid.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.example.soundroid.db.SoundroidContract.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TrackManager {
/** Convenience method for inserting a track into the database.
* @param context of the database helper.
* @param track to be inserted.
* @return false if an error occurred, true otherwise.
*/
private static boolean add(Context context, Track track) {
if (isTrackAlreadyInDb(context, track)) {
return true;
}
SQLiteDatabase db = new SoundroidDbHelper(context).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SoundroidTrack.COLUMN_NAME_HASH, track.getHash());
values.put(SoundroidTrack.COLUMN_NAME_NAME, track.getName());
values.put(SoundroidTrack.COLUMN_NAME_ARTIST, track.getArtist());
values.put(SoundroidTrack.COLUMN_NAME_ALBUM, track.getAlbum());
values.put(SoundroidTrack.COLUMN_NAME_DISK_NUMBER, track.getDiskNumber());
values.put(SoundroidTrack.COLUMN_NAME_TRACK_NUMBER, track.getTrackNumber());
values.put(SoundroidTrack.COLUMN_NAME_BITRATE, track.getBitrate());
values.put(SoundroidTrack.COLUMN_NAME_DATE, track.getDate());
values.put(SoundroidTrack.COLUMN_NAME_MINUTES, track.getMinutes());
values.put(SoundroidTrack.COLUMN_NAME_SECONDS, track.getSeconds());
values.put(SoundroidTrack.COLUMN_NAME_MARK, track.getMark());
values.put(SoundroidTrack.COLUMN_NAME_NUMBEROFCLICKS, track.getNumberOfClick());
values.put(SoundroidTrack.COLUMN_NAME_URI, track.getUri().toString());
return (db.insert(SoundroidTrack.TABLE_NAME, null, values) != -1);
}
/** Convenience method to add tracks into the database.
* @param context of the database helper.
* @param tracks to be inserted.
* @return false if an error occurred, true otherwise.
*/
public static boolean addAll(Context context, List<Track> tracks) {
for (Track track : tracks) {
if (!add(context, track)) {
return false;
}
}
return true;
}
/** Convenience method to get a track from the database by his hash.
* @param context of the database helper.
* @param hash of the asked track.
* @return the asked track or null if it doesn't exist in the database.
*/
public static Track get(Context context, String hash) {
SoundroidDbHelper dbHelper = new SoundroidDbHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = SoundroidContract.SoundroidTrack.getProjection();
String selection = SoundroidTrack.COLUMN_NAME_HASH + " = ?";
String[] selectionArgs = { hash };
Cursor cursor = db.query(SoundroidTrack.TABLE_NAME, projection, selection, selectionArgs,null,null,null);
if (!cursor.moveToNext()) {
return null;
};
Track track = new Track(
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getInt(4),
cursor.getInt(5),
cursor.getInt(6),
cursor.getLong(7),
cursor.getInt(8),
cursor.getInt(9),
Uri.parse(cursor.getString(12)));
cursor.close();
return track;
}
/**
* Test if the track exist in the database
* @param context of the database helper.
* @param track of the track to test.
* @return true if the track already exist, false otherwise.
*/
public static boolean isTrackAlreadyInDb(Context context, Track track) {
return get(context, track.getHash()) != null;
}
/** Get all tracks
* @param context of the database helper.
* @return list of tracks
*/
public static ArrayList<Track> getAll(Context context) {
SQLiteDatabase db = new SoundroidDbHelper(context).getReadableDatabase();
ArrayList<Track> tracks = new ArrayList<>();
String[] projection = SoundroidContract.SoundroidTrack.getProjection();
Cursor cursor = db.query(SoundroidTrack.TABLE_NAME, projection, null, null,null,null,null);
while (cursor.moveToNext()) {
tracks.add(new Track(
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getInt(4),
cursor.getInt(5),
cursor.getInt(6),
cursor.getLong(7),
cursor.getInt(8),
cursor.getInt(9),
Uri.parse(cursor.getString(12))));
}
cursor.close();
return tracks;
}
/** get a list of tracks that check filters in arguments.
* @param context of the database helper.
* @param artist filter, null to not use this filter.
* @param album filter, null to not use this filter.
* @param title filter, null to not use this filter.
* @return list of tracks that check filters in arguments.
*/
public static ArrayList<Tracklistable> get(Context context, String artist, String album, String title) {
SQLiteDatabase db = new SoundroidDbHelper(context).getReadableDatabase();
ArrayList<Tracklistable> tracks = new ArrayList<>();
String[] projection = SoundroidContract.SoundroidTrack.getProjection();
String[] selectionArgs = null;
StringBuilder selectionBuilder = new StringBuilder();
if (artist != null) {
selectionBuilder.append(SoundroidTrack.COLUMN_NAME_ARTIST + " = ? ");
selectionArgs = new String[] { artist };
}
if (album != null) {
selectionBuilder.append(SoundroidTrack.COLUMN_NAME_ALBUM + " = ? ");
selectionArgs = new String[] { album };
}
if (title != null) {
selectionBuilder.append(SoundroidTrack.COLUMN_NAME_NAME + " like ? ");
selectionArgs = new String[] { "%" + title + "%" };
}
Cursor cursor = db.query(SoundroidTrack.TABLE_NAME, projection, selectionBuilder.toString(), selectionArgs,null,null,null);
while (cursor.moveToNext()) {
tracks.add(new Track(
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getInt(4),
cursor.getInt(5),
cursor.getInt(6),
cursor.getLong(7),
cursor.getInt(8),
cursor.getInt(9),
Uri.parse(cursor.getString(12))));
}
cursor.close();
return tracks;
}
/** Return hashes of all track indexed.
* @param context of the database helper.
* @return list of tracks indexed.
*/
public static List<String> getHashes(Context context) {
SQLiteDatabase db = new SoundroidDbHelper(context).getReadableDatabase();
List<String> hashes = new ArrayList<>();
String query = "select " + SoundroidTrack.COLUMN_NAME_HASH + " from " + SoundroidTrack.TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
hashes.add(cursor.getString(0));
}
cursor.close();
return hashes;
}
/** Delete all tracks and all links of the given track prints
* @param context of the database helper.
* @param hashes of the tracks to remove
*/
public static void deleteAll(Context context, List<String> hashes) {
if (hashes.isEmpty()) {
throw new IllegalStateException();
}
SQLiteDatabase db = new SoundroidDbHelper(context).getWritableDatabase();
StringBuilder builder = new StringBuilder();
builder.append("(");
for (String hash : hashes) {
builder.append("'" + hash + "',");
}
builder.deleteCharAt(builder.length() - 1);
builder.append(")");
String predicate = " in " + builder.toString();
db.delete(SoundroidTrack.TABLE_NAME,SoundroidTrack.COLUMN_NAME_HASH + predicate, null);
db.delete(SoundroidTracklistLink.TABLE_NAME, SoundroidTracklistLink.COLUMN_NAME_TRACKLISTABLE_HASH + predicate, null);
}
}
| 41.868932 | 131 | 0.62029 |
ddac37f6c07e67822a62a4a309aad9e62c223714 | 5,354 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.extension.siddhi.io.prometheus.sink.util;
import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.Histogram;
import io.prometheus.client.SimpleCollector;
import io.prometheus.client.SimpleCollector.Builder;
import io.prometheus.client.Summary;
import io.siddhi.core.exception.SiddhiAppCreationException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* {@code PrometheusMetricBuilder } Builds and assigns values for metrics.
*/
public class PrometheusMetricBuilder {
private CollectorRegistry registry;
private String metricName;
private String metricHelp;
private List<String> attributes;
private Collector.Type metricType;
private Collector metricsCollector;
private double[] histogramBuckets = new double[0];
private double[] summaryQuantiles = new double[0];
private double quantileError;
public final CollectorRegistry getRegistry() {
return registry;
}
public PrometheusMetricBuilder(String metricName, String metrichelp,
Collector.Type metricType, List<String> labels) {
this.metricName = metricName;
this.metricHelp = metrichelp;
this.metricType = metricType;
this.attributes = labels;
}
public void setHistogramBuckets(double[] histogramBuckets) {
this.histogramBuckets = histogramBuckets.clone();
}
public void setQuantiles(double[] summaryQuantiles, Double quantileError) {
this.summaryQuantiles = summaryQuantiles.clone();
this.quantileError = quantileError;
}
public void registerMetric(String valueAttribute) {
metricsCollector = buildMetric(valueAttribute).register(registry);
}
private Builder buildMetric(String valueAttribute) {
attributes.remove(valueAttribute);
String[] metricLabels = attributes.toArray(new String[0]);
Builder builder = new Builder() {
@Override
public SimpleCollector create() {
return null;
}
};
switch (metricType) {
case COUNTER: {
builder = Counter.build(metricName, metricHelp);
break;
}
case GAUGE: {
builder = Gauge.build(metricName, metricHelp);
break;
}
case HISTOGRAM: {
builder = Histogram.build(metricName, metricHelp);
break;
}
case SUMMARY: {
builder = Summary.build(metricName, metricHelp);
break;
}
default: //default will never be executed
}
builder.labelNames(metricLabels);
if (metricType == Collector.Type.HISTOGRAM) {
if (!(histogramBuckets.length == 0)) {
((Histogram.Builder) builder).buckets(histogramBuckets);
}
}
if (metricType == Collector.Type.SUMMARY) {
if (!(summaryQuantiles.length == 0)) {
for (double summaryQuantile : summaryQuantiles) {
((Summary.Builder) builder).quantile(summaryQuantile, quantileError);
}
}
}
return builder;
}
//update values for metric labels
public void insertValues(double value, String[] labelValues) {
switch (metricType) {
case COUNTER: {
((Counter) metricsCollector).labels(labelValues).inc(value);
break;
}
case GAUGE: {
((Gauge) metricsCollector).labels(labelValues).inc(value);
break;
}
case HISTOGRAM: {
((Histogram) metricsCollector).labels(labelValues).observe(value);
break;
}
case SUMMARY: {
((Summary) metricsCollector).labels(labelValues).observe(value);
break;
}
default: //default will never be executed
}
}
public CollectorRegistry setRegistry(String url, String streamID) {
URL target;
try {
target = new URL(url);
registry = PrometheusRegistryHolder.retrieveRegistry(target.getHost(), target.getPort());
} catch (MalformedURLException e) {
throw new SiddhiAppCreationException("Error in the URL format of Prometheus sink associated with stream \'"
+ streamID + "\'. \n ", e);
}
return registry;
}
}
| 34.320513 | 119 | 0.620844 |
aa497b2c9a8758536e29c5aeeda91ad454b6a7d4 | 4,431 | /*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.vpc.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.annotation.Required;
/**
* createElasticIpSpec
*/
public class CreateElasticIpSpec implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 购买弹性ip数量;取值范围:[1,100]
* Required:true
*/
@Required
private Integer maxCount;
/**
* 指定弹性ip地址进行创建,当申请创建多个弹性ip时,必须为空
*/
private String elasticIpAddress;
/**
* 弹性ip规格
* Required:true
*/
@Required
private ElasticIpSpec elasticIpSpec;
/**
* 用户标签
*/
private List<Tag> userTags;
/**
* 弹性ip类型,取值:standard(标准公网IP),edge(边缘公网IP),默认为standard
*/
private String ipType;
/**
* get 购买弹性ip数量;取值范围:[1,100]
*
* @return
*/
public Integer getMaxCount() {
return maxCount;
}
/**
* set 购买弹性ip数量;取值范围:[1,100]
*
* @param maxCount
*/
public void setMaxCount(Integer maxCount) {
this.maxCount = maxCount;
}
/**
* get 指定弹性ip地址进行创建,当申请创建多个弹性ip时,必须为空
*
* @return
*/
public String getElasticIpAddress() {
return elasticIpAddress;
}
/**
* set 指定弹性ip地址进行创建,当申请创建多个弹性ip时,必须为空
*
* @param elasticIpAddress
*/
public void setElasticIpAddress(String elasticIpAddress) {
this.elasticIpAddress = elasticIpAddress;
}
/**
* get 弹性ip规格
*
* @return
*/
public ElasticIpSpec getElasticIpSpec() {
return elasticIpSpec;
}
/**
* set 弹性ip规格
*
* @param elasticIpSpec
*/
public void setElasticIpSpec(ElasticIpSpec elasticIpSpec) {
this.elasticIpSpec = elasticIpSpec;
}
/**
* get 用户标签
*
* @return
*/
public List<Tag> getUserTags() {
return userTags;
}
/**
* set 用户标签
*
* @param userTags
*/
public void setUserTags(List<Tag> userTags) {
this.userTags = userTags;
}
/**
* get 弹性ip类型,取值:standard(标准公网IP),edge(边缘公网IP),默认为standard
*
* @return
*/
public String getIpType() {
return ipType;
}
/**
* set 弹性ip类型,取值:standard(标准公网IP),edge(边缘公网IP),默认为standard
*
* @param ipType
*/
public void setIpType(String ipType) {
this.ipType = ipType;
}
/**
* set 购买弹性ip数量;取值范围:[1,100]
*
* @param maxCount
*/
public CreateElasticIpSpec maxCount(Integer maxCount) {
this.maxCount = maxCount;
return this;
}
/**
* set 指定弹性ip地址进行创建,当申请创建多个弹性ip时,必须为空
*
* @param elasticIpAddress
*/
public CreateElasticIpSpec elasticIpAddress(String elasticIpAddress) {
this.elasticIpAddress = elasticIpAddress;
return this;
}
/**
* set 弹性ip规格
*
* @param elasticIpSpec
*/
public CreateElasticIpSpec elasticIpSpec(ElasticIpSpec elasticIpSpec) {
this.elasticIpSpec = elasticIpSpec;
return this;
}
/**
* set 用户标签
*
* @param userTags
*/
public CreateElasticIpSpec userTags(List<Tag> userTags) {
this.userTags = userTags;
return this;
}
/**
* set 弹性ip类型,取值:standard(标准公网IP),edge(边缘公网IP),默认为standard
*
* @param ipType
*/
public CreateElasticIpSpec ipType(String ipType) {
this.ipType = ipType;
return this;
}
/**
* add item to 用户标签
*
* @param userTag
*/
public void addUserTag(Tag userTag) {
if (this.userTags == null) {
this.userTags = new ArrayList<>();
}
this.userTags.add(userTag);
}
} | 19.959459 | 76 | 0.590612 |
3aa05f7eb6039516b5517b10f3b240a9b500e0df | 5,471 | /*
* Copyright 2015 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.linkedin.featurefu.expr;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingFormatArgumentException;
/**
*
* Unit test for math expression parsing, evaluating and printing
*
* Author: Leo Tang <http://www.linkedin.com/in/lijuntang>
*/
public class ExprTest {
@Test
public void simple() {
Assert.assertTrue(Expression.evaluate("(!= 2 3)") == 1);
Assert.assertTrue(Expression.evaluate("(* 2 3)") == 6);
Assert.assertTrue(Expression.evaluate("(ln1plus 2)") == Math.log(1 + 2));
Assert.assertTrue(Expression.evaluate("(if (>= 4 5) 1 2)") == 2);
Assert.assertTrue(Expression.evaluate("(if (in 3 4 5) 2 1)") == 1);
Assert.assertTrue(Expression.evaluate("(- 1)") == -1);
Assert.assertTrue(Expression.evaluate("(cos 1)") == Math.cos(1));
double r = Expression.evaluate("(rand-in 5 10)");
Assert.assertTrue(r >= 5 && r <= 10);
r = Expression.evaluate("(rand)");
Assert.assertTrue(r >= 0 && r <= 1);
Assert.assertTrue(Expression.evaluate("(+ 0.5 (* (/ 15 1000) (ln (- 55 12))))") == 0.5 + 15.0 / 1000.0 * Math.log(55.0 - 12.0));
//big boss, time to show power
Assert.assertTrue(Expression.evaluate("(* (if (&& (== 0 12) (&& 3 (&& (&& (>= 4 5) (<= 4 6)) (&& (>= 7 5 ) (<= 7 4))))) 0 (if (&& (== 3 0) (<= 55 3)) 0 (if (&& (== 3 0) (|| (|| (&& 2 (&& 3 1) ) 1) (&& 6 3))) 0 (if (<= 55 12) (/ (* 0.5 55) 12)(+ 0.5 (*(/ 15 1000) (ln (- 55 12)))))))) 1000)") == 1000 * (0.5 + 15.0 / 1000.0 * Math.log(55.0 - 12.0)));
}
@Test
public void variables(){
VariableRegistry variableRegistry=new VariableRegistry();
//parse expression with variables, use variableRegistry to register variables
Expr expression = Expression.parse("(sigmoid (+ (* a x) b))", variableRegistry);
//retrieve variables from variableRegistry by name
Variable x = variableRegistry.findVariable("x");
Variable a = variableRegistry.findVariable("a");
Variable b = variableRegistry.findVariable("b");
//set variable values
x.setValue(1);
a.setValue(2);
b.setValue(3);
//evaluate expression with variables' value
Assert.assertTrue(expression.evaluate() == 1.0/(1+Math.exp(-a.getValue() * x.getValue() - b.getValue() )) );
//re-set variable values
x.setValue(4);
Assert.assertTrue(x.getValue()==4);
a.setValue(5);
Assert.assertTrue(a.getValue() == 5);
b.setValue(6);
Assert.assertTrue(b.getValue() == 6);
//re-eval expression without re-parsing
Assert.assertTrue(expression.evaluate() == 1.0/(1+Math.exp(-a.getValue() * x.getValue() - b.getValue() )) );
//another way to re-set variable values, using a <name,value> map
Map<String,Double> varMap = new HashMap<String,Double>();
varMap.put("x",0.2);
varMap.put("a",0.6);
varMap.put("b",0.8);
//call refresh to re-set values all at once
variableRegistry.refresh(varMap);
Assert.assertTrue(x.getValue()==0.2);
Assert.assertTrue(a.getValue()==0.6);
Assert.assertTrue(b.getValue()==0.8);
//re-evaluate expression
Assert.assertTrue(expression.evaluate() == 1.0 / (1 + Math.exp(-a.getValue() * x.getValue() - b.getValue())));
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void operatorNotSupported() {
Expression.evaluate("(atan 1)"); //some triangle functions are not supported due to no foreseeable use cases
}
@Test(expectedExceptions = MissingFormatArgumentException.class)
public void operantNotSupported() {
Expression.evaluate("(+ 1+1)");
}
@Test
public void testPrettyPrint(){
VariableRegistry variableRegistry=new VariableRegistry();
Expr expr = Expression.parse("(+ 0.5 (* (/ 15 1000) (ln (- 55 12))))", variableRegistry);
Assert.assertEquals(expr.toString(), "(0.5+((15.0/1000.0)*ln((55.0-12.0))))");
Assert.assertEquals(Expression.prettyTree(expr), "└── +\n" +
" ├── 0.5\n" +
" └── *\n" +
" ├── /\n" +
" | ├── 15.0\n" +
" | └── 1000.0\n" +
" └── ln\n" +
" └── -\n" +
" ├── 55.0\n" +
" └── 12.0\n");
}
}
| 40.828358 | 357 | 0.528057 |
a8179e7575d8f661a371cc4c5f505b71742aec3b | 892 | package com.revanwang.employee.dao;
import com.revanwang.employee.domain.Employee;
import com.revanwang.employee.query.EmployeeQueryObject;
import com.revanwang.employee.query.PageResult;
import java.util.List;
/**
* 员工信息DAO接口
*/
public interface IEmployeeDAO {
/**
* 保存员工信息
* @param e 新增员工
*/
void save(Employee e);
/**
* 删除员工
* @param e 被删除员工
*/
void delete(Employee e);
/**
* 编辑员工信息
* @param e 编辑员工信息
*/
void update(Employee e);
/**
* @param e 获取员工信息
* @return 查询的员工
*/
Employee get(Employee e);
/**
* @return 所有员工信息
*/
List<Employee> getList();
/**
* @param qo 查询条件对象
* @return 所有员工信息
*/
List<Employee> query(EmployeeQueryObject qo);
/**
* @param qo 查询条件对象
* @return
*/
PageResult pageQuery(EmployeeQueryObject qo);
}
| 16.218182 | 56 | 0.577354 |
9baec7acb8ed31537e5d07538f5aca16438396d9 | 2,215 | package com.lagou.gateway.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component //自动实例化并被Spring IOC容器管理
//全局过滤器必须实现两个接口:GlobalFilter、Ordered
//GlobalFilter是全局过滤器接口,实现类要实现filter()方法进行功能扩展
//Ordered接口用于排序,通过实现getOrder()方法返回整数代表执行当前过滤器的前后顺序
public class ElapsedFilter implements GlobalFilter, Ordered {
//基于slf4j.Logger实现日志输出
private static final Logger logger = LoggerFactory.getLogger(ElapsedFilter.class);
//起始时间属性名
private static final String ELAPSED_TIME_BEGIN = "elapsedTimeBegin";
/**
* 实现filter()方法记录处理时间
*
* @param exchange 用于获取与当前请求、响应相关的数据,以及设置过滤器间传递的上下文数据
* @param chain Gateway过滤器链对象
* @return Mono对应一个异步任务,因为Gateway是基于Netty Server异步处理的,Mono对就代表异步处理完毕的情况。
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//Pre前置处理部分
//在请求到达时,往ServerWebExchange上下文环境中放入了一个属性elapsedTimeBegin,保存请求执行前的时间戳
exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
//chain.filter(exchange).then()对应Post后置处理部分
//当响应产生后,记录结束与elapsedTimeBegin起始时间比对,获取RESTful API的实际执行时间
return chain.filter(exchange).then(
Mono.fromRunnable(() -> { //当前过滤器得到响应时,计算并打印时间
Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
if (startTime != null) {
logger.info(exchange.getRequest().getRemoteAddress() //远程访问的用户地址
+ " | " + exchange.getRequest().getPath() //Gateway URI
+ " | cost " + (System.currentTimeMillis() - startTime) + "ms"); //处理时间
}
})
);
}
//设置为最高优先级,最先执行ElapsedFilter过滤器
//return Ordered.LOWEST_PRECEDENCE; 代表设置为最低优先级
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
| 38.859649 | 103 | 0.690745 |
31d2bed20bd9f05e4748b11181da581015da53e1 | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:3732eebaa52f83c2fd8faba4413d78d221215eacb9e4f28b3120d97e5d560e1a
size 2534
| 32.25 | 75 | 0.883721 |
5bb02cc55edba0d69131829e1ca9fd5cbf017118 | 1,461 | package seedu.address.logic.parser.vendor;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_VENDOR_ID;
import seedu.address.logic.commands.vendor.DeleteVendorCommand;
import seedu.address.logic.parser.ArgumentMultimap;
import seedu.address.logic.parser.ArgumentTokenizer;
import seedu.address.logic.parser.Parser;
import seedu.address.logic.parser.ParserUtil;
import seedu.address.logic.parser.exceptions.ParseException;
// @author NicolasCwy
public class DeleteVendorCommandParser implements Parser<DeleteVendorCommand> {
/**
* Parses the given {@code String} of arguments in the context of the DeleteVendorCommand
* and returns an DeleteVendorCommand object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public DeleteVendorCommand parse(String args) throws ParseException {
requireNonNull(args);
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_VENDOR_ID);
if (argMultimap.getValue(PREFIX_VENDOR_ID).isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteVendorCommand.MESSAGE_USAGE));
}
return new DeleteVendorCommand(ParserUtil.parseVendorId(argMultimap.getValue(PREFIX_VENDOR_ID).get()));
}
}
| 39.486486 | 119 | 0.776865 |
700aa1595092cf2767ac66b0d0b3e5d94327d4d8 | 1,253 | package com.koch.ambeth.example.conversionHelper;
/*-
* #%L
* jambeth-examples
* %%
* Copyright (C) 2017 Koch Softwaredevelopment
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* #L%
*/
import java.util.Calendar;
import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.log.ILogger;
import com.koch.ambeth.log.LogInstance;
import com.koch.ambeth.util.IConversionHelper;
public class ConversionHelperExample {
@LogInstance
private ILogger log;
@Autowired
protected IConversionHelper conversionHelper;
public void logCalendar(Calendar calendar) {
if (log.isInfoEnabled()) {
String stringValue = conversionHelper.convertValueToType(String.class, calendar);
log.info(stringValue); // log ISO8601-formatted calendar value
}
}
}
| 28.477273 | 84 | 0.77095 |
39a21a6d497c0b73130596f7aa459bcaeeca5352 | 1,690 | package ua.kiev.icyb.bio.filters;
import java.io.Serializable;
import ua.kiev.icyb.bio.Sequence;
import ua.kiev.icyb.bio.StatesDescription;
import ua.kiev.icyb.bio.Transform;
import ua.kiev.icyb.bio.res.Messages;
/**
* Композиция из нескольких преобразований.
*/
public class TransformComposition implements Transform, Serializable {
private static final long serialVersionUID = 1L;
private final Transform[] transforms;
/**
* Создает композицию. Преобразования применяются в указанном порядке;
* при поиске обратной последовательности - в обратном порядке.
*
* @param transforms
* последовательность преобразований
*/
public TransformComposition(Transform... transforms) {
this.transforms = transforms;
}
@Override
public StatesDescription states(StatesDescription original) {
StatesDescription states = original;
for (Transform t : this.transforms) {
states = t.states(states);
}
return states;
}
@Override
public Sequence sequence(Sequence original) {
Sequence seq = original;
for (Transform t : this.transforms) {
seq = t.sequence(seq);
}
return seq;
}
@Override
public Sequence inverse(Sequence transformed) {
Sequence seq = transformed;
for (int i = this.transforms.length - 1; i >= 0; i--) {
seq = this.transforms[i].inverse(seq);
}
return seq;
}
@Override
public String repr() {
String repr = Messages.getString("transform.comp") + "\n";
String list = "";
for (int i = 0; i < transforms.length; i++) {
if (i > 0) list += "\n";
list += Messages.format("transform.comp.part", i + 1, transforms[i].repr());
}
repr += Messages.format("transform.comp.parts", list);
return repr;
}
}
| 24.142857 | 79 | 0.700592 |
b2f841c7484cc157619444dc17f622a0cadebbe6 | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:e01d606778c3d407e2ad1f1bcf34f8266a3b16dec75151b026bdb99f93f0296b
size 14961
| 32.5 | 75 | 0.884615 |
5e2914d08b5595d4db254a88c0996ca495b8790a | 211 | package sonar.core.client.gui;
public interface IGuiOrigin {
void setOrigin(Object origin);
static <T extends IGuiOrigin> T withOrigin(T gui, Object origin) {
gui.setOrigin(origin);
return gui;
}
}
| 16.230769 | 67 | 0.725118 |
fa275d134f9cb7dbfe74ed19fa8ea8931aa715fb | 1,494 | package com.smart.canteen.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* <p>
* 组织
* </p>
*
* @author lc
* @since 2020-03-11
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("permission")
@ApiModel(value = "Permission对象", description = "权限")
public class Permission implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键Id")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "名称")
@TableField("name")
private String name;
@ApiModelProperty(value = "上级id")
@TableField("parent_id")
private Long parentId;
@ApiModelProperty(value = "编码")
@TableField("code")
private String code;
@ApiModelProperty(value = "路径")
@TableField("path")
private String path;
@ApiModelProperty(value = "级别")
@TableField("level")
private Long level;
@ApiModelProperty(value = "是否拥有子节点")
@TableField("has_children")
private Boolean hasChildren;
}
| 24.096774 | 61 | 0.72423 |
e48b23357bb87eaad8582d4c3c94339f21e75abe | 1,766 | package help.lixin.sharding.resource.controller;
import help.lixin.sharding.resource.entity.Order;
import help.lixin.sharding.resource.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private IOrderService orderService;
/**
* 演示query
*
* @return
*/
@GetMapping("/list")
public List<Map> list() {
List<Long> ids = new ArrayList<>();
ids.add(565585450073325568L);
ids.add(565585450987683840L);
List<Map> maps = orderService.selectOrderbyIds(ids);
return maps;
}
/**
* 演示master插入数据.
*
* @param orderId
* @param userId
* @param price
* @param status
* @return
*/
@PostMapping("/save/{orderId}/{userId}/{price}/{status}")
public String save(@PathVariable("orderId") Long orderId, @PathVariable("userId") Long userId, @PathVariable("price") BigDecimal price, @PathVariable("status") String status) {
boolean save = orderService.save(orderId, userId, price, status);
return "SUCCESS";
}
@PostMapping("/save2")
public String save() {
Long orderId = 500L;
Long userId = 1000L;
BigDecimal price = new BigDecimal("100");
String status = "SUCCESS";
Order order = new Order();
order.setOrderId(orderId);
order.setUserId(userId);
order.setPrice(price);
order.setStatus(status);
boolean save = orderService.save(order);
return "SUCCESS";
}
}
| 26.358209 | 180 | 0.644394 |
44a8f979cae424897faef9e332a782d6fc05fa99 | 5,779 | package com.lognull.libnetwork.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;
import com.lognull.libnetwork.consumer.spi.Client;
import com.lognull.libnetwork.exception.ClientException;
import com.lognull.libnetwork.helper.Error;
import com.lognull.libnetwork.helper.LoggerHelper;
import com.lognull.libnetwork.producer.EndpointInfo;
/**
* This class encapsules and provide the communication between client
* and server through the Protocol TELNET, whose provide general,
* bi-directional, eight-bit byte oriented communications.
*
* @author Diogo Pinto <[email protected]>
* @since 1.0
*/
public class Telnet implements Client
{
private static final LoggerHelper LOG = LoggerHelper
.thisClass( Telnet.class );
/** The target IP Address from endpoint */
private String ip = null;
private String username = null;
private String password = null;
/** Default port that can be overwritten */
private int port = 23;
/** Holds data from endpoint */
private String receive = "";
/** Information about endpoint credential */
private EndpointInfo.Credential credential = null;
/** Reads data from endpoint */
private InputStream in = null;
/** Writes on remote endpoint */
private PrintStream out = null;
private TelnetClient telnet = null;
/**
* Constructor default with endpoint entity. This entity represents the
* endpoint whose this client will connect.
*
* @param endpoint
* the endpoint whose this client will connect.
* @throws ClientException
* There least two reasons by which this client might not
* working correctly. One is because the own client introducing
* problem and another is by the fact to occur problems with of
* endpoint target.
*/
public
Telnet( EndpointInfo endpoint ) throws ClientException
{
try
{
this.ip = endpoint.getIp();
this.username = endpoint.getCredential().getUser();
this.password = endpoint.getCredential().getPassword();
if ( endpoint.getPort() != 0 )
this.port = endpoint.getPort();
this.credential = endpoint.getCredential();
telnet = new TelnetClient();
}
catch( Exception e )
{
throw new ClientException( Error.ER_CREATE_SOCKET_CONNECTION + " "
+ this.ip + ":" + this.port, e );
}
}
/**
* @see Client#getIpFromEndpoint()
*/
public String
getIpFromEndpoint()
{
return this.ip;
}
/**
* @see Client#getPort()
*/
public int
getPort()
{
return this.port;
}
/**
* @see Client#connect()
*/
public void
connect() throws ClientException
{
try
{
LOG.debug( "Starting connection..." );
telnet.connect( ip, port );
in = telnet.getInputStream();
out = new PrintStream( telnet.getOutputStream() );
// Encountered credential, we going to login.
if ( null != credential )
__login();
else
LOG.debug( "Anonymous access." );
}
catch( SocketException se )
{
throw new ClientException( Error.ER_CREATE_SOCKET_CONNECTION + " "
+ this.ip + ":" + this.port, se );
}
catch( IOException ioe )
{
throw new ClientException( Error.ER_INPUT_OUTPUT_STREAM, ioe );
}
}
/**
* @see Client#close()
*/
public void
close() throws ClientException
{
try
{
LOG.debug( "Closing communication with server " + ip );
telnet.disconnect();
}
catch( IOException io )
{
throw new ClientException( Error.ER_INPUT_OUTPUT_STREAM, io );
}
}
/**
* @see Client#send(String)
*/
public void
send( String message ) throws ClientException
{
this.receive = __send( message );
}
/**
* @see Client#receive()
*/
public
String receive()
{
return this.receive;
}
/**
* @see Client#isConnect()
*/
public boolean
isConnect()
{
return telnet.isConnected();
}
public String
getUsername()
{
return username;
}
public String
getPassword()
{
return password;
}
/*
* Sends something to the endpoint.
*/
private String
__send( String something ) throws ClientException
{
if ( ! isConnect() )
throw new ClientException( Error.ER_CLIENT_IS_NOT_CONNECTED );
try
{
String prompt = "$";
__write( something );
return __readUntil( prompt + " " );
}
catch( Exception e )
{
throw new ClientException( Error.ER_UNEXPECTED_ERROR, e );
}
}
/*
* Reads until specific pattern.
*/
private String
__readUntil( String pattern )
throws ClientException
{
try
{
char lastChar = pattern.charAt( pattern.length() - 1 );
StringBuffer sb = new StringBuffer();
char ch = (char) in.read();
while( true )
{
sb.append( ch );
if ( ch == lastChar )
{
if ( sb.toString().endsWith( pattern ) )
return sb.toString();
}
ch = (char) in.read();
}
}
catch( Exception e )
{
throw new ClientException( Error.ER_UNEXPECTED_ERROR, e );
}
}
/*
* Writes to output Stream.
*/
private void
__write( String value ) throws ClientException
{
try
{
out.println( value );
out.flush();
}
catch( Exception e )
{
throw new ClientException( Error.ER_UNEXPECTED_ERROR, e );
}
}
/*
* Starts process of login with credentials given previously. Obviously,
* just to authentication that is not anonymous.
*
* The taken prompt from command line, can match with "#" or "$". The
* __readUntil method, getting through all String until it's match with one
* of the two quoted prompts.
*/
private void
__login() throws ClientException
{
__readUntil( "login: " );
__write( credential.getUser() );
__readUntil( "Password: " );
__write( credential.getPassword() );
String prompt = "$";
__readUntil( prompt + " " );
}
}
| 20.78777 | 76 | 0.664475 |
5cf7307bcf2f4127891eccea133d8d461848a33a | 2,247 | package com.coinninja.coinkeeper.presenter.activity;
import javax.inject.Inject;
public class RecoveryWordsPresenter {
static final int NUM_WORDS = 12;
static final int MAX_PAGER_POSITION = NUM_WORDS - 1;
public enum ButtonState {
START, DEFAULT, END
}
View view;
@Inject
public RecoveryWordsPresenter() {
}
public void onPageChange(int position) {
ButtonState buttonState = calculateButtonState(position);
StringBuilder positionCountTXT = new StringBuilder();
positionCountTXT.append("word ");
positionCountTXT.append(position + 1);
positionCountTXT.append(" of ");
positionCountTXT.append(NUM_WORDS);
view.setPageCounterText(positionCountTXT.toString());
view.setPagePosition(position);
switch (buttonState) {
case START:
view.hideFirst();
view.showNext();
break;
case DEFAULT:
view.showFirst();
view.showNext();
break;
case END:
view.showLast();
break;
}
}
public void onNextClicked() {
int currentPosition = view.getPagePosition();
ButtonState buttonState = calculateButtonState(currentPosition);
if (buttonState == ButtonState.END) {
view.showNextActivity();
} else {
view.scrollToPage(view.getPagePosition() + 1);
}
}
public void onBackClicked() {
view.scrollToPage(view.getPagePosition() - 1);
}
public void attach(View view) {
this.view = view;
}
private ButtonState calculateButtonState(int position) {
if (position == 0) {
return ButtonState.START;
}
return position == MAX_PAGER_POSITION ? ButtonState.END : ButtonState.DEFAULT;
}
public interface View {
int getPagePosition();
void setPagePosition(int pagePosition);
void scrollToPage(int pagePosition);
void setPageCounterText(String msg);
void showNextActivity();
void hideFirst();
void showNext();
void showFirst();
void showLast();
}
}
| 23.904255 | 86 | 0.591455 |
b92700a0caf154a50697127d2f3c10f8117bcde6 | 320 | package com.clients;
import com.panels.BasicPanel;
// Concrete Creator from the 'Factory Method' pattern. Creates teacher frame.
public class TeacherFrameCreator extends FrameCreator {
@Override
public BasicFrame createFrame(String frameTitle, BasicPanel panel) {
return new TeacherFrame(frameTitle, panel);
}
}
| 24.615385 | 77 | 0.79375 |
013d9474744231a50f14341f0ea6348fa9e16c00 | 2,951 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.layout;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPartViewer;
/**
* The class is the owner of the table layout.
*/
public interface ITableLayoutOwner
{
/**The owner if is active
* @return
*/
boolean isActive( );
/**Gets the layout figure
* @return
*/
IFigure getFigure();
/**
*Need the layout layout again
*/
void reLayout( );
/**gets the viewer
* @return
*/
//The methos maybe change
EditPartViewer getViewer();
/**Gets the heigh infomation form the model
* @param number
* @return
*/
DimensionInfomation getRowHeight(int number);
/**Gets the column from the model
* @param number
* @return
*/
DimensionInfomation getColumnWidth(int number);
/**Gets the column count
* @return
*/
int getColumnCount( );
/**Gets the row count
* @return
*/
int getRowCount( );
/**Gets the children
* @return
*/
List getChildren();
/**Gets the define width.
* @return
*/
String getDefinedWidth( );
/**If the force set to t he model
* @return
*/
boolean isForceWidth();
/**Gets the define height,return null if the owner don't support the height;
* @return
*/
String getDefinedHeight();
/**Gets the ori column width
* @param columNumber
* @return
*/
String getRawWidth( int columNumber);
/**Through the row infomation to cale the height value.
* @param number
* @return
*/
int getRowHeightValue(int number);
/**Through the column infomation to cale the width value.
* @param number
* @return
*/
int getColumnWidthValue(int number);
/**Gets the allow min row hight.If no special request, return FixTableLayout.DEFAULT_ROW_HEIGHT;
* @return
*/
int getFixAllowMinRowHight();
/**value and unit
* DimensionInfomation
*/
public static class DimensionInfomation
{
private double measure;
private String units = ""; //$NON-NLS-1$
private boolean isSet = false;
public DimensionInfomation(double measure, String units)
{
this(measure, units, false);
}
public DimensionInfomation(double measure, String units, boolean isSet)
{
this.measure = measure;
this.units = units;
this.isSet = isSet;
}
public String getUnits( )
{
return units;
}
public double getMeasure( )
{
return measure;
}
public boolean isSet()
{
return isSet;
}
}
}
| 20.212329 | 98 | 0.642833 |
5926a60206448de2e8b5352b45efa9315dce685c | 1,424 | package scene.geometry;
import java.util.ArrayList;
import support.Color3f;
import support.Point3f;
import support.TexCoord2f;
import support.Vector3f;
import support.Vector4f;
import util.Point4f;
import util.WorldTriangle;
public class TriangleSet extends Geometry
{
public TriangleSet(Point3f [] coordinates, Vector3f [] normals, TexCoord2f [] textureCoordinates, int [] coordinateIndices, int [] normalIndices, int [] textureCoordinateIndices, String name)
{
super(name);
// convert arrays to actual WorldTriangles
ArrayList<WorldTriangle> tr = new ArrayList<WorldTriangle>();
for(int i = 0; i < coordinateIndices.length; i=i+3)
{
Point4f a = coordinates[coordinateIndices[i]].get4f();
Point4f b = coordinates[coordinateIndices[i+1]].get4f();
Point4f c = coordinates[coordinateIndices[i+2]].get4f();
Point4f[] cornerpoints = {a,b,c};
Vector4f a_normal = normals[normalIndices[i]].get4f();
Vector4f b_normal = normals[normalIndices[i+1]].get4f();
Vector4f c_normal = normals[normalIndices[i+2]].get4f();
Vector4f[] norms = {a_normal,b_normal,c_normal};
TexCoord2f a_tex = textureCoordinates[textureCoordinateIndices[i]];
TexCoord2f b_tex = textureCoordinates[textureCoordinateIndices[i+1]];
TexCoord2f c_tex = textureCoordinates[textureCoordinateIndices[i+2]];
TexCoord2f[] texs = {a_tex,b_tex,c_tex};
tr.add(new WorldTriangle(cornerpoints, norms, texs));
}
}
}
| 36.512821 | 192 | 0.748596 |
ac09f2de82426ddf6d63e21febc1f7e68e10bb01 | 1,108 | package homework3;
/**
* BasePlusCommisionEmployee: baseSalary
* Employee->CommisionEmployee->BasePlusCommisionEmployee
*
* Created by WeiXiao on 06/12/17
*/
public class _15211301_WeiXiao_3_BasePlusCommisionEmployee extends _15211301_WeiXiao_3_CommisionEmployee
{
private double baseSalary;
public _15211301_WeiXiao_3_BasePlusCommisionEmployee()
{
baseSalary=0.0;
}
public _15211301_WeiXiao_3_BasePlusCommisionEmployee(double b,double c,double g,String f,String l,String s)
{
super(c,g,f,l,s);
baseSalary=b;
}
public final double getBaseSalary()
{
return baseSalary;
}
public final void setBaseSalary(double c)
{
baseSalary=c;
}
@Override
public int earning() {
return super.earning()+(int)Math.floor(baseSalary);//向下取整再int
}
public String toString()
{
StringBuilder base= new StringBuilder("");
//base.append(super.toString());
//base.append("\n基本工资:"+getBaseSalary());
base.append("本月工资:"+earning());
return base.toString();
}
}
| 22.612245 | 111 | 0.66065 |
3c0f5610b508ff6ed6254fedf37c3fcf4c72f5d7 | 9,728 | package com.huazie.fleaframework.db.sql;
import com.huazie.fleaframework.common.FleaFrameManager;
import com.huazie.fleaframework.common.slf4j.FleaLogger;
import com.huazie.fleaframework.common.slf4j.impl.FleaLoggerProxy;
import com.huazie.fleaframework.core.base.cfgdata.entity.FleaConfigData;
import com.huazie.fleaframework.core.base.cfgdata.service.interfaces.IFleaConfigDataSV;
import com.huazie.fleaframework.db.common.sql.template.ITemplate;
import com.huazie.fleaframework.db.common.sql.template.SqlTemplate;
import com.huazie.fleaframework.db.common.sql.template.impl.DeleteSqlTemplate;
import com.huazie.fleaframework.db.common.sql.template.impl.InsertSqlTemplate;
import com.huazie.fleaframework.db.common.sql.template.impl.SelectSqlTemplate;
import com.huazie.fleaframework.db.common.sql.template.impl.UpdateSqlTemplate;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Locale;
public class SqlTemplateTest {
private static final FleaLogger LOGGER = FleaLoggerProxy.getProxyInstance(SqlTemplateTest.class);
private ApplicationContext applicationContext;
private FleaConfigData fleaConfigData;
@Before
public void init() {
try {
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
LOGGER.debug("ApplicationContext={}", applicationContext);
IFleaConfigDataSV sv = (IFleaConfigDataSV) applicationContext.getBean("fleaConfigDataSV");
fleaConfigData = sv.getConfigData("huazie", "huazie");
LOGGER.debug("FleaConfigData={}", fleaConfigData);
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testDeleteSqlTemplate1() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
SqlTemplate<FleaConfigData> sqlTemplate = new DeleteSqlTemplate<>();
// 这个对应<template id="delete">
sqlTemplate.setId("delete");
// 实体类对应的表名
sqlTemplate.setTableName("flea_config_data");
// 实体类的实例对象
sqlTemplate.setEntity(fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testDeleteSqlTemplate1 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testDeleteSqlTemplate1 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testDeleteSqlTemplate2() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new DeleteSqlTemplate<>("delete", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testDeleteSqlTemplate2 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testDeleteSqlTemplate2 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testDeleteSqlTemplate3() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new DeleteSqlTemplate<>("delete", "flea_config_data", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testDeleteSqlTemplate3 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testDeleteSqlTemplate3 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testInsertSqlTemplate1() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
SqlTemplate<FleaConfigData> sqlTemplate = new InsertSqlTemplate<>();
// 这个对应<template id="insert">
sqlTemplate.setId("insert");
// 实体类对应的表名
sqlTemplate.setTableName("flea_config_data");
// 实体类的实例对象
sqlTemplate.setEntity(fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testInsertSqlTemplate1 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testInsertSqlTemplate1 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testInsertSqlTemplate2() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new InsertSqlTemplate<>("insert", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testInsertSqlTemplate2 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testInsertSqlTemplate2 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testInsertSqlTemplate3() {
// FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new InsertSqlTemplate<>("insert", "flea_config_data", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testInsertSqlTemplate3 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testInsertSqlTemplate3 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testSelectSqlTemplate1() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
SqlTemplate<FleaConfigData> sqlTemplate = new SelectSqlTemplate<>();
// 这个对应<template id="select">
sqlTemplate.setId("select");
// 实体类对应的表名
sqlTemplate.setTableName("flea_config_data");
// 实体类的实例对象
sqlTemplate.setEntity(fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testSelectSqlTemplate1 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testSelectSqlTemplate1 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testSelectSqlTemplate2() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new SelectSqlTemplate<>("select", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testSelectSqlTemplate2 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testSelectSqlTemplate2 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testSelectSqlTemplate3() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new SelectSqlTemplate<>("select", "flea_config_data", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testSelectSqlTemplate3 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testSelectSqlTemplate3 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testUpdateSqlTemplate1() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
SqlTemplate<FleaConfigData> sqlTemplate = new UpdateSqlTemplate<>();
// 这个对应<template id="update">
sqlTemplate.setId("update");
// 实体类对应的表名
//sqlTemplate.setTableName("flea_config_data");
// 实体类的实例对象
sqlTemplate.setEntity(fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testUpdateSqlTemplate1 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testUpdateSqlTemplate1 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testUpdateSqlTemplate2() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new UpdateSqlTemplate<>("update", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testUpdateSqlTemplate2 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testUpdateSqlTemplate2 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
@Test
public void testUpdateSqlTemplate3() {
FleaFrameManager.getManager().setLocale(Locale.US);
try {
ITemplate<FleaConfigData> sqlTemplate = new UpdateSqlTemplate<>("update", "flea_config_data", fleaConfigData);
// 模板初始化
sqlTemplate.initialize();
LOGGER.debug("testUpdateSqlTemplate3 --> NativeSql={}", sqlTemplate.toNativeSql());
LOGGER.debug("testUpdateSqlTemplate3 --> NativeParams={}", sqlTemplate.toNativeParams());
} catch (Exception e) {
LOGGER.error("Exception:", e);
}
}
} | 39.706122 | 122 | 0.632813 |
e398d8d25a900236103be50e41068ab43bf4813d | 3,895 | /*
* 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.sling.resourceresolver.impl;
import static org.apache.sling.resourceresolver.impl.MockedResourceResolverImplTest.createRPHandler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderHandler;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderStorage;
import org.apache.sling.spi.resource.provider.ResolverContext;
import org.apache.sling.spi.resource.provider.ResourceContext;
import org.apache.sling.spi.resource.provider.ResourceProvider;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class ProviderHandlerTest {
@SuppressWarnings("unchecked")
@Test public void testServletRegistrationAndSyntheticResources() throws LoginException {
final String servletpath = "/libs/a/b/GET.servlet";
final Resource servletResource = Mockito.mock(Resource.class);
Mockito.when(servletResource.getResourceMetadata()).then(new Answer<ResourceMetadata>() {
@Override
public ResourceMetadata answer(InvocationOnMock invocation) throws Throwable {
return new ResourceMetadata();
}
});
final ResourceProvider<?> leaveProvider = Mockito.mock(ResourceProvider.class);
Mockito.when(leaveProvider.getResource(Mockito.any(ResolverContext.class), Mockito.eq(servletpath), Mockito.any(ResourceContext.class), Mockito.any(Resource.class))).thenReturn(servletResource);
ResourceProviderHandler h = createRPHandler(leaveProvider, "my-pid", 0, servletpath);
ResourceResolver resolver = new ResourceResolverImpl(new CommonResourceResolverFactoryImpl(new ResourceResolverFactoryActivator()), false, null, new ResourceProviderStorage(Arrays.asList(h)));
final Resource parent = resolver.getResource(ResourceUtil.getParent(servletpath));
assertNotNull("Parent must be available", parent);
assertTrue("Resource should be synthetic", ResourceUtil.isSyntheticResource(parent));
final Resource servlet = resolver.getResource(servletpath);
assertNotNull("Servlet resource must not be null", servlet);
assertEquals(servletResource, servlet);
assertNotNull(resolver.getResource("/libs"));
// now check when doing a resolve()
assertTrue(resolver.resolve("/libs") instanceof NonExistingResource);
assertTrue(resolver.resolve(ResourceUtil.getParent(servletpath)) instanceof NonExistingResource);
assertNotNull(resolver.resolve(servletpath));
resolver.close();
}
}
| 49.303797 | 202 | 0.769448 |
d632575818ec73e925dc688193a2b257acd3a527 | 2,182 | /*
* Copyright 2009-2011 Collaborative Research Centre SFB 632
*
* 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 annis.model;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class TestAnnisNode {
// object under test
private AnnisNode node;
@Before
public void setup() {
node = new AnnisNode(0);
}
@Test
public void qNameFullyQualified() {
assertThat(AnnisNode.qName("namespace", "name"), is("namespace:name"));
}
@Test
public void qNameNoNamespace() {
assertThat(AnnisNode.qName(null, "name"), is("name"));
}
@Test
public void setSpannedText() {
// sanity check: values are null
assertThat(node.getSpannedText(), is(nullValue()));
// set span and text matching
String spannedText = "span";
node.setSpannedText(spannedText);
// test functionality of setter
assertThat(node.getSpannedText(), is(spannedText));
}
@Test
public void clearSpannedText() {
// set some values
node.setSpannedText("span");
// sanity check
assertThat(node.getSpannedText(), is(not(nullValue())));
// clear values
node.clearSpannedText();
// test for null values
assertThat(node.getSpannedText(), is(nullValue()));
}
@Test
public void setTokenIndexToken() {
AnnisNode node = new AnnisNode(1);
node.setTokenIndex(1L);
assertThat(node.isToken(), is(true));
}
@Test
public void setTokenIndexNull() {
AnnisNode node = new AnnisNode(1);
node.setTokenIndex(null);
assertThat(node.isToken(), is(false));
}
}
| 23.717391 | 75 | 0.714024 |
76cf4e384cb9b593d4e979d322c7e1d5b1f5b808 | 5,922 | package BEANS;
import java.sql.*;
//import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
public class NewDocK {
public String lMenu = "";
public String navi = "";
public String getList(HttpServletRequest r, String o, String g) throws ClassNotFoundException, SQLException {
ServletContext sc = r.getServletContext();
Connection con = BASE.VER.getServletConnection(sc);
Statement stmt = con.createStatement();
boolean isSecurity = false;
String offset = "0";
if (r.getParameter("of") != null) {
offset = r.getParameter("of");
}
String own = r.getParameter("own");
String OWN = "";
boolean next = false;
int ROWS = BASE.VER.getMaxRows(sc);
int rows = ROWS + 1;
if (own != null) {
OWN = " AND owner=" + own;
}
String sec = "f";
String role = (String) r.getSession().getAttribute("role");
if (role.indexOf("e") >= 0 || role.indexOf("s") >= 0) {
isSecurity = true;
}
if (own != null && ((role.indexOf("o") >= 0 && own.equals("-100")) || (role.indexOf("p") >= 0 && own.equals("-101"))
|| (role.indexOf("q") >= 0 && own.equals("-102")) || (role.indexOf("r") >= 0 && own.equals("-103")))) {
isSecurity = true;
}
String sql = "SELECT files.id, files.owner, files.name, files.fname, files.descr, "
+ " type, properTime(files_vers.created) AS create, files.superior, "
+ " catalog_name(superior),dopusk_type, ver_id, files_vers.created, is_doc_opend(ver_id, " + o + ") AS opend, status FROM files, files_vers WHERE file='1' "
+ " AND files.owner<0 AND files.copy=files_vers.id" + OWN + " AND (isBlogPermitted (dopusk_type, dopusk, " + g + "::Int) OR '" + isSecurity + "') ORDER BY files_vers.created DESC LIMIT " + rows + " OFFSET " + offset;
ResultSet rs = stmt.executeQuery(sql);
String list = "<table><tbody>";
int cc = 0;
while (rs.next()) {
if (rs.isLast() && cc == rows - 1) {
next = true;
} else {
String t = rs.getString("type");
String type = EXXOlib.DOCTYPES.getType(t, rs.getString(4));
String opend = "";
if (!rs.getBoolean("opend")) {
opend = "nopend";
}
int owner = rs.getInt(2);
String Fio = "";
if (owner == -100) {
Fio = "Общие";
} else if (owner == -101) {
Fio = "Входящие";
} else if (owner == -102) {
Fio = "Исходящие";
} else if (owner == -103) {
Fio = "Внутренние";
}
String classBlocked = "";
//if(isSecurity||rs.getBoolean("permitted")) {
cc++;
if (rs.getInt("status") == 2) {
classBlocked = " blocked";
}
list += "<tr><td class='first " + type + "'></td><td class='fil'><a href=\"fileLoader.jsp?id=" + rs.getString(1) + "\" class='" + opend + classBlocked + "'>" + rs.getString(3) + "</a>(" + rs.getString(4) + ")</td>";
list += "<td class='fio'><a href=\"docClassic.jsp?owner=" + rs.getString(2) + "&id=" + rs.getString(8) + "\">" + rs.getString(9) + " (" + Fio + ")</a></td><td class='descr'>" + rs.getString(5) + "</td>"
+ "<td class='created'>" + rs.getString("create") + "</td><td class='dop'><img src='" + BASE.Props.dopusks[rs.getInt("dopusk_type")] + "'></td></tr>";
//}
}
}
list += "</tbody></table>";
//навигация пэйджер--
navi += "<div id='menu-navi'><table><tr><td class='oneNavi'>";
String andown = "";
if (own != null) {
andown = "&own=" + own;
}
int of = Integer.parseInt(offset);
if (of > 0) {
int prev = of - ROWS;
if (prev < 0) {
prev = 0;
}
navi += "<a href='newDocK.jsp?of=" + prev + andown + "' class='exxo-shadow' id='backward'></a>";
}
navi += "</td><td></td><td class='threeNavi'>";
if (next) {
int sled = of + ROWS;
navi += "<a href='newDocK.jsp?of=" + sled + andown + "' class='exxo-shadow' id='forward'></a>";
}
navi += "</td></tr></table></div>";
//----
String class1 = "";
String class100 = "";
String class101 = "";
String class102 = "";
String class103 = "";
if (own == null) {
class1 = " class='own'";
} else if (own.equals("-100")) {
class100 = " class='own'";
} else if (own.equals("-101")) {
class101 = " class='own'";
} else if (own.equals("-102")) {
class102 = " class='own'";
} else if (own.equals("-103")) {
class103 = " class='own'";
}
lMenu = "<div id='lMenu' class='exxo-shadow'>";
lMenu += "<a href='newDocK.jsp' " + class1 + ">Все документы</a>";
lMenu += "<a href='newDocK.jsp?own=-100' " + class100 + ">Общие документы</a>";
lMenu += "<a href='newDocK.jsp?own=-101' " + class101 + ">Входящие документы</a>";
lMenu += "<a href='newDocK.jsp?own=-102' " + class102 + ">Исходящие документы</a>";
lMenu += "<a href='newDocK.jsp?own=-103' " + class103 + ">Внутренние документы</a>";
lMenu += "</div>";
if (own != null) {
lMenu += "<div id=\"menuList\"><a href=\"docClassic.jsp?owner=" + own + "\" id=\"addgroup\">Структура папок</a></div>";
}
rs.close();
stmt.close();
con.close();
return list;
}
}
| 43.226277 | 233 | 0.47771 |
22bfb319e0b2107b826526632bb2dbc8fbaa9cd0 | 3,661 | /*
* Copyright 2019 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.datatransferproject.spi.transfer.provider;
import org.datatransferproject.types.transfer.errors.ErrorDetail;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.Callable;
/**
* A utility that will execute a {@link Callable} only once for a given {@code idempotentId}. This
* allows client code to be called multiple times in the case of retries without worrying about
* duplicating imported data.
*/
public interface IdempotentImportExecutor {
/**
* Executes a callable, a callable will only be executed once for a given idempotentId, subsequent
* calls will return the same result as the first invocation if it was successful.
*
* <p>If the provided callable throws an exception if is logged and ignored and null is returned.
*
* <p>This is useful for leaf level imports where the importer should continue if a single item
* can't be imported.
*
* <p>Any errors (that aren't latter successful) will be reported as failed items.
*
* @param idempotentId a unique ID to prevent data from being duplicated
* @param itemName a user visible/understandable string to be displayed to the user if the item
* can't be imported
* @param callable the callable to execute
* @return the result of executing the callable.
*/
<T extends Serializable> T executeAndSwallowExceptions(
String idempotentId, String itemName, Callable<T> callable);
/**
* Executes a callable, a callable will only be executed once for a given idempotentId, subsequent
* calls will return the same result as the first invocation if it was successful.
*
* <p>If the provided callable throws an exception then that is exception is rethrown.
*
* <p>This is useful for container level items where the rest of the import can't continue if
* there is an error.
*
* <p>Any errors (that aren't latter successful) will be reported as failed items.
*
* @param idempotentId a unique ID to prevent data from being duplicated
* @param itemName a user visible/understandable string to be displayed to the user if the item
* can't be imported
* @param callable the callable to execute
* @return the result of executing the callable.
*/
<T extends Serializable> T executeOrThrowException(
String idempotentId, String itemName, Callable<T> callable) throws IOException;
/**
* Returns a cached result from a previous call to {@code execute}.
*
* @param idempotentId a unique ID previously passed into {@code execute}
* @return the result of a previously evaluated {@code execute} call
* @throws IllegalArgumentException if the key is not found
*/
<T extends Serializable> T getCachedValue(String idempotentId) throws IllegalArgumentException;
/** Checks if a given key has been cached already. */
boolean isKeyCached(String idempotentId);
/** Get the set of all errors that occurred, and weren't subsequently successful. */
Collection<ErrorDetail> getErrors();
}
| 42.08046 | 100 | 0.740235 |
2faa619487577279f5b4755721f51d389469ed93 | 4,387 | package li.cil.circuity.common.ecs.component;
import li.cil.circuity.api.bus.BusController;
import li.cil.circuity.api.bus.BusElement;
import li.cil.circuity.api.bus.device.AbstractBusDevice;
import li.cil.circuity.api.bus.device.AddressBlock;
import li.cil.circuity.api.bus.device.AddressHint;
import li.cil.circuity.api.bus.device.Addressable;
import li.cil.circuity.api.bus.device.BusStateListener;
import li.cil.circuity.api.bus.device.DeviceInfo;
import li.cil.circuity.api.bus.device.DeviceType;
import li.cil.circuity.common.Constants;
import li.cil.lib.api.ecs.manager.EntityComponentManager;
import li.cil.lib.api.serialization.Serializable;
import li.cil.lib.api.serialization.Serialize;
import li.cil.lib.synchronization.value.SynchronizedLong;
import javax.annotation.Nullable;
import java.util.Arrays;
@Serializable
public final class BusDeviceRandomAccessMemory extends AbstractComponentBusDevice {
private static final byte[] EMPTY = new byte[0];
@Serialize
private final RandomAccessMemoryImpl device = new RandomAccessMemoryImpl();
@Serialize
private byte[] memory = EMPTY;
// Component ID of controller for client.
public final SynchronizedLong controllerId = new SynchronizedLong();
// --------------------------------------------------------------------- //
public BusDeviceRandomAccessMemory(final EntityComponentManager manager, final long entity, final long id) {
super(manager, entity, id);
}
// --------------------------------------------------------------------- //
public int getSize() {
return memory.length;
}
public void setSize(final int bytes) {
final byte[] newMemory = bytes > 0 ? new byte[bytes] : EMPTY;
System.arraycopy(memory, 0, newMemory, 0, Math.min(memory.length, newMemory.length));
memory = newMemory;
if (device.getBusController() != null) {
device.getBusController().scheduleScan();
}
}
// --------------------------------------------------------------------- //
// AbstractComponentBusDevice
@Override
public BusElement getBusElement() {
return device;
}
// --------------------------------------------------------------------- //
public static final DeviceInfo DEVICE_INFO = new DeviceInfo(DeviceType.READ_WRITE_MEMORY, Constants.DeviceInfo.RANDOM_ACCESS_MEMORY_NAME);
public final class RandomAccessMemoryImpl extends AbstractBusDevice implements Addressable, AddressHint, BusStateListener {
// --------------------------------------------------------------------- //
// BusElement
@Override
public void setBusController(@Nullable final BusController controller) {
super.setBusController(controller);
BusDeviceRandomAccessMemory.this.controllerId.set(getBusControllerId(controller));
}
// --------------------------------------------------------------------- //
// BusDevice
@Nullable
@Override
public DeviceInfo getDeviceInfo() {
return DEVICE_INFO;
}
// --------------------------------------------------------------------- //
// Addressable
@Override
public AddressBlock getPreferredAddressBlock(final AddressBlock memory) {
return memory.take(Constants.MEMORY_ADDRESS, BusDeviceRandomAccessMemory.this.memory.length);
}
@Override
public int read(final long address) {
return BusDeviceRandomAccessMemory.this.memory[(int) address] & 0xFF;
}
@Override
public void write(final long address, final int value) {
BusDeviceRandomAccessMemory.this.memory[(int) address] = (byte) value;
BusDeviceRandomAccessMemory.this.markChanged();
}
// --------------------------------------------------------------------- //
// AddressHint
@Override
public int getSortHint() {
return Constants.MEMORY_ADDRESS;
}
// --------------------------------------------------------------------- //
// BusStateListener
@Override
public void handleBusOnline() {
}
@Override
public void handleBusOffline() {
Arrays.fill(BusDeviceRandomAccessMemory.this.memory, (byte) 0);
}
}
}
| 34.543307 | 142 | 0.577388 |
33c676edcd68f9f46176f89ba0002e2feaf3f96b | 12,887 | package harry.security.responder.resources;
import iaik.cms.SecurityProvider;
import iaik.cms.ecc.ECCelerateProvider;
import iaik.security.ec.provider.ECCelerate;
import iaik.security.provider.IAIKMD;
import iaik.utils.Util;
import iaik.x509.X509CRL;
import iaik.x509.X509Certificate;
import iaik.x509.ocsp.OCSPRequest;
import iaik.x509.ocsp.OCSPResponse;
import org.apache.commons.io.IOUtils;
import org.harry.security.CommonConst;
import org.harry.security.util.Tuple;
import org.harry.security.util.certandkey.KeyStoreTool;
import org.harry.security.util.keystores.UnicProvider;
import org.pmw.tinylog.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import static harry.security.responder.resources.UnicHornResponderUtil.*;
import static org.harry.security.CommonConst.APP_DIR_TRUST;
public class UnichornResponder extends HttpServlet {
public static boolean loggingInitialized = false;
public static void initReq() {
LoggerConfigSetter.setLoggerConfig();
/* register the providers*/
Provider iaik = Security.getProvider("IAIK");
Provider iaikMD = Security.getProvider("IAIKMD");
Provider ecc = Security.getProvider("ECCelerate");
if (iaik == null && iaikMD == null && ecc == null) {
Logger.trace("register base providers IAIK / IAIKMD");
IAIKMD.addAsProvider();
Logger.trace("register ECCelerate provider");
ECCelerate.insertProviderAt(3);
Logger.trace("register our own keystore spi");
Security.insertProviderAt(UnicProvider.getInstance(), 4);
Logger.trace("register ECCelerate security provider");
SecurityProvider.setSecurityProvider(new ECCelerateProvider());
Logger.trace("providers are registered");
} else {
Logger.trace("The providers are already registered");
}
}
@Override
public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
initReq();
String output = "Jersey say : ";
Logger.trace("Hallo here I am");
Logger.trace("enter ocsp method");
Map<String,String> messages = new HashMap<>();
messages.put("pre", "pre started: ");
try {
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(servletRequest);
InputStream stream = servletRequest.getInputStream();
String indicator = (stream == null) ? "null" : "not null";
Logger.trace("pre request read stream is: " + indicator);
OCSPRequest ocspRequest = new OCSPRequest(stream);
Logger.trace( "request read");
OCSPResponse response = UnicHornResponderUtil.generateResponse(ocspRequest,
copyTo(ocspRequest));
Logger.trace("Write stream");
response.writeTo(servletResponse.getOutputStream());
Logger.trace("written stream");
servletResponse.setStatus(Response.Status.OK.getStatusCode());
Logger.trace("Seems to be ok:");
servletResponse.setHeader("Content-Type","application/ocsp-response");
for(String key: messages.keySet()) {
servletResponse.addHeader(key, messages.get(key));
}
} catch (Exception ex) {
OCSPResponse response = new OCSPResponse(OCSPResponse.malformedRequest);
response.writeTo(servletResponse.getOutputStream());
servletResponse.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Logger.trace("Error Message is:" + ex.getMessage());
for(String key: messages.keySet()) {
servletResponse.addHeader(key, messages.get(key));
}
}
}
@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
initReq();
File trustFile = new File(APP_DIR_TRUST, "trustListPrivate" + ".xml");
Logger.trace("Trust file is: " + trustFile.getAbsolutePath());
File crlFile = new File(APP_DIR_TRUST, "privRevokation" + ".crl");
Logger.trace("CRL list file is: " + crlFile.getAbsolutePath());
File keyFile = new File(APP_DIR_TRUST, CommonConst.PRIV_KEYSTORE);
Logger.trace("Key Store file is: " + keyFile.getAbsolutePath());
String type = request.getHeader("fileType");
if (type.equals("crl")) {
OutputStream out = new FileOutputStream(crlFile);
InputStream in = request.getInputStream();
IOUtils.copy(in, out);
in.close();
out.close();
X509CRL crl = readCrl(new FileInputStream(crlFile));
Tuple<PrivateKey, X509Certificate[]> keys =getPrivateKeyX509CertificateTuple();
crl.setIssuerDN(keys.getSecond()[0].getIssuerDN());
crl.sign(keys.getFirst());
} else if (type.equals("UnicP12")) {
String passwdHeader = request.getHeader("passwd");
String passwdUser = request.getHeader("passwdUser");
String decodedUser = new String(Util.fromBase64String(passwdUser));
String decodedString = null;
if (passwdHeader != null) {
byte[] decodedPwd = Base64.getDecoder().decode(passwdHeader.getBytes());
decodedString = new String(decodedPwd);
encryptPassword("pwdFile", decodedString);
}
String storeTypeHeader = request.getHeader("storeType");
if (storeTypeHeader != null && decodedString != null) {
File temp = saveToTemp(request.getInputStream());
InputStream p12Stream = new FileInputStream(temp);
Logger.trace("Before loading keystore");
KeyStore storeToApply = KeyStoreTool.loadStore(p12Stream,
decodedUser.toCharArray(), storeTypeHeader);
Logger.trace("Before calling merge");
applyKeyStore(keyFile, storeToApply, decodedString, decodedUser, storeTypeHeader);
Logger.trace("After calling merge --> created");
response.setStatus(Response.Status.CREATED.getStatusCode());
}
} else if (type.equals("trust")) {
InputStream trustStream = request.getInputStream();
OutputStream out = new FileOutputStream(trustFile);
IOUtils.copy(trustStream, out);
trustStream.close();
out.close();
response.setStatus(Response.Status.CREATED.getStatusCode());
} else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} catch (Exception ex) {
Logger.trace("Error case load trust or pkcs7 or crl : " + ex.getMessage());
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
}
@Override
public void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
initReq();
Logger.trace("Enter get");
String type = servletRequest.getHeader("fileType");
Map<String,String> messages = new HashMap<>();
if (type == null) {
String path = servletRequest.getPathInfo();
Logger.trace("The path information is: -> " + path);
String ocsp = path.substring("/ocsp/".length());
Logger.trace("The extract information is: -> " + ocsp);
try {
byte [] encoded = Base64.getDecoder().decode(ocsp.getBytes());
Logger.trace("Before getting request");
OCSPRequest ocspRequest = new OCSPRequest(encoded);
Logger.trace("After getting request" + ocspRequest.toString(true));
OCSPResponse response = UnicHornResponderUtil.generateResponse(ocspRequest,
copyTo(ocspRequest));
Logger.trace("Write stream");
response.writeTo(servletResponse.getOutputStream());
Logger.trace("written stream");
servletResponse.setStatus(Response.Status.OK.getStatusCode());
servletResponse.setHeader("success", "Seems to be ok:");
servletResponse.setHeader("Content-Type","application/ocsp-response");
for(String key: messages.keySet()) {
servletResponse.addHeader(key, messages.get(key));
}
} catch (Exception ex) {
Logger.trace("exception type is ;; " + ex.getClass().getCanonicalName());
Logger.trace("Error casewith message :: " + ex.getMessage());
Logger.trace(" has cause " + ((ex.getCause() == null) ? "false" : "true"))
;
servletResponse.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
servletResponse.setHeader("error", "Message is:" + ex.getMessage());
for(String key: messages.keySet()) {
servletResponse.addHeader(key, messages.get(key));
}
}
}
if (type.equals("crl")) {
try {
InputStream stream = UnicHornResponderUtil.loadActualCRL();
OutputStream out = servletResponse.getOutputStream();
IOUtils.copy(stream, out);
stream.close();
servletResponse.setStatus(Response.Status.OK.getStatusCode());
return;
} catch (IOException ex){
servletResponse.setStatus(Response.Status.FORBIDDEN.getStatusCode());
return;
}
} else if (type.equals("trust")){
File trustFile = new File(APP_DIR_TRUST, "trustListPrivate" + ".xml");
if (trustFile.exists()) {
try {
FileInputStream stream = new FileInputStream(trustFile);
OutputStream out = servletResponse.getOutputStream();
IOUtils.copy(stream, out);
stream.close();
servletResponse.setStatus(Response.Status.OK.getStatusCode());
return;
} catch (IOException ex){
servletResponse.setStatus(Response.Status.FORBIDDEN.getStatusCode());
return;
}
}
} else if (type.equals("UnicP12")){
File keyFile = new File(APP_DIR_TRUST, "privKeystore" + ".p12");
if (keyFile.exists()) {
try {
FileInputStream stream = new FileInputStream(keyFile);
OutputStream out = servletResponse.getOutputStream();
IOUtils.copy(stream, out);
stream.close();
servletResponse.setStatus(Response.Status.OK.getStatusCode());
return;
} catch (IOException ex){
servletResponse.setStatus(Response.Status.FORBIDDEN.getStatusCode());
return;
}
}
} else {
servletResponse.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
}
private ByteArrayInputStream copyTo(OCSPRequest request) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
request.writeTo(out);
ByteArrayInputStream bufferIN = new ByteArrayInputStream(out.toByteArray());
out.close();
return bufferIN;
} catch (Exception ex) {
throw new IllegalStateException("cannot copy stream", ex);
}
}
public File saveToTemp(InputStream input) throws IOException {
File tempFile = File.createTempFile("upload", ".dat");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(input, out);
out.flush();
input.close();
out.close();
return tempFile;
}
public static boolean isLoggingInitialized() {
boolean result = loggingInitialized;
loggingInitialized = true;
return result;
}
}
| 42.956667 | 133 | 0.601847 |
b07138347cafe1012f134c61b37b2aedae8da14e | 42 | package main;
public class MainCtrl {
}
| 7 | 23 | 0.714286 |
14bb1c61c841c1292047832f9a3a9718ae4842a5 | 2,916 | package br.indie.fiscal4j.cte300.classes.nota;
import br.indie.fiscal4j.DFBase;
import br.indie.fiscal4j.validadores.DFBigDecimalValidador;
import br.indie.fiscal4j.validadores.StringValidador;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import java.math.BigDecimal;
/**
* @author Caio
* @info Informações relativas aos Impostos
*/
@Root(name = "imp")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeNotaInfoInformacoesRelativasImpostos extends DFBase {
private static final long serialVersionUID = -1424546812171486009L;
@Element(name = "ICMS")
private CTeNotaInfoInformacoesRelativasImpostosICMS icms;
@Element(name = "vTotTrib", required = false)
private String valorTotalTributos;
@Element(name = "infAdFisco", required = false)
private String informacoesAdicionaisFisco;
@Element(name = "ICMSUFFim", required = false)
private CTeNotaInfoInformacoesRelativasImpostosICMSPartilha icmsPartilha;
public CTeNotaInfoInformacoesRelativasImpostos() {
this.icms = null;
this.valorTotalTributos = null;
this.informacoesAdicionaisFisco = null;
this.icmsPartilha = null;
}
public CTeNotaInfoInformacoesRelativasImpostosICMS getIcms() {
return this.icms;
}
/**
* Informações relativas ao ICMS
*/
public void setIcms(final CTeNotaInfoInformacoesRelativasImpostosICMS icms) {
this.icms = icms;
}
public String getValorTotalTributos() {
return this.valorTotalTributos;
}
/**
* Valor Total dos Tributos
*/
public void setValorTotalTributos(final BigDecimal valorTotalTributos) {
this.valorTotalTributos = DFBigDecimalValidador.tamanho15Com2CasasDecimais(valorTotalTributos, "Valor Total dos Tributos");
}
public String getInformacoesAdicionaisFisco() {
return this.informacoesAdicionaisFisco;
}
/**
* Informações adicionais de interesse do Fisco<br>
* Norma referenciada, informações complementares, etc
*/
public void setInformacoesAdicionaisFisco(final String informacoesAdicionaisFisco) {
StringValidador.tamanho2000(informacoesAdicionaisFisco, "Informações adicionais de interesse do Fisco");
this.informacoesAdicionaisFisco = informacoesAdicionaisFisco;
}
public CTeNotaInfoInformacoesRelativasImpostosICMSPartilha getIcmsPartilha() {
return this.icmsPartilha;
}
/**
* Informações do ICMS de partilha com a UF de término do serviço de transporte na operação interestadual<br>
* Grupo a ser informado nas prestações interestaduais para consumidor final, não contribuinte do ICMS
*/
public void setIcmsPartilha(final CTeNotaInfoInformacoesRelativasImpostosICMSPartilha icmsPartilha) {
this.icmsPartilha = icmsPartilha;
}
}
| 33.136364 | 131 | 0.74177 |
1b6bfffc265929cb571d103e221e8c24a95b5778 | 11,154 | /*
* Copyright (C) 2014 Camptocamp
*
* This file is part of MapFish Print
*
* MapFish Print 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 3 of the License, or
* (at your option) any later version.
*
* MapFish Print 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 MapFish Print. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapfish.print.map.geotools;
import com.google.common.collect.Sets;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import com.google.common.io.Closer;
import com.google.common.io.Files;
import com.vividsolutions.jts.geom.Geometry;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultEngineeringCRS;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mapfish.print.Constants;
import org.mapfish.print.ExceptionUtils;
import org.mapfish.print.FileUtils;
import org.mapfish.print.PrintException;
import org.mapfish.print.config.Template;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nonnull;
/**
* Parser for GeoJson features collection.
* <p/>
* Created by Stéphane Brunner on 16/4/14.
*/
public class FeaturesParser {
private static final Logger LOGGER = LoggerFactory.getLogger(FeaturesParser.class);
private final MfClientHttpRequestFactory httpRequestFactory;
private final boolean forceLongitudeFirst;
/**
* Construct.
*
* @param httpRequestFactory the HTTP request factory
* @param forceLongitudeFirst if true then force longitude coordinate as first coordinate
*/
public FeaturesParser(final MfClientHttpRequestFactory httpRequestFactory, final boolean forceLongitudeFirst) {
this.httpRequestFactory = httpRequestFactory;
this.forceLongitudeFirst = forceLongitudeFirst;
}
/**
* Get the features collection from a GeoJson inline string or URL.
*
* @param template the template
* @param features what to parse
* @return the feature collection
* @throws IOException
*/
public final SimpleFeatureCollection autoTreat(final Template template, final String features) throws IOException {
SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);
if (featuresCollection == null) {
featuresCollection = treatStringAsGeoJson(features);
}
return featuresCollection;
}
/**
* Get the features collection from a GeoJson URL.
*
* @param template the template
* @param geoJsonUrl what to parse
* @return the feature collection
*/
public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl) throws IOException {
URL url;
try {
url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));
} catch (MalformedURLException e) {
return null;
}
final String geojsonString;
Closer closer = Closer.create();
try {
Reader input;
if (url.getProtocol().equalsIgnoreCase("file")) {
final CharSource charSource = Files.asCharSource(new File(url.getFile()), Constants.DEFAULT_CHARSET);
input = closer.register(charSource.openBufferedStream());
} else {
final ClientHttpResponse response = closer.register(this.httpRequestFactory.createRequest(url.toURI(),
HttpMethod.GET).execute());
input = closer.register(new BufferedReader(new InputStreamReader(response.getBody(), Constants.DEFAULT_CHARSET)));
}
geojsonString = CharStreams.toString(input);
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
} finally {
closer.close();
}
return treatStringAsGeoJson(geojsonString);
}
/**
* Get the features collection from a GeoJson inline string.
*
* @param geoJsonString what to parse
* @return the feature collection
* @throws IOException
*/
public final SimpleFeatureCollection treatStringAsGeoJson(final String geoJsonString) throws IOException {
return readFeatureCollection(geoJsonString);
}
private SimpleFeatureCollection readFeatureCollection(final String geojsonData) throws IOException {
String convertedGeojsonObject = convertToGeoJsonCollection(geojsonData);
FeatureJSON geoJsonReader = new FeatureJSON();
final SimpleFeatureType featureType = createFeatureType(convertedGeojsonObject);
if (featureType != null) {
geoJsonReader.setFeatureType(featureType);
}
ByteArrayInputStream input = new ByteArrayInputStream(convertedGeojsonObject.getBytes(Constants.DEFAULT_CHARSET));
return (SimpleFeatureCollection) geoJsonReader.readFeatureCollection(input);
}
private String convertToGeoJsonCollection(final String geojsonData) {
String convertedGeojsonObject = geojsonData.trim();
if (convertedGeojsonObject.startsWith("[")) {
convertedGeojsonObject = "{\"type\": \"FeatureCollection\", \"features\": " + convertedGeojsonObject + "}";
}
return convertedGeojsonObject;
}
private SimpleFeatureType createFeatureType(@Nonnull final String geojsonData) {
try {
JSONObject geojson = new JSONObject(geojsonData);
if (geojson.has("type") && geojson.getString("type").equalsIgnoreCase("FeatureCollection")) {
CoordinateReferenceSystem crs = parseCoordinateReferenceSystem(geojson);
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("GeosjonFeatureType");
final JSONArray features = geojson.getJSONArray("features");
Set<String> allAttributes = Sets.newHashSet();
Class<Geometry> geomType = null;
for (int i = 0; i < features.length(); i++) {
final JSONObject feature = features.getJSONObject(i);
final JSONObject properties = feature.getJSONObject("properties");
final Iterator keys = properties.keys();
while (keys.hasNext()) {
String nextKey = (String) keys.next();
if (!allAttributes.contains(nextKey)) {
allAttributes.add(nextKey);
builder.add(nextKey, Object.class);
}
if (geomType != Geometry.class) {
Class<Geometry> thisGeomType = parseGeometryType(feature);
if (thisGeomType != null) {
if (geomType == null) {
geomType = thisGeomType;
} else if (geomType != thisGeomType) {
geomType = Geometry.class;
}
}
}
}
}
builder.add("geometry", geomType, crs);
builder.setDefaultGeometry("geometry");
return builder.buildFeatureType();
} else {
return null;
}
} catch (JSONException e) {
throw new PrintException("Invalid geoJSON: \n" + geojsonData + ": " + e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
private Class<Geometry> parseGeometryType(@Nonnull final JSONObject featureJson) throws JSONException {
JSONObject geomJson = featureJson.optJSONObject("geometry");
if (geomJson == null) {
return null;
}
String geomTypeString = geomJson.optString("type", "Geometry");
if (geomTypeString.equalsIgnoreCase("Positions")) {
return Geometry.class;
} else {
try {
return (Class<Geometry>) Class.forName("com.vividsolutions.jts.geom." + geomTypeString);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unrecognized geometry type in geojson: " + geomTypeString);
}
}
}
private CoordinateReferenceSystem parseCoordinateReferenceSystem(final JSONObject geojson) {
CoordinateReferenceSystem crs = DefaultEngineeringCRS.GENERIC_2D;
StringBuilder code = new StringBuilder();
try {
if (geojson.has("crs")) {
JSONObject crsJson = geojson.getJSONObject("crs");
if (crsJson.has("type")) {
code.append(crsJson.getString("type"));
}
if (crsJson.has("properties")) {
final JSONObject propertiesJson = crsJson.getJSONObject("properties");
if (propertiesJson.has("code")) {
if (code.length() > 0) {
code.append(":");
}
code.append(propertiesJson.getString("code"));
}
}
}
} catch (JSONException e) {
LOGGER.warn("Error reading the required elements to parse crs of the geojson: \n" + geojson, e);
}
try {
if (code.length() > 0) {
crs = CRS.decode(code.toString(), this.forceLongitudeFirst);
}
} catch (NoSuchAuthorityCodeException e) {
LOGGER.warn("No CRS with code: " + code + ".\nRead from geojson: \n" + geojson);
} catch (FactoryException e) {
LOGGER.warn("Error loading CRS with code: " + code + ".\nRead from geojson: \n" + geojson);
}
return crs;
}
}
| 41.311111 | 130 | 0.639591 |
1a8f1a3845601a82b505a70c45891ba09c0adb87 | 1,807 | /*
* Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* NodeStepException.java
*
* User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
* Created: 3/21/11 6:20 PM
*
*/
package com.dtolabs.rundeck.core.execution.workflow.steps.node;
import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason;
import com.dtolabs.rundeck.core.execution.workflow.steps.StepException;
/**
* Represents an exception when executing a node step
*
* @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a>
*/
public class NodeStepException extends StepException {
private final String nodeName;
public NodeStepException(String s, FailureReason reason, String nodeName) {
super(s, reason);
this.nodeName = nodeName;
}
public NodeStepException(String s, Throwable throwable, FailureReason reason, String nodeName) {
super(s, throwable, reason);
this.nodeName = nodeName;
}
public NodeStepException(Throwable throwable, FailureReason reason, String nodeName) {
super(throwable, reason);
this.nodeName = nodeName;
}
public String getNodeName() {
return nodeName;
}
}
| 31.155172 | 100 | 0.718318 |
f4f33e1f549d8a53fcff984110876eb371e02238 | 2,826 | package com.projectem.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Disposable;
import com.projectem.game.ecs.*;
import com.projectem.game.input.*;
import com.projectem.game.menu.ISceneManager;
import com.projectem.game.render.Renderer;
import com.projectem.game.ui.*;
public class Game implements IUIAcceptor, ICommonInputAcceptor, Disposable {
private final IUIManager uiManager;
private final IPlatformInput inputManager;
private final ISceneManager sceneManager;
private OrthographicCamera camera;
private final float cameraSpeed = 0.25f;
private final float minZoom = 0.5f;
private final float maxZoom = 10f;
public Game (IUIManagerCreator uiCreator, IPlatformInputCreator inputCreator, ISceneManager sceneManager) {
this.uiManager = uiCreator.createUIManager(this);
this.inputManager = inputCreator.createInputManager(this);
this.sceneManager = sceneManager;
}
public void start () {
EntityGod.init();
TransformSystem.init();
SpriteSystem.init();
CellSystem.init();
inputManager.startProcessing();
this.camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Renderer.ins.setCamera(camera);
Entity cell = new Entity("Cell");
TransformSystem.ins.createComponent(cell);
SpriteComponent spriteComponent = (SpriteComponent) SpriteSystem.ins.createComponent(cell);
spriteComponent.setTexture(new Texture(Gdx.files.internal("emptycell.png")));
CellSystem.ins.createComponent(cell);
}
public void logicUpdate () {
TransformSystem.ins.update();
CellSystem.ins.update();
}
public void frameUpdate() {
inputManager.update();
SpriteSystem.ins.update();
}
@Override
public void move(Vector2 direction) {
move(direction, cameraSpeed);
}
@Override
public void move(Vector2 direction, float speed) {
camera.translate(direction.scl((camera.zoom + 1) * camera.viewportWidth * speed * Gdx.graphics.getDeltaTime()));
camera.update();
}
@Override
public void zoom(float amount) {
float nextZoom = camera.zoom + amount * (camera.zoom + 1);
if (nextZoom > minZoom && nextZoom < maxZoom)
{
camera.zoom = nextZoom;
camera.update();
}
}
@Override
public void dispose() {
EntityGod.ins.dispose();
CellSystem.ins.dispose();
SpriteSystem.ins.dispose();
TransformSystem.ins.dispose();
Renderer.ins.setCamera(null);
}
@Override
public void quitToMenu() {
dispose();
sceneManager.openMainMenu();
}
}
| 28.26 | 120 | 0.667728 |
80d6adbbd77f965e0c2c6579ddfad84e10884d9e | 2,543 | package com.blurryworks.fragment.validator.rule.logic;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import com.blurryworks.fragment.validator.ValidationResult;
import com.blurryworks.fragment.validator.engine.ResultStatus;
import com.blurryworks.fragment.validator.engine.ThrowableFunction;
import com.blurryworks.fragment.validator.engine.ValidationRule;
import com.blurryworks.fragment.validator.rule.MaxLength;;
public class MaxLengthLogic extends ValidationRule
{
ThrowableFunction<Object,ValidationResult> validationMethod;
MaxLength maxLengthAnnotation;
public MaxLengthLogic(Annotation validationAnnotation, Field fieldToValidate) throws Exception
{
super(validationAnnotation, fieldToValidate);
maxLengthAnnotation = (MaxLength) validationAnnotation;
if(fieldToValidate.getType().isArray())
{
validationMethod = this::validateArray;
}
else if(Collection.class.isAssignableFrom(fieldToValidate.getType()))
{
validationMethod = this::validateCollection;
}
else if(CharSequence.class.isAssignableFrom(fieldToValidate.getType()))
{
validationMethod = this::validateCharSequence;
}
else
{
throw new Exception("In Class: " + fieldToValidate.getDeclaringClass().getSimpleName() + "Type: " + fieldToValidate.getType().toString() + " validation is not supported by " + validationAnnotation.annotationType().getName());
}
}
@Override
public ValidationResult validate(Object obj) throws Exception
{
if(obj == null)
return null;
return validationMethod.apply(obj);
}
public ValidationResult validateArray(Object obj) throws Exception
{
Object arrayObject = obj;
if(Array.getLength(arrayObject) > maxLengthAnnotation.value() )
return new ValidationResult(ResultStatus.Failure);
return null;
}
public ValidationResult validateCharSequence(Object obj) throws Exception
{
CharSequence charSequenceObject = (CharSequence) obj;
if(charSequenceObject.length() > maxLengthAnnotation.value())
return new ValidationResult(ResultStatus.Failure);
return null;
}
public ValidationResult validateCollection(Object obj) throws Exception
{
Collection<?> setObject = (Collection<?>) obj;
if(setObject.size() > maxLengthAnnotation.value())
return new ValidationResult(ResultStatus.Failure);
return null;
}
@Override
public int getPriority()
{
return 9;
}
}
| 29.917647 | 229 | 0.748722 |
0f452cb55a2311d500d768e69235e91f170719be | 354 | import java.util.*;
/**
* Main for Markov Text Generation Program
*
* @author ola
* @date Jan 12, 2008
*
*/
public class MarkovMain {
public static void main(String[] args) {
IModel model = new MapMarkovModel();
SimpleViewer view = new SimpleViewer("Compsci 201 Markovian Text" +
" Generation", "k count>");
view.setModel(model);
}
}
| 19.666667 | 69 | 0.666667 |
0e4bae33bdbbee50a55ddd19c20323a111f8d23e | 27,912 | import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.ScreenOrientation;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.net.URL;
import java.time.Duration;
import java.util.List;
public class FirstTest {
private AppiumDriver driver;
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "AndroidTestDevice");
capabilities.setCapability("platformVersion", "8.0");
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("appPackage", "org.wikipedia");
capabilities.setCapability("appActivity", ".main.MainActivity");
//capabilities.setCapability("app","/home/demon/GitRepos/mobile_sw_automatiozation_46/apks/org.wikipedia.apk");
capabilities.setCapability("app", "/home/dmitryskalnenkov/GitRepos/mobile_sw_automatiozation_46/apks/org.wikipedia.apk");
//driver = new AndroidDriver(new URL("http://192.168.9.228:4723/wd/hub"), capabilities);
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.rotate(ScreenOrientation.PORTRAIT);
}
@After
public void tearDown() {
driver.quit();
}
@Test
public void firstTest() {
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
waitForElementPresent(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find 'Object-oriented programming language' topic searching by 'Java'",
15
);
System.out.println("First test run");
}
@Test
public void testCancelSearch()
{
waitForElementAndClick(
By.id("org.wikipedia:id/search_container"),
"Cannot find 'Search Wikipedia' input",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
waitForElementAndClear(
By.id("org.wikipedia:id/search_src_text"),
"Cannot find search field",
5
);
waitForElementAndClick(
By.id("org.wikipedia:id/search_close_btn"),
"Cannot find X to cancel search",
5
);
waitForElementNotPresent(
By.id("org.wikipedia:id/search_close_btn"),
"X is still present on the page",
5
);
}
@Test
public void testCompareArticleTitle()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find search input.",
5
);
WebElement title_element = waitForElementPresent(
By.id("org.wikipedia:id/view_page_title_text"),
"Cannot find article title",
15
);
String article_title = title_element.getAttribute("text");
Assert.assertEquals(
"We see unexpected title",
"Java (programming language)",
article_title
);
}
@Test
public void testSearchFieldHasText()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
assertElementHasText(
By.id("org.wikipedia:id/search_src_text"),
"Search…",
"Cannot find 'Search...' text",
5
);
}
@Test
public void testSearchTextAndCancel(){
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Conga",
"Cannot find search input.",
5
);
List resultSearchList = driver.findElements(By.id("org.wikipedia:id/page_list_item_container"));
waitForElementAndClick(
By.id("org.wikipedia:id/search_close_btn"),
"Cannot find X to cancel search",
5
);
waitForElementNotPresent(
By.id("org.wikipedia:id/search_results_container"),
"Search results exist",
5
);
Assert.assertTrue("Count of search result is not more than one",resultSearchList.size() > 1);
}
@Test
public void testCheckSearchResultTitles() {
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
List<WebElement> resultSearchList = driver.findElements(By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_title']"));
for (int i = 0; i < resultSearchList.size(); i++){
String cur_title_article = resultSearchList.get(i).getAttribute("text").toString();
System.out.println(cur_title_article);
Assert.assertTrue("This string doesn't contain word 'Java': " + cur_title_article,
cur_title_article.contains("Java"));
}
}
@Test
public void testSwipeArticle()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Appium",
"Cannot find search input.",
5
);
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_title'][@text='Appium']"),
"Cannot find 'Appium' article in search",
5
);
waitForElementPresent(
By.id("org.wikipedia:id/view_page_title_text"),
"Cannot find article title",
15
);
swipeUpToFindElement(
By.xpath("//*[@text='View page in browser']"),
"Cannot find the end of article",
20
);
}
@Test
public void saveFirstArticleToMyList(){
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find search input.",
5
);
WebElement title_element = waitForElementPresent(
By.id("org.wikipedia:id/view_page_title_text"),
"Cannot find article title",
15
);
waitForElementAndClick(
By.xpath("//android.widget.ImageView[@content-desc='More options']"),
"Cannot find button to open article options",
5
);
waitForElementAndClick(
By.xpath("//*[@text='Add to reading list']"),
"Cannot find options to add article to reading list",
5
);
waitForElementAndClick(
By.id("org.wikipedia:id/onboarding_button"),
"Cannot find 'Got it' tip overlay",
5
);
waitForElementAndClear(
By.id("org.wikipedia:id/text_input"),
"Cannot find input to set name of articles folder",
5
);
String name_of_folder = "Learning programming";
waitForElementAndSendKeys(
By.id("org.wikipedia:id/text_input"),
name_of_folder,
"Cannot put text into articles folder input",
5
);
waitForElementAndClick(
By.xpath("//*[@text='OK']"),
"Cannot press OK button",
5
);
waitForElementAndClick(
By.xpath("//android.widget.ImageButton[@content-desc='Navigate up']"),
"Cannot close article, cannot find X link",
5
);
waitForElementAndClick(
By.xpath("//android.widget.FrameLayout[@content-desc='My lists']"),
"Cannot find navigation button to My lists",
5
);
waitForElementAndClick(
By.xpath("//*[@text='" + name_of_folder + "']"),
"Cannot find created folder",
5
);
swipeElementToLeft(
By.xpath("//*[@text='Java (programming language)']"),
"Cannot find saved article"
);
waitForElementNotPresent(
By.xpath("//*[@text='Java (programming language)']"),
"Cannot delete saved article",
5
);
}
@Test
public void testAmountOfNotEmptySearch()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
String search_line = "Linking Park Discography";
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
search_line,
"Cannot find search input.",
5
);
String search_result_locator = "//*[@resource-id='org.wikipedia:id/search_results_list']//*[@resource-id='org.wikipedia:id/page_list_item_container']";
waitForElementPresent(
By.xpath(search_result_locator),
"Cannot find anything by the request " + search_line,
15
);
int amount_of_search_results = getAmountOfElements(
By.xpath(search_result_locator), 15
);
Assert.assertTrue(
"We've found to few results",
amount_of_search_results > 0
);
}
@Test
public void testAmountOfEmptySearch()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
String search_line = "afsdfafdasgweg";
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
search_line,
"Cannot find search input.",
5
);
String search_result_locator = "//*[@resource-id='org.wikipedia:id/search_results_list']//*[@resource-id='org.wikipedia:id/page_list_item_container']";
String empty_result_label = "//*[@text='No results found']";
waitForElementPresent(
By.xpath(empty_result_label),
"Cannot find empty result label by the request " + search_line,
15
);
assertElementsNotPresent(
By.xpath(search_result_locator),
"We've found some results by request " + search_line
);
}
@Test
public void testChangeScreenOrientationOnSearchResults() {
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
String search_line = "Java";
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
search_line,
"Cannot find search input.",
5
);
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find 'Object-oriented programming language' topic searching by " + search_line,
15
);
String title_before_rotation = waitForElementAndGetAttribute(
By.id("org.wikipedia:id/view_page_title_text"),
"text",
"Cannot find title of article",
15
);
driver.rotate(ScreenOrientation.LANDSCAPE);
String title_after_rotation = waitForElementAndGetAttribute(
By.id("org.wikipedia:id/view_page_title_text"),
"text",
"Cannot find title of article",
15
);
driver.rotate(ScreenOrientation.PORTRAIT);
String title_after_second_rotation = waitForElementAndGetAttribute(
By.id("org.wikipedia:id/view_page_title_text"),
"text",
"Cannot find title of article",
15
);
Assert.assertEquals(
"Article had been changed after screen rotation",
title_before_rotation,
title_after_second_rotation
);
}
@Test
public void testCheckSearchArticleInBackground()
{
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find search input.",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
"Java",
"Cannot find search input.",
5
);
waitForElementPresent(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find search input.",
5
);
driver.runAppInBackground(Duration.ofSeconds(2));
waitForElementPresent(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='Object-oriented programming language']"),
"Cannot find article after returning from background",
15
);
}
@Test
public void saveTwoArticlesToMyListAndDeleteFirst(){
String first_article_title = "Java";
String second_article_title = "Conga";
//Adding first article ('Java') to reading list
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find 'Search Wikipedia' text",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
first_article_title,
"Cannot find search input",
5
);
String expected_article_subject = "Object-oriented programming language";
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='" + expected_article_subject + "']"),
"Cannot find search input",
5
);
waitForElementPresent(
By.id("org.wikipedia:id/view_page_title_text"),
"Cannot find article title",
15
);
waitForElementAndClick(
By.xpath("//android.widget.ImageView[@content-desc='More options']"),
"Cannot find button to open article options",
5
);
waitForElementAndClick(
By.xpath("//*[@text='Add to reading list']"),
"Cannot find options to add article to reading list",
5
);
waitForElementAndClick(
By.id("org.wikipedia:id/onboarding_button"),
"Cannot find 'Got it' tip overlay",
5
);
waitForElementAndClear(
By.id("org.wikipedia:id/text_input"),
"Cannot find input to set name of articles folder",
5
);
String name_of_folder = "My list";
waitForElementAndSendKeys(
By.id("org.wikipedia:id/text_input"),
name_of_folder,
"Cannot put text into articles folder input",
5
);
waitForElementAndClick(
By.xpath("//*[@text='OK']"),
"Cannot press OK button",
5
);
waitForElementAndClick(
By.xpath("//android.widget.ImageButton[@content-desc='Navigate up']"),
"Cannot close article, cannot find X link",
5
);
//Adding second article into 'My list'
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find 'Search Wikipedia' text",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
second_article_title,
"Cannot find search input",
5
);
expected_article_subject = "Cuban drum";
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='" + expected_article_subject + "']"),
"Cannot find search input",
5
);
waitForElementPresent(
By.id("org.wikipedia:id/view_page_title_text"),
"Cannot find article title",
15
);
waitForElementAndClick(
By.xpath("//android.widget.ImageView[@content-desc='More options']"),
"Cannot find button to open article options",
5
);
waitForElementAndClick(
By.xpath("//*[@text='Add to reading list']"),
"Cannot find options to add article to reading list",
5
);
waitForElementAndClick(
By.xpath("//*[@text='"+ name_of_folder + "']"),
"Cannot find list folder with name " + name_of_folder +"\n",
5
);
waitForElementAndClick(
By.xpath("//android.widget.ImageButton[@content-desc='Navigate up']"),
"Cannot close article, cannot find X link",
5
);
///////
waitForElementAndClick(
By.xpath("//android.widget.FrameLayout[@content-desc='My lists']"),
"Cannot find navigation button to My lists",
5
);
waitForElementAndClick(
By.xpath("//*[@text='" + name_of_folder + "']"),
"Cannot find created folder",
5
);
swipeElementToLeft(
By.xpath("//*[contains(@text,'" + first_article_title + "')]"),
"Cannot find saved article"
);
waitForElementNotPresent(
By.xpath("//*[contains(@text,'" + first_article_title + "')]"),
"Cannot delete saved article",
5
);
waitForElementPresent(
By.xpath("//*[contains(@text,'" + second_article_title + "')]"),
"Cannot find the second article which have been added into " + name_of_folder + "\n",
15
);
}
@Test
public void checkTitleElementExist(){
String first_article_title = "Java";
waitForElementAndClick(
By.xpath("//*[contains(@text, 'Search Wikipedia')]"),
"Cannot find 'Search Wikipedia' text",
5
);
waitForElementAndSendKeys(
By.xpath("//*[contains(@text,'Search…')]"),
first_article_title,
"Cannot find search input",
5
);
String expected_article_subject = "Object-oriented programming language";
waitForElementAndClick(
By.xpath("//*[@resource-id='org.wikipedia:id/page_list_item_container']//*[@text='" + expected_article_subject + "']"),
"Cannot find search input",
5
);
String locator = "org.wikipedia:id/view_page_title_text";
boolean element_existence = ifElementExist(
By.id(locator),
"Cannot find article title",
15
);
Assert.assertTrue("The element '" + locator + "' doesn't exist", element_existence);
}
private WebElement waitForElementPresent(By by, String error_message, long timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.withMessage(error_message + "\n");
return wait.until(
ExpectedConditions.presenceOfElementLocated(by)
);
}
private boolean ifElementExist(By by, String error_message, long timeoutInSeconds)
{
int amount_of_elements = getAmountOfElements(by, timeoutInSeconds);
if (amount_of_elements > 0){
System.out.println("Amount of elements is " + amount_of_elements);
return true;
}
else{
System.out.println("Amount of elements is " + amount_of_elements);
return false;
}
}
private WebElement waitForElementPresent(By by, String error_message)
{
return waitForElementPresent(by, error_message, 5);
}
private WebElement waitForElementAndClick(By by, String error_message, long timeoutInSeconds)
{
WebElement element = waitForElementPresent(by, error_message, timeoutInSeconds);
element.click();
return element;
}
private WebElement waitForElementAndSendKeys(By by, String value, String error_message, long timeoutInSeconds)
{
WebElement element = waitForElementPresent(by, error_message, timeoutInSeconds);
element.sendKeys(value);
return element;
}
private boolean waitForElementNotPresent(By by, String error_message, long timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.withMessage(error_message + '\n');
return wait.until(
ExpectedConditions.invisibilityOfElementLocated(by)
);
}
private WebElement waitForElementAndClear(By by, String error_message, long timeoutInSeconds)
{
WebElement element = waitForElementPresent(by, error_message, timeoutInSeconds);
element.clear();
return element;
}
private String assertElementHasText(By by, String expected_text, String error_message, long timeoutInSeconds)
{
WebElement element = waitForElementPresent(by, error_message, timeoutInSeconds);
String actual_text = element.getAttribute("text");
Assert.assertEquals(
"We see unexpected text",
expected_text,
actual_text
);
return actual_text;
}
protected void swipeUp(int timeOfSwipe)
{
TouchAction action = new TouchAction(driver);
Dimension size = driver.manage().window().getSize();
int x = size.width / 2;
int start_y = (int) (size.height * 0.8);
int end_y = (int) (size.height * 0.2);
Duration duration_of_swipe = Duration.ofMillis(timeOfSwipe);
PointOption start_point = PointOption.point(x, start_y);
PointOption end_point = PointOption.point(x, end_y);
action.press(start_point).waitAction(WaitOptions.waitOptions(duration_of_swipe)).moveTo(end_point).release().perform();
}
protected void swipeUpQuick()
{
swipeUp(200);
}
protected void swipeUpToFindElement(By by, String error_message, int max_swipes)
{
int already_swiped = 0;
while (driver.findElements(by).size() == 0){
if (already_swiped > max_swipes){
waitForElementPresent(by, "Cannot find element by swiping up. \n" + error_message, 0);
return;
}
swipeUpQuick();
++already_swiped;
}
}
protected void swipeElementToLeft(By by, String error_message)
{
WebElement element = waitForElementPresent(
by,
error_message,
10);
int left_x = element.getLocation().getX();
int right_x = left_x + element.getSize().getWidth();
int upper_y = element.getLocation().getY();
int lower_y = upper_y + element.getSize().getHeight();
int middle_y = (upper_y + lower_y) / 2;
PointOption start_point = PointOption.point(right_x, middle_y);
PointOption finish_point = PointOption.point(left_x, middle_y);
WaitOptions wait_duration_of_swipe = WaitOptions.waitOptions(Duration.ofMillis(300));
TouchAction action = new TouchAction(driver);
action
.press(start_point)
.waitAction(wait_duration_of_swipe)
.moveTo(finish_point)
.release()
.perform();
}
private int getAmountOfElements(By by, long timeoutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
List elements = driver.findElements(by);
return elements.size();
}
private void assertElementsNotPresent(By by, String error_message)
{
int amount_of_elements = getAmountOfElements(by, 15);
if (amount_of_elements > 0) {
String default_message = "An element '" + by.toString() + "' supposed to be not present";
throw new AssertionError(default_message + " " + error_message);
}
}
private String waitForElementAndGetAttribute(By by, String attribute, String error_message, long timeoutInSeconds)
{
WebElement element = waitForElementPresent(by, error_message, timeoutInSeconds);
return element.getAttribute(attribute);
}
}
| 33.268176 | 159 | 0.549334 |
98a88d893aacda2f9610103b451097108c5666b9 | 13,520 | // Copyright 2021, Justen Walker
// SPDX-License-Identifier: Apache-2.0
package tech.justen.concord.goodwill.task;
import com.walmartlabs.concord.ApiClient;
import com.walmartlabs.concord.client.ApiClientConfiguration;
import com.walmartlabs.concord.client.ApiClientFactory;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.justen.concord.goodwill.*;
import tech.justen.concord.goodwill.service.*;
import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ExecutorService;
import static java.lang.String.format;
import static tech.justen.concord.goodwill.DockerContainer.DEFAULT_WORK_DIR;
public class TaskCommon {
private static final Logger log = LoggerFactory.getLogger(TaskCommon.class);
private static final Logger processLog = LoggerFactory.getLogger("processLog");
private static final String MAGIC_VALUE = "d0c08ee0-a663-4a6b-ad5e-00a5fca1e5cf";
private final TaskConfig config;
private final TaskParams params;
private final DependencyManager dependencyManager;
private final DockerService dockerService;
private final ContextService contextService;
private final SecretService secretService;
private final ExecutorService executor;
private final LockService lockService;
private final ApiClientConfiguration apiClientConfig;
private final ApiClientFactory apiClientFactory;
public TaskCommon(
TaskConfig config,
TaskParams params,
DependencyManager dependencyManager,
ContextService executionService,
DockerService dockerService,
SecretService secretService,
LockService lockService,
ExecutorService executor,
ApiClientConfiguration apiClientConfig,
ApiClientFactory apiClientFactory) {
this.config = config;
this.params = params;
this.dependencyManager = dependencyManager;
this.contextService = executionService;
this.lockService = lockService;
this.dockerService = dockerService;
this.secretService = secretService;
this.executor = executor;
this.apiClientConfig = apiClientConfig;
this.apiClientFactory = apiClientFactory;
}
public ApiClient getSessionClient() {
return apiClientFactory.create(apiClientConfig);
}
public String compileInDocker() throws java.lang.Exception {
log.info("Compiling goodwill binary in Docker");
Path goodwillContainerBinPath = Paths.get(DEFAULT_WORK_DIR, params.getBuildDirectory(), "goodwill");
Path goodwillBinPath = Paths.get(config.workingDirectory().toString(), params.getBuildDirectory(), "goodwill");
File goodwillBin = goodwillBinPath.toFile();
if (!goodwillBin.exists()) {
String binClasspath = params.getBinaryClasspath();
try (InputStream link = (getClass().getResourceAsStream(binClasspath))) {
Files.copy(link, goodwillBin.getAbsoluteFile().toPath());
}
}
if (!goodwillBin.canExecute()) {
goodwillBin.setExecutable(true);
}
Map<String, String> env = new HashMap<>();
env.put("GOROOT", "/usr/local/go");
params.setGoEnvironment(env);
Path out = Paths.get(DEFAULT_WORK_DIR, params.getTasksBinary());
DockerContainer container = new DockerContainer();
container.entryPoint = goodwillContainerBinPath.toString();
List<String> cmd = new ArrayList<>();
cmd.add(goodwillBin.toString());
cmd.add("-os");
cmd.add(params.getGoOS());
cmd.add("-arch");
cmd.add(params.getGoArch());
if (params.debug) {
cmd.add("-debug");
}
cmd.add("-dir");
cmd.add(DEFAULT_WORK_DIR);
cmd.add("-out");
cmd.add(out.toString());
container.command = cmd;
container.image = params.getGoDockerImage();
container.env = env;
container.workDir = DEFAULT_WORK_DIR;
container.debug = params.debug;
int result = dockerService.start(container, line -> {
processLog.info("DOCKER: {}", line);
}, line -> {
processLog.info("DOCKER: {}", line);
});
if (result != 0) {
throw new RuntimeException("goodwill exited unsuccessfully. See output logs for details.");
}
return Paths.get(config.workingDirectory().toString(), params.getTasksBinary()).toString();
}
public String compileOnHost() throws java.lang.Exception {
log.info("Compiling goodwill binary on the agent");
String os = params.getGoOS();
String arch = params.getGoArch();
File goodwillBin = params.getBinaryOutPath(config.workingDirectory()).toFile();
if (!goodwillBin.exists()) {
String binClasspath = params.getBinaryClasspath();
try (InputStream link = (getClass().getResourceAsStream(binClasspath))) {
Files.copy(link, goodwillBin.getAbsoluteFile().toPath());
}
}
if (!goodwillBin.canExecute()) {
if (!goodwillBin.setExecutable(true)) {
throw new RuntimeException("Cannot make set executable bit");
}
}
File out = new File(config.workingDirectory().toString(), params.getTasksBinary());
Map<String, String> env = new HashMap<>();
if (params.installGo) {
Path goRoot = installGo();
String path = System.getenv("PATH");
env.put("PATH", path + File.pathSeparatorChar + Paths.get(goRoot.toString(), "bin").toString());
env.put("GOROOT", goRoot.toString());
}
List<String> cmd = new ArrayList<>();
cmd.add(goodwillBin.toString());
cmd.add("-os");
cmd.add(os);
cmd.add("-arch");
cmd.add(arch);
if (params.debug) {
cmd.add("-debug");
}
cmd.add("-dir");
cmd.add(config.workingDirectory().toString());
cmd.add("-out");
cmd.add(out.toString());
exec(env, cmd.toArray(new String[0]));
return out.toString();
}
public Map<String, Object> execute() throws java.lang.Exception {
Path workDir = config.workingDirectory();
File goodwillDir = new File(workDir.toString(), params.getBuildDirectory());
goodwillDir.mkdir();
File goodwillBin = new File(workDir.toString(), params.getTasksBinary());
if (!goodwillBin.exists()) {
String commandPath;
log.debug("Goodwill binary {} does not exist", goodwillBin.toString());
if (params.useDockerImage) {
commandPath = compileInDocker();
} else {
commandPath = compileOnHost();
}
goodwillBin = new File(commandPath);
if (!goodwillBin.exists()) {
log.error("Goodwill binary {} does not exist", goodwillBin.toString());
throw new RuntimeException("Goodwill binary did not exist after compilation");
}
}
String taskName = params.getTask();
boolean v = goodwillBin.setExecutable(true);
Server server = null;
CertUtils.CA ca = CertUtils.generateCA();
InputStream caCert = ca.getCACertInputStream();
InputStream caKey = ca.getCAKeyInputStream();
File caFile = new File(goodwillDir, "ca.crt");
File certFile = new File(goodwillDir, "client.crt");
File keyFile = new File(goodwillDir, "client.key");
ca.generatePKI(caFile, certFile, keyFile);
Map<String, Object> taskResult = new HashMap<>();
try {
ApiClient apiClient = apiClientFactory.create(apiClientConfig);
int port = 0;
long sleepMillis = 0;
IOException startException = null;
for (int i = 0; i < 10; i++) {
Thread.sleep(sleepMillis);
try {
port = randomPort();
server = ServerBuilder.forPort(port)
.useTransportSecurity(caCert, caKey)
.addService(new GrpcDockerService(dockerService))
.addService(new GrpcConfigService(apiClientConfig, config))
.addService(new GrpcContextService(contextService, taskResult))
.addService(new GrpcSecretService(config, secretService, apiClient))
.addService(new GrpcLockService(lockService))
.build();
server.start();
startException = null;
} catch (IOException e) {
startException = e;
sleepMillis = i * 1000;
port = 0;
log.warn("GRPC service failed to start on port {}, trying again in {} ms", port, sleepMillis);
continue;
}
break;
}
if (startException != null) {
log.error("GRPC Service failed to start,");
throw startException;
}
Map<String, String> env = new HashMap<>();
env.put("GRPC_ADDR", format(":%d", port));
env.put("GRPC_MAGIC_KEY", MAGIC_VALUE);
env.put("GRPC_CA_CERT_FILE", caFile.getAbsolutePath());
env.put("GRPC_CLIENT_CERT_FILE", certFile.getAbsolutePath());
env.put("GRPC_CLIENT_KEY_FILE", keyFile.getAbsolutePath());
env.put("CONCORD_ORG_NAME", config.orgName());
env.put("CONCORD_PROCESS_ID", config.processId());
env.put("CONCORD_WORKING_DIRECTORY", config.workingDirectory().toString());
env.put("GOODWILL_SERVER_VERSION", BuildInfo.getVersion());
params.setGoEnvironment(env);
log.info("======== BEGIN GOODWILL TASK: {} ========", taskName);
exec(env, goodwillBin.toString(), taskName);
log.info("======== END GOODWILL TASK: {} ========", taskName);
} catch (IOException e) {
if (e.getMessage().contains("Cannot run program") && goodwillBin.exists()) {
log.error("Could not run goodwill tasks binary. "
+ "This could mean the binary was compiled for a different architecture "
+ "or linked against a different libc than the platform supports.");
}
throw e;
} finally {
if (server != null) {
server.shutdown();
}
}
return taskResult;
}
private int randomPort() {
SecureRandom s = new SecureRandom();
return 49152 + s.nextInt(65535 - 49152);
}
private void exec(Map<String, String> env, String... command) throws IOException, InterruptedException {
Path workDir = config.workingDirectory();
ProcessBuilder pb = new ProcessBuilder();
pb.command(command);
if (env != null) {
for (Map.Entry<String, String> e : env.entrySet()) {
pb.environment().put(e.getKey(), e.getValue());
}
}
pb.directory(workDir.toFile());
String commandString = String.join(" ", pb.command());
log.debug("Exec Goodwill Task: [{}]", commandString);
Process p = pb.start();
executor.execute(() -> {
try (BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = stdout.readLine()) != null) {
processLog.info(line);
}
} catch (IOException e) {
log.error("error reading stdout", e);
}
});
executor.execute(() -> {
try (BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
String line;
while ((line = stderr.readLine()) != null) {
processLog.warn(line);
}
} catch (IOException e) {
log.error("error reading stderr", e);
}
});
int rc = p.waitFor();
if (rc != 0) {
log.warn("call ['{}'] -> finished with code {}",
commandString, rc);
throw new RuntimeException("goodwill command failed");
}
}
private Path installGo() throws IOException {
String version = params.getGoVersion();
Path workDir = config.workingDirectory();
Path goRootDir = Paths.get(workDir.toString(), params.getBuildDirectory(), "go");
File goInstall = Paths.get(workDir.toString(), params.getBuildDirectory(), "go", "bin", "go").toFile();
if (goInstall.canExecute()) {
log.info("Go already installed at {}", goInstall.toString());
return goRootDir;
}
log.info("Installing Go {}", version);
Path tar = dependencyManager.resolve(URI.create(params.getGoDownloadURL(version)));
TarUtils.extractTarball(tar, Paths.get(workDir.toString(), params.getBuildDirectory()));
log.info("Go installed at {}", goInstall.toString());
return goRootDir;
}
}
| 40.845921 | 119 | 0.591568 |
ce9300fa0eb26245077740810b7acf0dd5fca9bc | 251 | interface List{
boolean isEmpty();
boolean isFull();
boolean isFound(int e);//search an element from the list
void insertItem(int e);//insert an element on the desired position
boolean remove(int e);//remove the specified element
void clear();
} | 31.375 | 67 | 0.749004 |
af6a909351ae993458d115212ac315d633321361 | 1,777 | package com.pdffiller.client.api;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.pdffiller.client.PdfFillerAPIClient;
import com.pdffiller.client.dto.DocumentInfo;
import com.pdffiller.client.dto.DocumentListResponse;
import com.pdffiller.client.dto.DocumentUploadRequest;
import com.pdffiller.client.exception.PdfFillerAPIException;
public class DocumentApiTest {
private PdfFillerAPIClient apiClient;
private Document api;
private DocumentInfo documentCreateResponse;
@Before
public void setUp() throws Exception {
apiClient = new PdfFillerAPIClient
.Builder("CLIENT_ID","CLIENT_SECRET")
.build();
api = new Document(apiClient);
}
@Test
public void uploadDocumentTest() throws PdfFillerAPIException {
String sampleFile = "http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf";
DocumentUploadRequest body = new DocumentUploadRequest();
body.setFile(sampleFile);
documentCreateResponse = api.createDocumentTemplate(body);
assertTrue(documentCreateResponse.getId() != null);
}
@Test
public void uploadDocumentMultipartTest() throws PdfFillerAPIException {
String sampleFile = "/home/srg_kas/projects/Testing/data/test.pdf";
documentCreateResponse = api.createDocumentMultipart(sampleFile);
assertTrue(documentCreateResponse.getId() != null);
}
@Test
public void getDocumentInfoTest() throws PdfFillerAPIException {
DocumentInfo response = api.getDocumentInfo(123456);
assertTrue(response.getId() != null);
}
@Test
public void getDocumentList() throws PdfFillerAPIException {
DocumentListResponse response = api.retrieveDocumentList();
assertTrue(response.getTotal() != null);
}
}
| 32.309091 | 101 | 0.760833 |
961952abed2b1fdbfe983eea8fce921939a23d65 | 708 | package subarray;
import org.junit.Assert;
import org.junit.Test;
/**
* @author LiDaQian
*/
public class FindMaximumSubArrayTest {
@Test
public void testFind() {
int[] array1 = new int[] {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, -7};
int[] array2 = new int[] {13, 20, 18, 20, 24, 54, 56};
SubArray rightSubArray1 = new SubArray(7, 10, 43);
SubArray rightSubArray2 = new SubArray(0, 6, 205);
SubArray subArray1 = FindMaximumSubArray.find(array1);
SubArray subArray2 = FindMaximumSubArray.find(array2);
Assert.assertEquals(rightSubArray1, subArray1);
Assert.assertEquals(rightSubArray2, subArray2);
}
}
| 27.230769 | 102 | 0.625706 |
c2d9aa4125837fb18f1ea879f52668e33658a44c | 1,163 | package com.stackroute.quizify.recommendationservice.controller;
import com.stackroute.quizify.recommendationservice.domain.LikesGame;
import com.stackroute.quizify.recommendationservice.service.LikesGameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/rest/neo4j/likesgame")
public class LikesGameController {
LikesGameService likesGameService;
@Autowired
public LikesGameController(LikesGameService likesGameService) {
this.likesGameService = likesGameService;
}
@GetMapping("/")
public List<LikesGame> getAll(){
return likesGameService.getAllRelationships();
}
@PostMapping("/")
public LikesGame create(@RequestParam("userId") long userId, @RequestParam("gameId") long gameId){
return likesGameService.createRelationship(userId, gameId);
}
@DeleteMapping("/")
public LikesGame delete(@RequestParam("userId") long userId, @RequestParam("gameId") long gameId){
return likesGameService.deleteRelationship(userId, gameId);
}
}
| 29.820513 | 102 | 0.759243 |
6c8dd5ecbbd50de18dc7b026db350ed1296eae77 | 1,256 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.EnumComboBoxModel;
import com.intellij.ui.SimpleListCellRenderer;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public final class PresentableEnumUtil {
private PresentableEnumUtil() {}
public static <T extends Enum<T> & PresentableEnum> JComboBox<T> fill(JComboBox<T> comboBox, Class<T> enumClass) {
comboBox.setModel(new EnumComboBoxModel<>(enumClass));
comboBox.setRenderer(new PresentableEnumCellRenderer<>());
return comboBox;
}
public static <T extends Enum<T> & PresentableEnum> ComboBox<T> fill(ComboBox<T> comboBox, Class<T> enumClass) {
comboBox.setModel(new EnumComboBoxModel<>(enumClass));
comboBox.setRenderer(new PresentableEnumCellRenderer<>());
return comboBox;
}
}
class PresentableEnumCellRenderer<T extends Enum<T> & PresentableEnum> extends SimpleListCellRenderer<T> {
@Override
public void customize(@NotNull JList<? extends T> list, T value, int index, boolean selected, boolean hasFocus) {
setText(value.getPresentableText());
}
} | 39.25 | 140 | 0.763535 |
37ab728d35ea53a8d6f0b0826a728623eed026a5 | 1,014 | package com.mobwal.home.models.db;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import com.mobwal.home.R;
public class Setting {
public Setting() {
id = UUID.randomUUID().toString();
}
public String id;
public String c_key;
public String c_value;
public String f_route;
public String toKeyName(@NotNull Context context) {
switch (c_key) {
case "geo":
return context.getString(R.string.location);
case "geo_quality":
return context.getString(R.string.geo_quality);
case "image":
return context.getString(R.string.attach);
case "image_quality":
return context.getString(R.string.image_quality);
case "image_height":
return context.getString(R.string.image_height);
default:
return context.getString(R.string.params);
}
}
}
| 22.043478 | 66 | 0.598619 |
32111ce8e15f5697dadc3f04e66cf6a2194036c2 | 1,237 | package com.lyx.study.helloworld;
public class Helloworld {
public static void main(String[] var0) {
System.out.print("hello world\n");
byte var1 = 1;
System.out.println(var1);
byte var2 = 2;
System.out.println(var2);
byte var3 = 3;
byte var4 = 4;
System.out.println(var3);
System.out.println(var4);
byte var5 = 5;
byte var6 = 6;
System.out.println(var5);
System.out.println(var6);
byte var7 = 7;
byte var8 = 8;
System.out.println(var7);
System.out.println(var8);
boolean var10 = true;
boolean var11 = false;
System.out.println(var10);
System.out.println(var11);
char var13 = 'a';
System.out.println(var13);
float var15 = 0.1F;
System.out.println(var15);
double var17 = 0.1D;
System.out.println(var17);
long var21 = 1L;
System.out.println(var21);
long var25 = 1L;
System.out.println(var25);
byte var27 = 1;
System.out.println(var27);
byte var29 = 1;
System.out.println(var29);
byte var30 = 127;
System.out.println(var30 + 2);
}
}
| 26.891304 | 44 | 0.542441 |
7614e925d51d0978783af382b5b3c45db491211a | 18,196 | /* OpenRemote, the Home of the Digital Home.
* Copyright 2008-2011, OpenRemote Inc.
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openremote.modeler.client.widget.buildingmodeler;
import java.util.ArrayList;
import java.util.List;
import org.openremote.ir.domain.CodeSetInfo;
import org.openremote.ir.domain.IRCommandInfo;
import org.openremote.modeler.client.rpc.AsyncServiceFactory;
import org.openremote.modeler.client.widget.CommonForm;
import org.openremote.modeler.irfileparser.BrandInfo;
import org.openremote.modeler.irfileparser.DeviceInfo;
import org.openremote.modeler.shared.dto.DeviceDTO;
import org.openremote.modeler.shared.ir.IRServiceException;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FormEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Padding;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridView;
import com.extjs.gxt.ui.client.widget.grid.GridViewConfig;
import com.extjs.gxt.ui.client.widget.layout.CenterLayout;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout.HBoxLayoutAlign;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* IR File Command Import Form.
*
*/
public class IRFileImportForm extends CommonForm {
/** The device. */
protected DeviceDTO device = null;
/** The select container. */
private LayoutContainer selectContainer = new LayoutContainer();
/** The command container. */
private LayoutContainer commandContainer = new LayoutContainer();
/** The next button. */
protected Button nextButton;
/** The code grid. */
protected Grid<BeanModel> codeGrid = null;
private ColumnModel cm = null;
protected ListStore<BeanModel> brandInfos = null;
protected ComboBox<BeanModel> brandInfoList = null;
protected ListStore<BeanModel> deviceInfos = null;
protected ComboBox<BeanModel> deviceInfoList = null;
protected ListStore<BeanModel> codeSetInfos = null;
protected ComboBox<BeanModel> codeSetInfoList = null;
ListStore<BeanModel> listStore;
protected IRFileImportWindow wrapper;
private String irServiceRootRestURL;
private String prontoFileHandle;
/**
* Instantiates a new iR command file import form.
*
* @param wrapper
* the wrapper
* @param deviceBeanModel
* the device bean model
*/
public IRFileImportForm(final IRFileImportWindow wrapper, BeanModel deviceBeanModel) {
super();
setHeight(500);
this.wrapper = wrapper;
setLayout(new RowLayout(Orientation.VERTICAL));
HBoxLayout selectContainerLayout = new HBoxLayout();
selectContainerLayout.setPadding(new Padding(5));
selectContainerLayout.setHBoxLayoutAlign(HBoxLayoutAlign.TOP);
selectContainer.setLayout(selectContainerLayout);
selectContainer.setLayoutOnChange(true);
add(selectContainer, new RowData(1, 35));
commandContainer.setLayout(new CenterLayout());
commandContainer.setLayoutOnChange(true);
add(commandContainer, new RowData(1, 1));
device = (DeviceDTO) deviceBeanModel.getBean();
cleanBrandComboBox();
cleanCodeGrid();
cleanCodeSetComboBox();
cleanDeviceComboBox();
onSubmit(wrapper);
}
/**
* On submit.
*
* @param wrapper
* the wrapper
*/
protected void onSubmit(final Component wrapper) {
addListener(Events.BeforeSubmit, new Listener<FormEvent>() {
public void handleEvent(FormEvent be) {
}
});
}
@Override
protected void addButtons() {
nextButton = new Button("Next");
nextButton.setEnabled(false);
nextButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
IRFileImportToProtocolForm protocolChooserForm = new IRFileImportToProtocolForm(wrapper, irServiceRootRestURL, prontoFileHandle, device);
protocolChooserForm.setSelectedFunctions(codeGrid.getSelectionModel().getSelectedItems());
protocolChooserForm.setVisible(true);
protocolChooserForm.show();
}
});
addButton(nextButton);
}
/**
* populates and shows the brand combo box
*/
public void showBrands() {
AsyncServiceFactory.getIRRPCServiceAsync().getBrands(prontoFileHandle, new AsyncCallback<ArrayList<String>>() {
@Override
public void onSuccess(ArrayList<String> brands) {
if (brandInfos == null) {
brandInfos = new ListStore<BeanModel>();
brandInfoList = new ComboBox<BeanModel>();
brandInfoList.setEmptyText("Please select Brand...");
brandInfoList.setDisplayField("brandName");
brandInfoList.setWidth(150);
brandInfoList.setStore(brandInfos);
brandInfoList.setTriggerAction(TriggerAction.ALL);
brandInfoList.setEditable(false);
selectContainer.add(brandInfoList);
setStyleOfComboBox(brandInfoList);
brandInfoList.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
@Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
showDevices((BrandInfo) se.getSelectedItem().getBean());
}
});
} else {
cleanCodeGrid();
cleanDeviceComboBox();
cleanCodeSetComboBox();
cleanBrandComboBox();
}
BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(BrandInfo.class);
for (String brandName : brands) {
brandInfos.add(beanModelFactory.createModel(new BrandInfo(brandName)));
}
brandInfoList.setVisible(true);
}
@Override
public void onFailure(Throwable caught) {
if (caught instanceof IRServiceException) {
wrapper.setErrorMessage(caught.getLocalizedMessage());
} else {
wrapper.setErrorMessage("Error connecting to server");
}
}
});
}
/**
* populates and shows the devices combobox for the currently selected brand
*
* @param brandInfo
*/
private void showDevices(final BrandInfo brandInfo) {
AsyncServiceFactory.getIRRPCServiceAsync().getDevices(prontoFileHandle, brandInfo.getBrandName(), new AsyncCallback<ArrayList<String>>() {
@Override
public void onSuccess(ArrayList<String> devices) {
if (deviceInfos == null) {
deviceInfos = new ListStore<BeanModel>();
deviceInfoList = new ComboBox<BeanModel>();
deviceInfoList.setEmptyText("Please select Device...");
deviceInfoList.setDisplayField("modelName");
deviceInfoList.setWidth(150);
deviceInfoList.setStore(deviceInfos);
deviceInfoList.setTriggerAction(TriggerAction.ALL);
deviceInfoList.setEditable(false);
selectContainer.add(deviceInfoList);
setStyleOfComboBox(deviceInfoList);
deviceInfoList.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
@Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
showCodeSets((DeviceInfo) se.getSelectedItem().getBean());
}
});
} else {
cleanCodeGrid();
cleanCodeSetComboBox();
cleanDeviceComboBox();
}
BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(DeviceInfo.class);
for (String deviceName : devices) {
deviceInfos.add(beanModelFactory.createModel(new DeviceInfo(brandInfo, deviceName)));
}
deviceInfoList.setVisible(true);
}
@Override
public void onFailure(Throwable caught) {
if (caught instanceof IRServiceException) {
wrapper.setErrorMessage(caught.getLocalizedMessage());
} else {
wrapper.setErrorMessage("Error connecting to server");
}
}
});
}
/**
* populates and shows the code set combo box for the currently selected
* device
*
* @param device
*/
private void showCodeSets(final DeviceInfo device) {
AsyncServiceFactory.getIRRPCServiceAsync().getCodeSets(prontoFileHandle, device.getBrandInfo().getBrandName(), device.getModelName(), new AsyncCallback<ArrayList<CodeSetInfo>>() {
@Override
public void onSuccess(ArrayList<CodeSetInfo> codeSets) {
if (codeSetInfos == null) {
codeSetInfos = new ListStore<BeanModel>();
codeSetInfoList = new ComboBox<BeanModel>();
codeSetInfoList.setEmptyText("Please select CodeSet...");
codeSetInfoList.setDisplayField("index");
codeSetInfoList.setSimpleTemplate("{category}");
codeSetInfoList.setWidth(150);
codeSetInfoList.setStore(codeSetInfos);
codeSetInfoList.setTriggerAction(TriggerAction.ALL);
codeSetInfoList.setEditable(false);
selectContainer.add(codeSetInfoList);
setStyleOfComboBox(codeSetInfoList);
codeSetInfoList.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
@Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
showGrid((CodeSetInfo) se.getSelectedItem().getBean());
codeSetInfoList.setRawValue(((CodeSetInfo)se.getSelectedItem().getBean()).getCategory());
}
});
} else {
cleanCodeGrid();
cleanCodeSetComboBox();
}
BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(org.openremote.modeler.irfileparser.CodeSetInfo.class);
for (CodeSetInfo codeSet : codeSets) {
codeSetInfos.add(beanModelFactory.createModel(new org.openremote.modeler.irfileparser.CodeSetInfo(codeSet)));
}
codeSetInfoList.setVisible(true);
}
@Override
public void onFailure(Throwable caught) {
if (caught instanceof IRServiceException) {
wrapper.setErrorMessage(caught.getLocalizedMessage());
} else {
wrapper.setErrorMessage("Error connecting to server");
}
}
});
}
/**
* show the Ir commands from the currently selected code set
*
* @param selectedItem
*/
private void showGrid(final CodeSetInfo selectedItem) {
AsyncServiceFactory.getIRRPCServiceAsync().getIRCommands(prontoFileHandle, selectedItem.getDeviceInfo().getBrandInfo().getBrandName(),
selectedItem.getDeviceInfo().getModelName(), selectedItem.getIndex(), new AsyncCallback<ArrayList<IRCommandInfo>>() {
@Override
public void onSuccess(ArrayList<IRCommandInfo> irCommands) {
if (listStore == null) {
listStore = new ListStore<BeanModel>();
} else {
listStore.removeAll();
}
if (cm == null) {
List<ColumnConfig> codeGridColumns = new ArrayList<ColumnConfig>();
codeGridColumns.add(new ColumnConfig("name", "Name", 120));
codeGridColumns.add(new ColumnConfig("originalCode", "Original Code", 250));
codeGridColumns.add(new ColumnConfig("comment", "Comment", 250));
cm = new ColumnModel(codeGridColumns);
}
if (codeGrid == null) {
codeGrid = new Grid<BeanModel>(listStore, cm);
GridView gv = new GridView();
codeGrid.setView(gv);
// invalid code lines are rendered in red
gv.setViewConfig(new GridViewConfig() {
@Override
public String getRowStyle(ModelData model, int rowIndex, ListStore<ModelData> ds) {
if (model != null) {
if (model.get("code") == null) {
return "row-invalid_file_imported_code";
} else {
return "";
}
} else {
return "";
}
}
});
codeGrid.setLoadMask(true);
codeGrid.setHeight(400);
codeGrid.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
// if trying to select invalid line,
// remove it from selection
@Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
List<BeanModel> selectedItems = se.getSelection();
for (BeanModel bm : selectedItems) {
IRCommandInfo irCommandInfo = bm.getBean();
if (irCommandInfo.getCode() == null) {
codeGrid.getSelectionModel().deselect(bm);
}
}
if (codeGrid.getSelectionModel().getSelectedItems().size() > 0) {
nextButton.setEnabled(true);
} else {
nextButton.setEnabled(false);
}
}
});
commandContainer.add(codeGrid);
} else {
codeGrid.getStore().removeAll();
}
BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(org.openremote.modeler.irfileparser.IRCommandInfo.class);
for (IRCommandInfo irCommand : irCommands) {
codeGrid.getStore().add(beanModelFactory.createModel(new org.openremote.modeler.irfileparser.IRCommandInfo(irCommand.getName(), irCommand.getCode(), irCommand.getOriginalCode(), irCommand.getComment(), selectedItem)));
}
wrapper.unmask();
}
@Override
public void onFailure(Throwable caught) {
if (caught instanceof IRServiceException) {
wrapper.setErrorMessage(caught.getLocalizedMessage());
} else {
wrapper.setErrorMessage("Error connecting to server");
}
}
});
}
/**
* Hides the combobox and clean the grid
*/
public void hideComboBoxes() {
if (brandInfoList != null) {
brandInfoList.setVisible(false);
}
if (deviceInfoList != null) {
deviceInfoList.setVisible(false);
}
if (codeSetInfoList != null) {
codeSetInfoList.setVisible(false);
}
cleanCodeGrid();
}
/**
* cleans the grid
*/
private void cleanCodeGrid() {
if (codeGrid != null) {
codeGrid.getSelectionModel().deselectAll();
codeGrid.removeFromParent();
codeGrid.removeAllListeners();
nextButton.setEnabled(false);
codeGrid = null;
}
}
/**
* cleans the device combobox
*/
private void cleanDeviceComboBox() {
if (deviceInfos != null) {
deviceInfos.removeAll();
deviceInfoList.clearSelections();
deviceInfoList.getStore().removeAll();
}
}
/**
* cleans the code set combo box
*/
private void cleanCodeSetComboBox() {
if (codeSetInfos != null) {
codeSetInfos.removeAll();
codeSetInfoList.clearSelections();
codeSetInfoList.getStore().removeAll();
}
}
/**
* cleans the brand combo box
*/
private void cleanBrandComboBox() {
if (brandInfos != null) {
brandInfoList.clearSelections();
brandInfos.removeAll();
}
}
/**
* Sets the style of combo box.
*
* @param box
* the new style of combo box
*/
private void setStyleOfComboBox(ComboBox<?> box) {
box.setWidth(170);
box.setMaxHeight(250);
}
public void setProntoFileHandle(String prontoFileHandle) {
this.prontoFileHandle = prontoFileHandle;
}
public void setIrServiceRootRestURL(String irServiceRootRestURL) {
this.irServiceRootRestURL = irServiceRootRestURL;
}
}
| 36.61167 | 229 | 0.640415 |
7bc3b5925a5b4552571a78c65d89ad67dbd3d66e | 2,438 | package sh.isaac.provider.elk;
//import org.junit.jupiter.api.Test;
//import org.semanticweb.elk.owlapi.ElkReasonerFactory;
//import org.semanticweb.owlapi.apibinding.OWLManager;
//import org.semanticweb.owlapi.model.*;
//import org.semanticweb.owlapi.reasoner.InferenceType;
//import org.semanticweb.owlapi.reasoner.OWLReasoner;
//import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import java.io.File;
import static org.junit.jupiter.api.Assertions.*;
class ExampleTest {
/*
@Test
void incrementalClassify() {
System.out.println(System.getProperty("user.dir"));
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
try {
// Load your ontology
//OWLOntology ont = manager.loadOntologyFromOntologyDocument(new File("src/test/resources/bevon-0.8.owl"));
OWLOntology ont = manager.loadOntologyFromOntologyDocument(new File("src/test/resources/RDF/OpenGALEN8_CRM.owl"));
// Create an ELK reasoner.
OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ont);
// Classify the ontology.
reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
OWLDataFactory factory = manager.getOWLDataFactory();
OWLClass subClass = factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#AbsoluteShapeState"));
//OWLAxiom removed = factory.getOWLSubClassOfAxiom(subClass, factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#ShapeState")));
OWLAxiom added = factory.getOWLSubClassOfAxiom(subClass, factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#GeneralisedStructure")));
// Remove an existing axiom, add a new axiom
manager.addAxiom(ont, added);
//manager.removeAxiom(ont, removed);
// This is a buffering reasoner, so you need to flush the changes
reasoner.flush();
// Re-classify the ontology, the changes should be accommodated
// incrementally (i.e. without re-inferring all subclass relationships)
// You should be able to see it from the log output
reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
// Terminate the worker threads used by the reasoner.
reasoner.dispose();
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
}
*/
} | 42.77193 | 165 | 0.719852 |
8f41e108a45d369dcd2b9966b89bb8e80d438223 | 6,279 | package net.minecraft.block;
import net.minecraft.block.properties.*;
import net.minecraft.creativetab.*;
import net.minecraft.world.*;
import java.util.*;
import net.minecraft.util.*;
import net.minecraft.init.*;
import net.minecraft.item.*;
import net.minecraft.block.state.*;
public class BlockCrops extends BlockBush implements IGrowable
{
public static final PropertyInteger AGE;
protected BlockCrops() {
this.setDefaultState(this.blockState.getBaseState().withProperty((IProperty<Comparable>)BlockCrops.AGE, 0));
this.setTickRandomly(true);
final float f = 0.5f;
this.setBlockBounds(0.5f - f, 0.0f, 0.5f - f, 0.5f + f, 0.25f, 0.5f + f);
this.setCreativeTab(null);
this.setHardness(0.0f);
this.setStepSound(BlockCrops.soundTypeGrass);
this.disableStats();
}
@Override
protected boolean canPlaceBlockOn(final Block ground) {
return ground == Blocks.farmland;
}
@Override
public void updateTick(final World worldIn, final BlockPos pos, final IBlockState state, final Random rand) {
super.updateTick(worldIn, pos, state, rand);
if (worldIn.getLightFromNeighbors(pos.up()) >= 9) {
final int i = state.getValue((IProperty<Integer>)BlockCrops.AGE);
if (i < 7) {
final float f = getGrowthChance(this, worldIn, pos);
if (rand.nextInt((int)(25.0f / f) + 1) == 0) {
worldIn.setBlockState(pos, state.withProperty((IProperty<Comparable>)BlockCrops.AGE, i + 1), 2);
}
}
}
}
public void grow(final World worldIn, final BlockPos pos, final IBlockState state) {
int i = state.getValue((IProperty<Integer>)BlockCrops.AGE) + MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5);
if (i > 7) {
i = 7;
}
worldIn.setBlockState(pos, state.withProperty((IProperty<Comparable>)BlockCrops.AGE, i), 2);
}
protected static float getGrowthChance(final Block blockIn, final World worldIn, final BlockPos pos) {
float f = 1.0f;
final BlockPos blockpos = pos.down();
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
float f2 = 0.0f;
final IBlockState iblockstate = worldIn.getBlockState(blockpos.add(i, 0, j));
if (iblockstate.getBlock() == Blocks.farmland) {
f2 = 1.0f;
if (iblockstate.getValue((IProperty<Integer>)BlockFarmland.MOISTURE) > 0) {
f2 = 3.0f;
}
}
if (i != 0 || j != 0) {
f2 /= 4.0f;
}
f += f2;
}
}
final BlockPos blockpos2 = pos.north();
final BlockPos blockpos3 = pos.south();
final BlockPos blockpos4 = pos.west();
final BlockPos blockpos5 = pos.east();
final boolean flag = blockIn == worldIn.getBlockState(blockpos4).getBlock() || blockIn == worldIn.getBlockState(blockpos5).getBlock();
final boolean flag2 = blockIn == worldIn.getBlockState(blockpos2).getBlock() || blockIn == worldIn.getBlockState(blockpos3).getBlock();
if (flag && flag2) {
f /= 2.0f;
}
else {
final boolean flag3 = blockIn == worldIn.getBlockState(blockpos4.north()).getBlock() || blockIn == worldIn.getBlockState(blockpos5.north()).getBlock() || blockIn == worldIn.getBlockState(blockpos5.south()).getBlock() || blockIn == worldIn.getBlockState(blockpos4.south()).getBlock();
if (flag3) {
f /= 2.0f;
}
}
return f;
}
@Override
public boolean canBlockStay(final World worldIn, final BlockPos pos, final IBlockState state) {
return (worldIn.getLight(pos) >= 8 || worldIn.canSeeSky(pos)) && this.canPlaceBlockOn(worldIn.getBlockState(pos.down()).getBlock());
}
protected Item getSeed() {
return Items.wheat_seeds;
}
protected Item getCrop() {
return Items.wheat;
}
@Override
public void dropBlockAsItemWithChance(final World worldIn, final BlockPos pos, final IBlockState state, final float chance, final int fortune) {
super.dropBlockAsItemWithChance(worldIn, pos, state, chance, 0);
if (!worldIn.isRemote) {
final int i = state.getValue((IProperty<Integer>)BlockCrops.AGE);
if (i >= 7) {
for (int j = 3 + fortune, k = 0; k < j; ++k) {
if (worldIn.rand.nextInt(15) <= i) {
Block.spawnAsEntity(worldIn, pos, new ItemStack(this.getSeed(), 1, 0));
}
}
}
}
}
@Override
public Item getItemDropped(final IBlockState state, final Random rand, final int fortune) {
return (state.getValue((IProperty<Integer>)BlockCrops.AGE) == 7) ? this.getCrop() : this.getSeed();
}
@Override
public Item getItem(final World worldIn, final BlockPos pos) {
return this.getSeed();
}
@Override
public boolean canGrow(final World worldIn, final BlockPos pos, final IBlockState state, final boolean isClient) {
return state.getValue((IProperty<Integer>)BlockCrops.AGE) < 7;
}
@Override
public boolean canUseBonemeal(final World worldIn, final Random rand, final BlockPos pos, final IBlockState state) {
return true;
}
@Override
public void grow(final World worldIn, final Random rand, final BlockPos pos, final IBlockState state) {
this.grow(worldIn, pos, state);
}
@Override
public IBlockState getStateFromMeta(final int meta) {
return this.getDefaultState().withProperty((IProperty<Comparable>)BlockCrops.AGE, meta);
}
@Override
public int getMetaFromState(final IBlockState state) {
return state.getValue((IProperty<Integer>)BlockCrops.AGE);
}
@Override
protected BlockState createBlockState() {
return new BlockState(this, new IProperty[] { BlockCrops.AGE });
}
static {
AGE = PropertyInteger.create("age", 0, 7);
}
}
| 38.521472 | 295 | 0.598025 |
bf981abbab040a41bf507ef1399a851a044fe856 | 3,846 | /**********************************************************************
Copyright (c) 2009 Andy Jefferson and others. 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.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.query.cache;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.datanucleus.store.query.Query;
/**
* Cache for query results.
*/
public interface QueryResultsCache extends Serializable
{
/**
* Method to close the cache when no longer needed. Provides a hook to release resources etc.
*/
void close();
/**
* Method to evict all queries that use the provided class as candidate.
* This is usually called when an instance of the candidate has been changed in the datastore.
* @param candidate The candidate
*/
void evict(Class candidate);
/**
* Evict the query from the results cache.
* @param query The query to evict (evicts all use of this query, with any params)
*/
void evict(Query query);
/**
* Evict the query with the specified params from the results cache.
* @param query The query to evict
* @param params The parameters
*/
void evict(Query query, Map params);
/**
* Method to clear the cache.
*/
void evictAll();
/**
* Method to pin the specified query in the cache, preventing garbage collection.
* @param query The query
*/
default void pin(Query query)
{
// Not supported
}
/**
* Method to pin the specified query in the cache, preventing garbage collection.
* @param query The query
* @param params Its params
*/
default void pin(Query query, Map params)
{
// Not supported
}
/**
* Method to unpin the specified query from the cache, allowing garbage collection.
* @param query The query
*/
default void unpin(Query query)
{
// Not supported
}
/**
* Method to unpin the specified query from the cache, allowing garbage collection.
* @param query The query
* @param params Its params
*/
default void unpin(Query query, Map params)
{
// Not supported
}
/**
* Accessor for whether the cache is empty.
* @return Whether it is empty.
*/
default boolean isEmpty()
{
return size() == 0;
}
/**
* Accessor for the total number of results in the query cache.
* @return Number of queries
*/
default int size()
{
// Some don't support it, so provide a default
return 0;
}
/**
* Accessor for the results from the cache.
* @param queryKey The query key
* @return The cached query result ids
*/
List<Object> get(String queryKey);
/**
* Method to put an object in the cache.
* @param queryKey The query key
* @param results The results for this query
* @return The result ids previously associated with this query (if any)
*/
List<Object> put(String queryKey, List<Object> results);
/**
* Accessor for whether the specified query is in the cache
* @param queryKey The query key
* @return Whether it is in the cache
*/
boolean contains(String queryKey);
} | 27.669065 | 98 | 0.624545 |
868182d6bf6b0ed5bc4b2a9b88ea0e089db45c01 | 130 | /** Implementations of {@link org.anchoranalysis.io.input.bean.InputManager}. */
package org.anchoranalysis.plugin.io.bean.input;
| 43.333333 | 80 | 0.784615 |
a3c56c103564b31c20ac7e829885336902266642 | 9,232 | package ru.assisttech.assistsdk;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.Date;
import ru.assisttech.sdk.AssistResult;
import ru.assisttech.sdk.storage.AssistTransaction;
import ru.assisttech.sdk.storage.AssistTransactionFilter;
import ru.assisttech.sdk.storage.AssistTransactionStorage;
import ru.assisttech.sdk.storage.AssistTransactionStorageImpl;
import ru.assisttech.sdk.storage.AssistTransactionsLoader;
public class TransactionsActivity extends UpButtonActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "TransactionsActivity";
private static final int LOADER_ID = 0;
public static final String TRANS_ID = "id";
private AssistTransactionStorage storage;
private AssistTransactionFilter deleteFilter;
private TransactionSimpleAdapter transactionsAdapter;
private String[] from = new String[] {AssistTransactionStorageImpl.COLUMN_ORDER_DATE_DEVICE,
AssistTransactionStorageImpl.COLUMN_ORDER_NUMBER,
AssistTransactionStorageImpl.COLUMN_ORDER_AMOUNT,
AssistTransactionStorageImpl.COLUMN_ORDER_CURRENCY};
private int[] to = new int[] {R.id.tvTransItemOrderDate,
R.id.tvTransItemOrderNumber,
R.id.tvTransItemOrderAmount,
R.id.tvTransItemOrderCurrency};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
if (getActionBar() != null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
ApplicationConfiguration cfg = ApplicationConfiguration.getInstance();
storage = cfg.getPaymentEngine().transactionStorage();
getLoaderManager().initLoader(LOADER_ID, null, this);
transactionsAdapter = new TransactionSimpleAdapter(this, R.layout.trans_item, null, from, to);
ListView lvTransactions = (ListView) findViewById(R.id.lvTransactions);
lvTransactions.setAdapter(transactionsAdapter);
lvTransactions.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("TransactionsActivity", "onClick(). position: " + position);
Intent intent = new Intent(TransactionsActivity.this, TransDetailsActivity.class);
Bundle extras = new Bundle();
extras.putLong(TRANS_ID, id);
intent.putExtras(extras);
startActivity(intent);
}
});
}
@Override
public void onResume() {
super.onResume();
updateList();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.transactions_activity_menu, menu);
SearchView searchView = (SearchView)(menu.findItem(R.id.action_search).getActionView());
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
updateListWithCertainOrderNumber(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
updateListWithCertainOrderNumber(newText);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Date date;
long msDay = 24*60*60*1000;
switch (item.getItemId()) {
case R.id.miTransFilter:
Intent intent = new Intent(this, TransFilterActivity.class);
startActivity(intent);
break;
case R.id.miDelete2weeks:
deleteFilter = new AssistTransactionFilter();
date = new Date();
date.setTime(date.getTime() - msDay * 14L);
deleteFilter.setDateEnd(date);
showAlertDialog();
break;
case R.id.miDelete1month:
deleteFilter = new AssistTransactionFilter();
date = new Date();
date.setTime(date.getTime() - msDay * 30L);
deleteFilter.setDateEnd(date);
showAlertDialog();
break;
}
return super.onOptionsItemSelected(item);
}
/*
* LoaderManager.LoaderCallbacks<>
*/
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader()");
return new AssistTransactionsLoader(storage, this, args);
}
/*
* LoaderManager.LoaderCallbacks<>
*/
@Override
public void onLoaderReset(Loader<Cursor> loader) {
Log.d(TAG, "onLoaderReset()");
transactionsAdapter.swapCursor(null);
transactionsAdapter.notifyDataSetChanged();
}
/*
* LoaderManager.LoaderCallbacks<>
*/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(TAG, "onLoadFinished(). Cursor size: " + data.getCount());
transactionsAdapter.swapCursor(data);
transactionsAdapter.notifyDataSetChanged();
}
private void updateList() {
Log.d(TAG, "updateList");
if (getLoaderManager().getLoader(LOADER_ID).isStarted()) {
getLoaderManager().getLoader(LOADER_ID).forceLoad();
} else {
getLoaderManager().initLoader(LOADER_ID, null, this);
}
}
private void updateListWithCertainOrderNumber(String orderNumber) {
Bundle bundle = null;
if (!TextUtils.isEmpty(orderNumber)) {
bundle = new Bundle();
bundle.putString(AssistTransactionsLoader.ARG_STRING_ORDER_NUMBER, orderNumber);
}
getLoaderManager().restartLoader(LOADER_ID, bundle, TransactionsActivity.this);
}
private class TransactionSimpleAdapter extends SimpleCursorAdapter {
TransactionSimpleAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Cursor c = getCursor();
c.moveToPosition(position);
AssistTransaction t = storage.transactionFromCursor(c);
AssistResult.OrderState os = t.getResult().getOrderState();
Log.d(TAG, "State: " + os.toString());
switch (os) {
case APPROVED:
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.transaction_approved));
break;
case IN_PROCESS:
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.transaction_in_process));
break;
case UNKNOWN:
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.transaction_unknown));
break;
case CANCEL_ERROR:
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.transaction_cancel_error));
break;
default:
view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.transaction_napproved));
break;
}
TextView tvAmount = (TextView)view.findViewById(R.id.tvTransItemOrderAmount);
tvAmount.setText(AssistTransaction.formatAmount(t.getOrderAmount()));
ImageView ivFilterIcon = (ImageView)view.findViewById(R.id.ivFilterIcon);
if (storage.getFilter().match(t)) {
ivFilterIcon.setVisibility(View.VISIBLE);
} else {
ivFilterIcon.setVisibility(View.INVISIBLE);
}
return view;
}
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Удаление транзакций");
builder.setMessage("Действие не может быть отменено!");
builder.setPositiveButton("Удалить", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
storage.deleteTransactions(deleteFilter);
updateList();
}
});
builder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
| 36.780876 | 127 | 0.674285 |
bd96086d273a16980f03eb5b92585370aba88bd3 | 7,806 |
import java.util.Arrays;
/**
*@author Paul Nguyen
*@created May 3, 2003
*@version 1.0 The main interface to the SM. The storage manager (SM) is the
* primary interface to all database I/O. SM implementers will provide the
* ability to store and fetch arbitrarily size records. Each record will be
* indentified by a (hopefully) unique OID. Implementers may choose to
* implement one or more OID types and whether or not these OIDs can be
* reused.
*/
public interface SM {
/**
* Construct a SM. SM implementers will need to provide a constructor that
* creates an SM intstance while prviding for constructor arguments that
* connect the SM to appropriate disk volumes or one or more files contianing
* persistent data. XXX (may consider developping a storage manager Factory
* class for instantiating new SM instances and deal with default
* initialization)
*
*@param rec Description of Parameter
*@return Description of the Returned Value
*@exception IOException Description of Exception
*@since
*/
//SM(...);
/**
* Construct a SM. SM implementers will need to provide a constructor that
* creates an SM intstance while prviding for constructor arguments that
* connect the SM to appropriate disk volumes or one or more files contianing
* persistent data. XXX (may consider developping a storage manager Factory
* class for instantiating new SM instances and deal with default
* initialization)
*
* Store the given record and return its OID.
*
*@param rec Description of Parameter
*@return Description of the Returned Value
*@return an OID.
*@exception IOException Description of Exception
*@since
*/
OID store(Record rec) throws IOException;
/**
* Fetch a record by OID. Return a reference to a record thus instantiating
* an in-memory Record instance whose address is given by the specified OID.
*
*@param oid an OID.
*@return a Record.
*@exception NotFoundException when there is no record for the specified
* OID.
*@exception IOException when there is an IO error in the SM.
*@since
*/
Record fetch(OID oid) throws NotFoundException, IOException;
/**
* Update by replacing the Record at the specified OID with the new Record
* specified.
*
*@param oid an OID.
*@param rec a Record.
*@return Description of the Returned Value
*@exception NotFoundException when there is no record for the specified
* OID.
*@exception IOException when there is an IO error in the SM.
*@since
*/
OID update(OID oid, Record rec) throws NotFoundException, IOException;
/**
* Delete the stored record whose address is given by the specified OID.
* Implementers may also chose to remove any in memory, cached copies if that
* would be appropriate. Implementers may choose whether or not to reuse the
* OID for subsequently created records.
*
*@param oid an OID.
*@exception NotFoundException when there is no record for the given
* OID.
*@exception CannotDeleteException when some other problem occurs.
*@since
*/
void delete(OID oid) throws NotFoundException, CannotDeleteException;
/**
* Description of the Method
*
*@exception IOException Description of Exception
*@since
*/
void close() throws IOException;
void flush() ;
OID getOID( byte[] bytes ) ;
/**
* This is a tagging interface used to abstract a concrete OID
* implementataion. SM implementers extend this interface thus providing a
* concrete implementatation for an OID. Note that OID implementations must
* provide a constuctor that instantiates an OID from a byte array. XXX (may
* consider developping an OIDFactory to ensure uniform semantics for
* instantiation)
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static interface OID {
/**
* Gets the key attribute of the OID object
*
*@return The key value
*@since
*/
String getKey();
/**
* Description of the Method
*
*@return Description of the Returned Value
*@since
*/
byte[] toBytes();
}
/**
* Record implements a wrapper around an arbirtrary length array of bytes.
* XXX (may be better as an abstract class or interface)
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static class Record {
/**
* Description of the Field
*
*@since
*/
protected byte[] data;
/**
* Construct a Record with the specified number of bytes.
*
*@param size a int.
*@exception SMException Description of Exception
*@since
*/
Record(int size) throws SMException {
try {
data = new byte[size];
} catch (java.lang.OutOfMemoryError oome) {
throw new SMException();
}
}
/**
* Description of the Method
*
*@param o Description of Parameter
*@return Description of the Returned Value
*@since
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Record)) {
return false;
}
final Record l_fileRecord = (Record) o;
if (!Arrays.equals(data, l_fileRecord.data)) {
return false;
}
return true;
}
// void truncate(long length);
/**
* Copies the given array to the record, possibly overwriting any
* previously copied data and returns the number of bytes successfully
* copied.
*
*@param someData The new bytes value
*@return a int.
*@since
*/
public int setBytes(byte[] someData) {
if (someData == null) {
return 0;
} else {
int minLength = (data.length < someData.length)
? data.length
: someData.length;
for (int i = 0; i < minLength; i++) {
data[i] = someData[i];
}
return someData.length;
}
}
/**
* getBytes.
*
*@param pos a long.
*@param length a int.
*@return a byte[].
*@since
*/
public byte[] getBytes(long pos, int length) {
return data;
}
public byte[] getBytes(long pos, long length) {
return data ;
}
/**
* Returns the length of the Record.
*
*@return a long.
*@since
*/
public long length() {
return data.length;
}
}
/**
* This exception is used to signal any of a number of possible IO, OID,
* memory, or other internal SM problems. As the root of all SM exceptions
* its type can used to catch all SM exceptions.
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static class SMException extends java.lang.Exception {
}
/**
* This exception is used to signal lookup failures.
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static class NotFoundException extends SMException {
}
/**
* This exception is used to signal IO failures.
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static class IOException extends SMException {
}
/**
* This exception is used to signal deletion problems.
*
*@author Paul Nguyen
*@created May 3, 2003
*/
public static class CannotDeleteException extends SMException {
}
// XXX (any other exceptions can be added here)
}
| 26.824742 | 80 | 0.611197 |
0ff0bed89e7eb93d4e820c21351211f991298273 | 7,874 | package ball.activation;
/*-
* ##########################################################################
* Utilities
* %%
* Copyright (C) 2008 - 2022 Allen D. Ball
* %%
* 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.
* ##########################################################################
*/
import java.beans.ConstructorProperties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang3.StringUtils.EMPTY;
/**
* {@link javax.activation.DataSource} implementation that provides a
* {@link BufferedReader} wrapping the {@link javax.activation.DataSource}
* {@link java.io.InputStream} and a {@link PrintWriter} wrapping the
* {@link javax.activation.DataSource} {@link java.io.OutputStream}.
*
* @author {@link.uri mailto:[email protected] Allen D. Ball}
*/
public class ReaderWriterDataSource extends FilterDataSource {
protected static final Charset CHARSET = UTF_8;
private final Charset charset;
/**
* @param name Initial {@code "Name"} attribute value.
* @param type Initial {@code "ContentType"} attribute
* value.
*/
@ConstructorProperties({ "name", "contentType" })
public ReaderWriterDataSource(String name, String type) {
this(name, type, null);
}
/**
* @param name Initial {@code "Name"} attribute value.
* @param type Initial {@code "ContentType"} attribute
* value.
* @param charset The {@link Charset} used to encode the
* {@link java.io.OutputStream}.
*/
@ConstructorProperties({ "name", "contentType", "charset" })
public ReaderWriterDataSource(String name, String type, Charset charset) {
this(name, type, charset, null);
}
/**
* @param name Initial {@code "Name"} attribute value.
* @param type Initial {@code "ContentType"} attribute
* value.
* @param charset The {@link Charset} used to encode the
* {@link java.io.OutputStream}.
* @param content The initial content {@link String}.
*/
@ConstructorProperties({ "name", "contentType", "charset", EMPTY })
public ReaderWriterDataSource(String name, String type, Charset charset, String content) {
super(new ByteArrayDataSource(name, type));
this.charset = (charset != null) ? charset : CHARSET;
if (content != null) {
try (Writer writer = getWriter()) {
writer.write(content);
} catch (IOException exception) {
throw new ExceptionInInitializerError(exception);
}
}
}
/**
* Private no-argument constructor (for JAXB annotated subclasses).
*/
private ReaderWriterDataSource() { this(null, null); }
/**
* Method to get the {@link Charset} used to create the
* {@link BufferedReader} and {@link PrintWriter}.
*
* @return The Charset.
*/
public Charset getCharset() { return charset; }
/**
* Method to return a new {@link Reader} to read the underlying
* {@link java.io.InputStream}.
*
* @see #getInputStream()
*
* @return A {@link Reader} wrapping the
* {@link javax.activation.DataSource}
* {@link java.io.InputStream}.
*
* @throws IOException If an I/O exception occurs.
*/
public Reader getReader() throws IOException {
return new InputStreamReader(getInputStream(), getCharset());
}
/**
* Method to return a new {@link Writer} to write to the underlying
* {@link java.io.OutputStream}.
*
* @see #getOutputStream()
*
* @return A {@link Writer} wrapping the
* {@link javax.activation.DataSource}
* {@link java.io.OutputStream}.
*
* @throws IOException If an I/O exception occurs.
*/
public Writer getWriter() throws IOException {
return new OutputStreamWriter(getOutputStream(), getCharset());
}
/**
* Method to return a new {@link BufferedReader} to read the underlying
* {@link java.io.InputStream}.
*
* @see #getInputStream()
*
* @return A {@link BufferedReader} wrapping the
* {@link javax.activation.DataSource}
* {@link java.io.InputStream}.
*
* @throws IOException If an I/O exception occurs.
*/
public BufferedReader getBufferedReader() throws IOException {
return new BufferedReader(getReader());
}
/**
* Method to return a new {@link PrintWriter} to write to the underlying
* {@link java.io.OutputStream}.
*
* @see #getOutputStream()
*
* @return A {@link PrintWriter} wrapping the
* {@link javax.activation.DataSource}
* {@link java.io.OutputStream}.
*
* @throws IOException If an I/O exception occurs.
*/
public PrintWriter getPrintWriter() throws IOException {
return new PrintWriter(getWriter(), true);
}
/**
* Method to return a new {@link PrintStream} to write to the underlying
* {@link java.io.OutputStream}.
*
* @see #getOutputStream()
*
* @return A {@link PrintStream} wrapping the
* {@link javax.activation.DataSource}
* {@link java.io.OutputStream}.
*
* @throws IOException If an I/O exception occurs.
*/
public PrintStream getPrintStream() throws IOException {
return new PrintStream(getOutputStream(), true, getCharset().name());
}
/**
* Method to write the contents of this
* {@link javax.activation.DataSource} to a {@link PrintWriter}.
*
* @see #getBufferedReader()
*
* @param writer The target {@link PrintWriter}.
*
* @throws IOException If a problem is encountered opening or
* reading the {@link BufferedReader} or
* writing to the {@link PrintWriter}.
*/
public void writeTo(PrintWriter writer) throws IOException {
getBufferedReader().lines().forEach(t -> writer.println(t));
}
@Override
public String toString() {
String string = null;
try (BufferedReader reader = getBufferedReader()) {
string = reader.lines().collect(joining("\n"));
} catch (IOException exception) {
string = super.toString();
}
return string;
}
/**
* Convenience method to get the name of a {@link Charset}.
*
* @param charset The {@link Charset}.
*
* @return The name of the {@link Charset} if non-{@code null};
* {@code null} otherwise.
*
* @see Charset#name()
*/
protected static String nameOf(Charset charset) {
return (charset != null) ? charset.name() : null;
}
}
| 34.234783 | 94 | 0.590551 |
5f447a28054ce2a91e8209273b34c6b2815e2004 | 3,846 | /*
* Copyright 2018 Okta
*
* 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.okta.tools.helpers;
import org.apache.http.HttpHost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.*;
// Inspired by https://stackoverflow.com/a/22960881/154527
public final class HttpHelper {
public static CloseableHttpClient createClient(HttpClientBuilder httpClientBuilder)
{
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", ProxySelectorPlainConnectionSocketFactory.INSTANCE)
.register("https", new ProxySelectorSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
return httpClientBuilder
.useSystemProperties()
.setConnectionManager(cm)
.build();
}
public static CloseableHttpClient createClient()
{
return createClient(HttpClients.custom());
}
private enum ProxySelectorPlainConnectionSocketFactory implements ConnectionSocketFactory {
INSTANCE;
@Override
public Socket createSocket(HttpContext context) throws IOException {
Socket socket = HttpHelper.createSocket(context);
return socket != null ? socket : PlainConnectionSocketFactory.INSTANCE.createSocket(context);
}
@Override
public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException {
return PlainConnectionSocketFactory.INSTANCE.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
}
}
private static final class ProxySelectorSSLConnectionSocketFactory extends SSLConnectionSocketFactory {
ProxySelectorSSLConnectionSocketFactory(SSLContext sslContext) {
super(sslContext);
}
@Override
public Socket createSocket(HttpContext context) throws IOException {
Socket socket = HttpHelper.createSocket(context);
return socket != null ? socket : super.createSocket(context);
}
}
private static Socket createSocket(HttpContext context) {
HttpHost httpTargetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URI uri = URI.create(httpTargetHost.toURI());
Proxy proxy = ProxySelector.getDefault().select(uri).iterator().next();
return proxy.type().equals(Proxy.Type.SOCKS) ? new Socket(proxy) : null;
}
}
| 42.733333 | 190 | 0.73791 |
c86afea847e8036c6171fe9a832ea34c70c14185 | 1,550 | package durianhln.polymorph.hud;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
/**
* Represents the colored capsule button that a player drags a touch to in order to morph.
* @author Darian
*/
public class ColorButton extends Image {
private final Vector2 targetPosition;
public ColorButton(TextureRegion texture, Color color, Vector2 targetPosition) {
super(texture);
setColor(color);
reset();
this.targetPosition = targetPosition;
}
public void moveFrom(ShapeButton shapeButton) {
setVisible(true);
setPosition(shapeButton.getCenterX(), shapeButton.getCenterY());
final float ANIMATION_SPEED = 0.1f;
addAction(Actions.parallel(Actions.moveTo(targetPosition.x, targetPosition.y, ANIMATION_SPEED),
Actions.scaleTo(1.0f, 1.0f, ANIMATION_SPEED)));
}
public final void reset() {
clearActions();
setVisible(false);
addAction(Actions.scaleTo(0, 0));
}
public boolean contains(Vector2 point) {
//hitbox intentionally square for more lenient hit detection
if (!isTouchable()) return false;
return targetPosition.x <= point.x && point.x <= targetPosition.x+getWidth() &&
targetPosition.y <= point.y && point.y <= targetPosition.y+getWidth(); //intentional
}
}
| 33.695652 | 103 | 0.67871 |
f7ba5446b90b7ace43ab91f2a0a6edd98550ea80 | 912 | package io.quantumdb.core.schema.operations;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Strings;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class MergeTable implements SchemaOperation {
private final String leftTableName;
private final String rightTableName;
private final String targetTableName;
MergeTable(String leftTableName, String rightTableName, String targetTableName) {
checkArgument(!Strings.isNullOrEmpty(leftTableName), "You must specify a 'leftTableName'.");
checkArgument(!Strings.isNullOrEmpty(rightTableName), "You must specify a 'rightTableName'.");
checkArgument(!Strings.isNullOrEmpty(targetTableName), "You must specify a 'targetTableName'.");
this.leftTableName = leftTableName;
this.rightTableName = rightTableName;
this.targetTableName = targetTableName;
}
}
| 32.571429 | 98 | 0.804825 |
9388bb6312a5011b20c31cb7b6609699003e991f | 16,033 | package com.loopedlabs.lang;
/*
The MIT License (MIT)
Copyright (c) 2015 Looped Labs Pvt. Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class KnUnicodeToBaraha {
private static final Map<String, String> mapping;
static {
HashMap<String, String> m = new HashMap<String, String>();
m.put("ಅ", "C");
m.put("ಆ", "D");
m.put("ಇ", "E");
m.put("ಈ", "F");
m.put("ಉ", "G");
m.put("ಊ", "H");
m.put("ಋ", "IÄ");
m.put("ಎ", "J");
m.put("ಏ", "K");
m.put("ಐ", "L");
m.put("ಒ", "M");
m.put("ಓ", "N");
m.put("ಔ", "O");
m.put("ಂ", "A");
m.put("ಃ", "B");
m.put("ಕ್", "Pï");
m.put("ಕ", "PÀ");
m.put("ಕಾ", "PÁ");
m.put("ಕಿ", "Q");
m.put("ಕೀ", "QÃ");
m.put("ಕು", "PÀÄ");
m.put("ಕೂ", "PÀÆ");
m.put("ಕೃ", "PÀÈ");
m.put("ಕೆ", "PÉ");
m.put("ಕೇ", "PÉÃ");
m.put("ಕೈ", "PÉÊ");
m.put("ಕೊ", "PÉÆ");
m.put("ಕೋ", "PÉÆÃ");
m.put("ಕೌ", "PË");
m.put("ಖ್", "Sï");
m.put("ಖ", "R");
m.put("ಖಾ", "SÁ");
m.put("ಖಿ", "T");
m.put("ಖೀ", "TÃ");
m.put("ಖು", "RÄ");
m.put("ಖೂ", "RÆ");
m.put("ಖೃ", "RÈ");
m.put("ಖೆ", "SÉ");
m.put("ಖೇ", "SÉÃ");
m.put("ಖೈ", "SÉÊ");
m.put("ಖೊ", "SÉÆ");
m.put("ಖೋ", "SÉÆÃ");
m.put("ಖೌ", "SË");
m.put("ಗ್", "Uï");
m.put("ಗ", "UÀ");
m.put("ಗಾ", "UÁ");
m.put("ಗಿ", "V");
m.put("ಗೀ", "VÃ");
m.put("ಗು", "UÀÄ");
m.put("ಗೂ", "UÀÆ");
m.put("ಗೃ", "UÀÈ");
m.put("ಗೆ", "UÉ");
m.put("ಗೇ", "UÉÃ");
m.put("ಗೈ", "UÉÊ");
m.put("ಗೊ", "UÉÆ");
m.put("ಗೋ", "UÉÆÃ");
m.put("ಗೌ", "UË");
m.put("ಘ್", "Wï");
m.put("ಘ", "WÀ");
m.put("ಘಾ", "WÁ");
m.put("ಘಿ", "X");
m.put("ಘೀ", "XÃ");
m.put("ಘು", "WÀÄ");
m.put("ಘೂ", "WÀÆ");
m.put("ಘೃ", "WÀÈ");
m.put("ಘೆ", "WÉ");
m.put("ಘೇ", "WÉÃ");
m.put("ಘೈ", "WÉÊ");
m.put("ಘೊ", "WÉÆ");
m.put("ಘೋ", "WÉÆÃ");
m.put("ಘೌ", "WË");
m.put("ಞ", "k");
m.put("ಚ್", "Zï");
m.put("ಚ", "ZÀ");
m.put("ಚಾ", "ZÁ");
m.put("ಚಿ", "a");
m.put("ಚೀ", "aÃ");
m.put("ಚು", "ZÀÄ");
m.put("ಚೂ", "ZÀÆ");
m.put("ಚೃ", "ZÀÈ");
m.put("ಚೆ", "ZÉ");
m.put("ಚೇ", "ZÉÃ");
m.put("ಚೈ", "ZÉÊ");
m.put("ಚೊ", "ZÉÆ");
m.put("ಚೋ", "ZÉÆÃ");
m.put("ಚೌ", "ZË");
m.put("ಛ್", "bï");
m.put("ಛ", "bÀ");
m.put("ಛಾ", "bÁ");
m.put("ಛಿ", "c");
m.put("ಛೀ", "cÃ");
m.put("ಛು", "bÀÄ");
m.put("ಛೂ", "bÀÆ");
m.put("ಛೃ", "bÀÈ");
m.put("ಛೆ", "bÉ");
m.put("ಛೇ", "bÉÃ");
m.put("ಛೈ", "bÉÆ");
m.put("ಛೊ", "bÉÆÃ");
m.put("ಛೋ", "bË");
m.put("ಛೌ", "bË");
m.put("ಜ್", "eï");
m.put("ಜ", "d");
m.put("ಜಾ", "eÁ");
m.put("ಜಿ", "f");
m.put("ಜೀ", "fÃ");
m.put("ಜು", "dÄ");
m.put("ಜೂ", "dÆ");
m.put("ಜೃ", "dÈ");
m.put("ಜೆ", "eÉ");
m.put("ಜೇ", "eÉÊ");
m.put("ಜೈ", "eÉÆ");
m.put("ಜೊ", "eÉÆÃ");
m.put("ಜೋ", "eË");
m.put("ಜೌ", "eË");
m.put("ಝ್", "gÀhiï");
m.put("ಝ", "gÀhÄ");
m.put("ಝಾ", "gÀhiÁ");
m.put("ಝಿ", "jhÄ");
m.put("ಝೀ", "jhÄÃ");
m.put("ಝೆ", "gÉhÄ");
m.put("ಝು", "gÀhÄÄ");
m.put("ಝೂ", "gÀhÄÆ");
m.put("ಝೃ", "gÀhÄÈ");
m.put("ಝೆ", "gÉhÄ");
m.put("ಝೇ", "gÉhÄÃ");
m.put("ಝೈ", "gÉhÄÊ");
m.put("ಝೊ", "gÉhÆ");
m.put("ಝೋ", "gÉhÆÃ");
m.put("ಝೌ", "gÀhiË");
m.put("ಙ", "Y");
m.put("ಟ್", "mï");
m.put("ಟ", "l");
m.put("ಟಾ", "mÁ");
m.put("ಟಿ", "n");
m.put("ಟೀ", "nÃ");
m.put("ಟು", "lÄ");
m.put("ಟೂ", "lÆ");
m.put("ಟೃ", "lÈ");
m.put("ಟೆ", "mÉ");
m.put("ಟೇ", "mÉÃ");
m.put("ಟೈ", "mÉÊ");
m.put("ಟೊ", "mÉÆ");
m.put("ಟೋ", "mÉÆÃ");
m.put("ಟೌ", "mË");
m.put("ಠ್", "oï");
m.put("ಠ", "oÀ");
m.put("ಠಾ", "oÁ");
m.put("ಠಿ", "p");
m.put("ಠೀ", "pÃ");
m.put("ಠು", "oÀÄ");
m.put("ಠೂ", "oÀÆ");
m.put("ಠೃ", "oÀÈ");
m.put("ಠೆ", "oÉ");
m.put("ಠೇ", "oÉÃ");
m.put("ಠೈ", "oÉÊ");
m.put("ಠೊ", "oÉÆ");
m.put("ಠೋ", "oÉÆÃ");
m.put("ಠೌ", "oË");
m.put("ಡ್", "qï");
m.put("ಡ", "qÀ");
m.put("ಡಾ", "qÁ");
m.put("ಡಿ", "r");
m.put("ಡೀ", "rÃ");
m.put("ಡು", "qÀÄ");
m.put("ಡೂ", "qÀÆ");
m.put("ಡೃ", "qÀÈ");
m.put("ಡೆ", "qÉ");
m.put("ಡೇ", "qÉÃ");
m.put("ಡೈ", "qÉÊ");
m.put("ಡೊ", "qÉÆ");
m.put("ಡೋ", "qÉÆÃ");
m.put("ಡೌ", "qË");
m.put("ಢ್", "qsï");
m.put("ಢ", "qsÀ");
m.put("ಢಾ", "qsÁ");
m.put("ಢಿ", "rü");
m.put("ಢೀ", "rüÃ");
m.put("ಢು", "qsÀÄ");
m.put("ಢೂ", "qsÀÆ");
m.put("ಢೃ", "qsÀÈ");
m.put("ಢೆ", "qsÉ");
m.put("ಢೇ", "qsÉÃ");
m.put("ಢೈ", "qsÉÊ");
m.put("ಢೊ", "qsÉÆ");
m.put("ಢೋ", "qsÉÆÃ");
m.put("ಢೌ", "qsË");
m.put("ಣ್", "uï");
m.put("ಣ", "t");
m.put("ಣಾ", "uÁ");
m.put("ಣಿ", "tÂ");
m.put("ಣೀ", "tÂÃ");
m.put("ಣು", "tÄ");
m.put("ಣೂ", "tÆ");
m.put("ಣೃ", "tÈ");
m.put("ಣೆ", "uÉ");
m.put("ಣೇ", "uÉÃ");
m.put("ಣೈ", "uÉÊ");
m.put("ಣೊ", "uÉÆ");
m.put("ಣೋ", "uÉÆÃ");
m.put("ಣೌ", "uË");
m.put("ತ್", "vï");
m.put("ತ", "vÀ");
m.put("ತಾ", "vÁ");
m.put("ತಿ", "w");
m.put("ತೀ", "wÃ");
m.put("ತು", "vÀÄ");
m.put("ತೂ", "vÀÆ");
m.put("ತೃ", "vÀÈ");
m.put("ತೆ", "vÉ");
m.put("ತೇ", "vÉÃ");
m.put("ತೈ", "vÉÊ");
m.put("ತೊ", "vÉÆ");
m.put("ತೋ", "vÉÆÃ");
m.put("ತೌ", "vË");
m.put("ಥ್", "xï");
m.put("ಥ", "xÀ");
m.put("ಥಾ", "xÁ");
m.put("ಥಿ", "y");
m.put("ಥೀ", "yÃ");
m.put("ಥು", "xÀÄ");
m.put("ಥೂ", "xÀÆ");
m.put("ಥೃ", "xÀÈ");
m.put("ಥೆ", "xÉ");
m.put("ಥೇ", "xÉÃ");
m.put("ಥೈ", "xÉÊ");
m.put("ಥೊ", "xÉÆ");
m.put("ಥೋ", "xÉÆÃ");
m.put("ಥೌ", "xË");
m.put("ದ್", "zï");
m.put("ದ", "zÀ");
m.put("ದಾ", "zÁ");
m.put("ದಿ", "¢");
m.put("ದೀ", "¢Ã");
m.put("ದು", "zÀÄ");
m.put("ದೂ", "zÀÆ");
m.put("ದೃ", "zÀÈ");
m.put("ದೆ", "zÉ");
m.put("ದೇ", "zÉÃ");
m.put("ದೈ", "zÉÊ");
m.put("ದೊ", "zÉÆ");
m.put("ದೋ", "zÉÆÃ");
m.put("ದೌ", "zË");
m.put("ಧ್", "zsï");
m.put("ಧ", "zsÀ");
m.put("ಧಾ", "zsÁ");
m.put("ಧಿ", "¢ü");
m.put("ಧೀ", "¢üÃ");
m.put("ಧು", "zsÀÄ");
m.put("ಧೂ", "zsÀÆ");
m.put("ಧೃ", "zsÀÈ");
m.put("ಧೆ", "zsÉ");
m.put("ಧೇ", "zsÉÃ");
m.put("ಧೈ", "zsÉÊ");
m.put("ಧೊ", "zsÉÆ");
m.put("ಧೋ", "zsÉÆÃ");
m.put("ಧೌ", "zsË");
m.put("ನ್", "£ï");
m.put("ನ", "£À");
m.put("ನಾ", "£Á");
m.put("ನಿ", "¤");
m.put("ನೀ", "¤Ã");
m.put("ನು", "£ÀÄ");
m.put("ನೂ", "£ÀÆ");
m.put("ನೃ", "£ÀÈ");
m.put("ನೆ", "£É");
m.put("ನೇ", "£ÉÃ");
m.put("ನೈ", "£ÉÊ");
m.put("ನೊ", "£ÉÆ");
m.put("ನೋ", "£ÉÆÃ");
m.put("ನೌ", "£Ë");
m.put("ಪ್", "¥ï");
m.put("ಪ", "¥À");
m.put("ಪಾ", "¥Á");
m.put("ಪಿ", "¦");
m.put("ಪೀ", "¦Ã");
m.put("ಪು", "¥ÀÄ");
m.put("ಪೂ", "¥ÀÆ");
m.put("ಪೃ", "¥ÀÈ");
m.put("ಪೆ", "¥É");
m.put("ಪೇ", "¥ÉÃ");
m.put("ಪೈ", "¥ÉÊ");
m.put("ಪೊ", "¥ÉÆ");
m.put("ಪೋ", "¥ÉÆÃ");
m.put("ಪೌ", "¥Ë");
m.put("ಫ್", "¥sï");
m.put("ಫ", "¥sÀ");
m.put("ಫಾ", "¥sÁ");
m.put("ಫಿ", "¦ü");
m.put("ಫೀ", "¦üÃ");
m.put("ಫು", "¥sÀÄ");
m.put("ಫೂ", "¥sÀÆ");
m.put("ಫೃ", "¥sÀÈ");
m.put("ಫೆ", "¥sÉ");
m.put("ಫೇ", "¥sÉÃ");
m.put("ಫೈ", "¥sÉÊ");
m.put("ಫೊ", "¥sÉÆ");
m.put("ಫೋ", "¥sÉÆÃ");
m.put("ಫೌ", "¥sË");
m.put("ಬ್", "¨ï");
m.put("ಬ", "§");
m.put("ಬಾ", "¨Á");
m.put("ಬಿ", "©");
m.put("ಬೀ", "©Ã");
m.put("ಬು", "§Ä");
m.put("ಬೂ", "§Æ");
m.put("ಬೃ", "§È");
m.put("ಬೆ", "¨É");
m.put("ಬೇ", "¨ÉÃ");
m.put("ಬೈ", "¨ÉÊ");
m.put("ಬೊ", "¨ÉÆ");
m.put("ಬೋ", "¨ÉÆÃ");
m.put("ಬೌ", "¨Ë");
m.put("ಭ್", "¨sï");
m.put("ಭ", "¨sÀ");
m.put("ಭಾ", "¨sÁ");
m.put("ಭಿ", "©ü");
m.put("ಭೆ", "¨sÉ");
m.put("ಭೌ", "¨sË");
m.put("ಮ್", "ªÀiï");
m.put("ಮ", "ªÀÄ");
m.put("ಮಾ", "ªÀiÁ");
m.put("ಮಿ", "«Ä");
m.put("ಮೀ", "«ÄÃ");
m.put("ಮು", "ªÀÄÄ");
m.put("ಮೂ", "ªÀÄÆ");
m.put("ಮೃ", "ªÀÄÈ");
m.put("ಮೆ", "ªÉÄ");
m.put("ಮೇ", "ªÉÄÃ");
m.put("ಮೈ", "ªÉÄÊ");
m.put("ಮೊ", "ªÉÆ");
m.put("ಮೋ", "ªÉÆÃ");
m.put("ಮೌ", "ªÀiË");
m.put("ಯ್", "AiÀiï");
m.put("ಯ", "AiÀÄ");
m.put("ಯಾ", "AiÀiÁ");
m.put("ಯಿ", "¬Ä");
m.put("ಯೀ", "¬ÄÃ");
m.put("ಯು", "AiÀÄÄ");
m.put("ಯೂ", "AiÀÄÆ");
m.put("ಯೃ", "AiÀÄÈ");
m.put("ಯೆ", "AiÉÄ");
m.put("ಯೇ", "AiÉÄÃ");
m.put("ಯೈ", "AiÉÄÊ");
m.put("ಯೊ", "AiÉÆ");
m.put("ಯೋ", "AiÉÆÃ");
m.put("ಯೌ", "AiÀiË");
m.put("ರ್", "gï");
m.put("ರ", "gÀ");
m.put("ರಾ", "gÁ");
m.put("ರಿ", "j");
m.put("ರೀ", "jÃ");
m.put("ರು", "gÀÄ");
m.put("ರೂ", "gÀÆ");
m.put("ರೃ", "gÀÈ");
m.put("ರೆ", "gÉ");
m.put("ರೇ", "gÉÃ");
m.put("ರೈ", "gÉÊ");
m.put("ರೊ", "gÉÆ");
m.put("ರೋ", "gÉÆÃ");
m.put("ರೌ", "gË");
m.put("ಲ್", "¯ï");
m.put("ಲ", "®");
m.put("ಲಾ", "¯Á");
m.put("ಲಿ", "°");
m.put("ಲೀ", "°Ã");
m.put("ಲು", "®Ä");
m.put("ಲೂ", "®Æ");
m.put("ಲೃ", "®È");
m.put("ಲೆ", "¯É");
m.put("ಲೇ", "¯ÉÃ");
m.put("ಲೈ", "¯ÉÊ");
m.put("ಲೊ", "¯ÉÆ");
m.put("ಲೋ", "¯ÉÆÃ");
m.put("ಲೌ", "¯Ë");
m.put("ವ್", "ªï");
m.put("ವ", "ªÀ");
m.put("ವಾ", "ªÁ");
m.put("ವಿ", "«");
m.put("ವೀ", "«Ã");
m.put("ವು", "ªÀÅ");
m.put("ವೂ", "ªÀÇ");
m.put("ವೃ", "ªÀÈ");
m.put("ವೆ", "ªÉ");
m.put("ವೇ", "ªÉÃ");
m.put("ವೈ", "ªÉÊ");
m.put("ವೊ", "ªÉÇ");
m.put("ವೋ", "ªÉÇÃ");
m.put("ವೌ", "ªË");
m.put("ಶ್", "±ï");
m.put("ಶ", "±À");
m.put("ಶಾ", "±Á");
m.put("ಶಿ", "²");
m.put("ಶೀ", "²Ã");
m.put("ಶು", "±ÀÄ");
m.put("ಶೂ", "±ÀÆ");
m.put("ಶೃ", "±ÀÈ");
m.put("ಶೆ", "±É");
m.put("ಶೇ", "±ÉÃ");
m.put("ಶೈ", "±ÉÊ");
m.put("ಶೊ", "±ÉÆ");
m.put("ಶೋ", "±ÉÆÃ");
m.put("ಶೌ", "±Ë");
m.put("ಷ್", "µï");
m.put("ಷ", "µÀ");
m.put("ಷಾ", "µÁ");
m.put("ಷಿ", "¶");
m.put("ಷೀ", "¶Ã");
m.put("ಷು", "µÀÄ");
m.put("ಷೂ", "µÀÆ");
m.put("ಷೃ", "µÀÈ");
m.put("ಷೆ", "µÉ");
m.put("ಷೇ", "µÉÃ");
m.put("ಷೈ", "µÉÊ");
m.put("ಷೊ", "µÉÆ");
m.put("ಷೋ", "µÉÆÃ");
m.put("ಷೌ", "µË");
m.put("ಸ್", "¸ï");
m.put("ಸ", "¸À");
m.put("ಸಾ", "¸Á");
m.put("ಸಿ", "¹");
m.put("ಸೀ", "¹Ã");
m.put("ಸು", "¸ÀÄ");
m.put("ಸೂ", "¸ÀÆ");
m.put("ಸೃ", "¸ÀÈ");
m.put("ಸೆ", "¸É");
m.put("ಸೇ", "¸ÉÃ");
m.put("ಸೈ", "¸ÉÊ");
m.put("ಸೊ", "¸ÉÆ");
m.put("ಸೋ", "¸ÉÆÃ");
m.put("ಸೌ", "¸Ë");
m.put("ಹ್", "ºï");
m.put("ಹ", "ºÀ");
m.put("ಹಾ", "ºÁ");
m.put("ಹಿ", "»");
m.put("ಹೀ", "»Ã");
m.put("ಹು", "ºÀÄ");
m.put("ಹೂ", "ºÀÆ");
m.put("ಹೃ", "ºÀÈ");
m.put("ಹೆ", "ºÉ");
m.put("ಹೇ", "ºÉÃ");
m.put("ಹೈ", "ºÉÊ");
m.put("ಹೊ", "ºÉÆ");
m.put("ಹೋ", "ºÉÆÃ");
m.put("ಹೌ", "ºË");
m.put("ಳ್", "¼ï");
m.put("ಳ", "¼À");
m.put("ಳಾ", "¼Á");
m.put("ಳಿ", "½");
m.put("ಳೀ", "½Ã");
m.put("ಳು", "¼ÀÄ");
m.put("ಳೂ", "¼ÀÆ");
m.put("ಳೃ", "¼ÀÈ");
m.put("ಳೆ", "¼É");
m.put("ಳೇ", "¼ÉÃ");
m.put("ಳೈ", "¼ÉÊ");
m.put("ಳೊ", "¼ÉÆ");
m.put("ಳೋ", "¼ÉÆÃ");
m.put("ಳೌ", "¼Ë");
mapping = Collections.unmodifiableMap(m);
}
private static final Map<String, String> vattaksharagalu;
static {
HashMap<String, String> v = new HashMap<String, String>();
v.put("ಕ", "Ì");
v.put("ಖ", "Í");
v.put("ಗ", "Î");
v.put("ಘ", "Ï");
v.put("ಞ", "Õ");
v.put("ಚ", "Ñ");
v.put("ಛ", "Ò");
v.put("ಜ", "Ó");
v.put("ಝ", "Ô");
v.put("ಟ", "Ö");
v.put("ಠ", "×");
v.put("ಡ", "Ø");
v.put("ಢ", "Ù");
v.put("ಣ", "Ú");
v.put("ತ", "Û");
v.put("ಥ", "Ü");
v.put("ದ", "Ý");
v.put("ಧ", "Þ");
v.put("ನ", "ß");
v.put("ಪ", "à");
v.put("ಫ", "á");
v.put("ಬ", "â");
v.put("ಭ", "ã");
v.put("ಮ", "ä");
v.put("ಯ", "å");
v.put("ರ", "æ");
v.put("ಲ", "è");
v.put("ವ", "é");
v.put("ಶ", "ê");
v.put("ಷ", "ë");
v.put("ಸ", "ì");
v.put("ಹ", "í");
v.put("ಳ", "î");
v.put("ರ", "ç");
vattaksharagalu = Collections.unmodifiableMap(v);
}
private static ArrayList<String> dependent_vowels = new ArrayList<String>();
static {
dependent_vowels.add("್");
dependent_vowels.add("ಾ");
dependent_vowels.add("ಿ");
dependent_vowels.add("ೀ");
dependent_vowels.add("ು");
dependent_vowels.add("ೂ");
dependent_vowels.add("ೃ");
dependent_vowels.add("ೆ");
dependent_vowels.add("ೇ");
dependent_vowels.add("ೈ");
dependent_vowels.add("ೊ");
dependent_vowels.add("ೋ");
dependent_vowels.add("ೌ");
}
private ArrayList<String> op;
public String convert(String knUnicode) {
ArrayList<String> aOut = new ArrayList<String>();
String[] words = knUnicode.split(" ");
for (String word : words) {
aOut.add(processWord(word));
}
return join(aOut, " ");
}
private String processWord(String word) {
// Initialize op
op = new ArrayList<String>();
int maxLen = word.length();
int i = 0;
// rearrange "್", only if in the middle of the word
int wl = word.length();
StringBuilder sbWord = new StringBuilder(word);
String v = "";
for (int zz = 1; zz < wl; zz++) {
if (word.charAt(zz) == '್') {
switch (wl - zz) {
case 0:
case 1:
// do nothing; word ending with ್
break;
case 2:
// no dependent vowels
v = vattaksharagalu
.get(String.valueOf(word.charAt(zz + 1)));
sbWord.replace(zz, zz + 1, v);
if (sbWord.length() >= (zz + 2)) {
sbWord.deleteCharAt(zz + 1);
}
break;
default:
String dv = word.substring(zz + 2, zz + 3);
// check for dependent vowels
if (dependent_vowels.contains(dv)) {
v = vattaksharagalu.get(String.valueOf(word
.charAt(zz + 1)));
sbWord.replace(zz, zz + 1, dv);
sbWord.replace(zz + 1, zz + 2, v);
sbWord.deleteCharAt(zz + 2);
} else {
v = vattaksharagalu.get(String.valueOf(word
.charAt(zz + 1)));
sbWord.replace(zz, zz + 1, v);
}
break;
}
}
}
word = sbWord.toString();
while (i < maxLen) {
// Find the mapping data
int data = find_mapping(word, i);
// Jump if data > 0 which means found a match for more than
// one letter combination
i += (1 + data);
}
return join(op, "");
}
private int find_mapping(String txt, int current_pos) {
// Finds mapping in reverse order, For Example if input string
// is abcde then itteration will be for abcde, abcd, abc, ab, a
// Only when mapping available the index jumps, say if mapping
// available for ab
// then subtract length of ab while processing next
// Combination length, if length remaining is less than max len then
// Consider length remaining as max length
// remaining length = len(txt) - current_pos
int max_len = 4;
int remaining = txt.length() - current_pos;
if (remaining < 5) {
max_len = (remaining - 1);
}
// Number of letters found mapping, will be returned to caller and
// used to jump the index (Zero if one char found mapping)
int n = 0;
// String zwj = "\u200d";
// Loop 4 to 0 or max to 0
// Controller which checks direct mapping,
// arkavattu, vattaksharagalu and broken cases
for (int i = max_len; i >= 0; i--) {
int substr_till = current_pos + i + 1;
String t = txt.substring(current_pos, substr_till);
if (mapping.containsKey(t)) {
// Direct mapping case
op.add(mapping.get(t));
// Update Jump by number
n = i;
// Break and return to caller since we found the mapping
// for given input
break;
} else {
// Try without processing till reaches to last char
if (i > 0) {
continue;
}
// No match
op.add(t);
}
}
return n;
}
private String join(ArrayList<String> s, String glue) {
int k = s.size();
if (k == 0) {
return "";
}
StringBuilder out = new StringBuilder();
out.append(s.get(0));
for (int x = 1; x < k; ++x) {
out.append(glue).append(s.get(x));
}
return out.toString();
}
}
| 23.474378 | 77 | 0.452379 |
57dfd510e903fad737afbaba67f76de842170dd9 | 3,448 | package com.ruoyi.report.controller;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.ConfigMainTable;
import com.ruoyi.report.service.IConfigMainTableService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 主的配置Controller
*
* @author wzy
* @date 2021-05-02
*/
@RestController
@RequestMapping("/report/mtable")
public class ConfigMainTableController extends BaseController
{
@Autowired
private IConfigMainTableService configMainTableService;
/**
* 查询主的配置列表
*/
@PreAuthorize("@ss.hasPermi('report:mtable:list')")
@GetMapping("/list")
public TableDataInfo list(ConfigMainTable configMainTable)
{
startPage();
List<ConfigMainTable> list = configMainTableService.selectConfigMainTableList(configMainTable);
return getDataTable(list);
}
/**
* 导出主的配置列表
*/
@PreAuthorize("@ss.hasPermi('report:mtable:export')")
@Log(title = "主的配置", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(ConfigMainTable configMainTable)
{
List<ConfigMainTable> list = configMainTableService.selectConfigMainTableList(configMainTable);
ExcelUtil<ConfigMainTable> util = new ExcelUtil<ConfigMainTable>(ConfigMainTable.class);
return util.exportExcel(list, "主的配置数据");
}
/**
* 获取主的配置详细信息
*/
@PreAuthorize("@ss.hasPermi('report:mtable:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(configMainTableService.selectConfigMainTableById(id));
}
/**
* 新增主的配置
*/
@PreAuthorize("@ss.hasPermi('report:mtable:add')")
@Log(title = "主的配置", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody ConfigMainTable configMainTable)
{
return toAjax(configMainTableService.insertConfigMainTable(configMainTable));
}
/**
* 修改主的配置
*/
@PreAuthorize("@ss.hasPermi('report:mtable:edit')")
@Log(title = "主的配置", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody ConfigMainTable configMainTable)
{
return toAjax(configMainTableService.updateConfigMainTable(configMainTable));
}
/**
* 删除主的配置
*/
@PreAuthorize("@ss.hasPermi('report:mtable:remove')")
@Log(title = "主的配置", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(configMainTableService.deleteConfigMainTableByIds(ids));
}
}
| 33.153846 | 103 | 0.732019 |
a89ded964da13924170591a4fee1bf553b33fb2c | 14,941 | /*
* Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.pipeline.controller.metadata;
import com.epam.pipeline.controller.AbstractRestController;
import com.epam.pipeline.controller.PagedResult;
import com.epam.pipeline.controller.Result;
import com.epam.pipeline.controller.vo.metadata.MetadataEntityVO;
import com.epam.pipeline.entity.metadata.FireCloudClass;
import com.epam.pipeline.entity.metadata.MetadataClass;
import com.epam.pipeline.entity.metadata.MetadataClassDescription;
import com.epam.pipeline.entity.metadata.MetadataEntity;
import com.epam.pipeline.entity.metadata.MetadataField;
import com.epam.pipeline.entity.metadata.MetadataFilter;
import com.epam.pipeline.manager.metadata.MetadataEntityApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Controller
@Api(value = "MetadataEntities")
public class MetadataEntityController extends AbstractRestController {
private static final String ID = "id";
private static final String NAME = "name";
@Autowired
private MetadataEntityApiService metadataEntityApiService;
@RequestMapping(value = "/metadataClass/register", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(
value = "Registers a new user entity class.",
notes = "Registers a new user entity class.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataClass> registerMetadataClass(@RequestParam(value = NAME) final String entityName) {
return Result.success(metadataEntityApiService.createMetadataClass(entityName));
}
@RequestMapping(value = "/metadataClass/loadAll", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(
value = "Returns all metadata classes.",
notes = "Returns all metadata classes.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<List<MetadataClass>> loadAllMetadataClasses() {
return Result.success(metadataEntityApiService.loadAllMetadataClasses());
}
@RequestMapping(value = "/metadataClass/{id}/delete", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(
value = "Deletes a metadata class, specified by id.",
notes = "Deletes a metadata class, specified by id.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataClass> deleteMetadataClass(@PathVariable(value = ID) final Long id) {
return Result.success(metadataEntityApiService.deleteMetadataClass(id));
}
@PostMapping(value = "/metadataClass/{id}/external")
@ResponseBody
@ApiOperation(
value = "Updates a metadata external class, specified by metadata's id.",
notes = "Updates a metadata external class, specified by metadata's id.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataClass> updateExternalClass(@PathVariable(value = ID) final Long id,
@RequestParam FireCloudClass externalClassName) {
return Result.success(metadataEntityApiService.updateExternalClassName(id, externalClassName));
}
@RequestMapping(value = "/metadataEntity/{id}/load", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(
value = "Registers a new user entity metadata.",
notes = "Registers a new user entity metadata.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> loadMetadataEntity(@PathVariable(value = ID) final Long id) {
return Result.success(metadataEntityApiService.loadMetadataEntity(id));
}
@RequestMapping(value = "/metadataEntity/loadExternal", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(
value = "Loads entity by externalID.",
notes = "Loads entity by externalID.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> loadMetadataEntity(@RequestParam(value = ID) final String id,
@RequestParam final String className, @RequestParam final Long folderId) {
return Result.success(metadataEntityApiService.loadByExternalId(id, className, folderId));
}
@RequestMapping(value = "/metadataEntity/filter", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(
value = "Filters and sorts metadata entities.",
notes = "Filters and sorts metadata entities.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<PagedResult<List<MetadataEntity>>> filterMetadataEntities(@RequestBody MetadataFilter filter) {
return Result.success(metadataEntityApiService.filterMetadata(filter));
}
@RequestMapping(value = "/metadataEntity/upload", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(
value = "Uploads metadata entities from a text file.",
notes = "Uploads metadata entities from a text file. "
+ "Method accepts the following file formats: csv, tsv, tdf.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<List<MetadataEntity>> uploadMetadataFromFile(@RequestParam Long parentId,
HttpServletRequest request) throws FileUploadException {
MultipartFile file = consumeMultipartFile(request);
return Result.success(metadataEntityApiService.uploadMetadataFromFile(parentId, file));
}
@RequestMapping(value = "/metadataEntity/keys", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(
value = "Returns all present keys in a folder for a MetadataClass.",
notes = "Returns all present keys in a folder for a MetadataClass.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<List<MetadataField>> getMetadataKeys(@RequestParam Long folderId,
@RequestParam String metadataClass) {
return Result.success(metadataEntityApiService.getMetadataKeys(folderId, metadataClass));
}
@RequestMapping(value = "/metadataEntity/fields", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(
value = "Returns all classes and keys in a folder recursively.",
notes = "Returns all classes and keys in a folder recursively.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<Collection<MetadataClassDescription>> getMetadataFields(@RequestParam Long folderId) {
return Result.success(metadataEntityApiService.getMetadataFields(folderId));
}
@RequestMapping(value = "/metadataEntity/{id}/delete", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(
value = "Deletes a metadata entity, specified by id.",
notes = "Deletes a metadata entity, specified by id.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> deleteMetadataEntity(@PathVariable(value = ID) final Long id) {
return Result.success(metadataEntityApiService.deleteMetadataEntity(id));
}
@RequestMapping(value = "/metadataEntity/save", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(
value = "Update user entity. If id not specified or not fount a new one will be created",
notes = "Update user entity. If id not specified or not fount a new one will be created.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> updateMetadataEntity(@RequestBody MetadataEntityVO metadataEntityVO) {
MetadataEntity entity = metadataEntityVO.getEntityId() == null ?
metadataEntityApiService.createMetadataEntity(metadataEntityVO) :
metadataEntityApiService.updateMetadataEntity(metadataEntityVO);
return Result.success(entity);
}
@RequestMapping(value = "/metadataEntity/updateKey", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(
value = "Update metadata entity item key.",
notes = "Update metadata entity item key.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> updateMetadataEntityItemKey(@RequestBody MetadataEntityVO metadataEntityVO) {
return Result.success(metadataEntityApiService.updateMetadataItemKey(metadataEntityVO));
}
@RequestMapping(value = "/metadataEntity/{id}/deleteKey", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(
value = "Deletes a metadata entity key, specified by id and class.",
notes = "Deletes a metadata entity key, specified by id and class.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<MetadataEntity> deleteMetadataItemKey(@PathVariable(value = ID) Long id,
@RequestParam(value = "key") final String key) {
return Result.success(metadataEntityApiService.deleteMetadataItemKey(id, key));
}
@DeleteMapping(value = "/metadataEntity/deleteList")
@ResponseBody
@ApiOperation(
value = "Deletes a list of metadata entities.",
notes = "Deletes a list of metadata entities.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<Set<Long>> deleteMetadataEntities(@RequestBody final Set<Long> entitiesIds) {
return Result.success(metadataEntityApiService.deleteMetadataEntities(entitiesIds));
}
@DeleteMapping(value = "/metadataEntity/deleteFromProject")
@ResponseBody
@ApiOperation(
value = "Deletes metadata entities from project.",
notes = "Deletes all metadata entities from project. " +
"If entityClass is provided, only entities of this class are deleted.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result deleteMetadataEntities(@RequestParam final Long projectId,
@RequestParam(required = false) final String entityClass) {
metadataEntityApiService.deleteMetadataFromProject(projectId, entityClass);
return Result.success();
}
@PostMapping("/metadataEntity/entities")
@ResponseBody
@ApiOperation(
value = "Loads specified metadata entities.",
notes = "Loads specified metadata entities.",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<Map<String, String>> loadEntitiesData(@RequestBody Set<Long> entitiesIds) {
return Result.success(metadataEntityApiService.loadEntitiesData(entitiesIds));
}
@GetMapping("/metadataEntity/download")
@ResponseBody
@ApiOperation(
value = "Download specified metadata entity as a csv/tsv file.",
notes = "Download specified metadata entity as a csv/tsv file.",
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public void downloadEntityAsFile(
@RequestParam final Long folderId,
@RequestParam final String entityClass,
@RequestParam(required = false, defaultValue = "tsv") final String fileFormat,
final HttpServletResponse response) throws IOException {
final InputStream inputStream =
metadataEntityApiService.getMetadataEntityFile(folderId, entityClass, fileFormat);
writeStreamToResponse(response, inputStream, String.format("%s.%s", entityClass, fileFormat));
}
}
| 47.582803 | 119 | 0.69326 |
78da8b53ec3b7edcf2d2f245b118ec2956cc0fd9 | 2,218 | package com.samon.administrator.uclass;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//设置此界面为
// 竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//portrait:竖屏 , 显示时 高 度大于 宽 度 ;
//设置全屏显示欢迎页面
hideActionBar();
setFullScreen();
init();
}
private void init() {
TextView tv_version = findViewById(R.id.tv_version);
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),0);
tv_version.setText("version:"+packageInfo.versionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
tv_version.setText("version");
}
//利用timer让此界面延迟3秒后跳转,timer有一个线程,该线程不断执行task
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
//发送intent实现页面跳转,第一个参数为当前页面的context,第二个参数为要跳转的主页
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
//跳转后关闭当前欢迎页面
SplashActivity.this.finish();
}
};
//调度执行timerTask,第二个参数传入延迟时间(毫秒)
timer.schedule(timerTask,1000);
}
//设置全屏显示欢迎页面
private void hideActionBar() {
// Hide UI
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
}
private void setFullScreen() {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
| 32.144928 | 122 | 0.656898 |
797aac96cb3bcb0583b09de3e9346195067aaf84 | 3,599 | /*
* 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 dao;
import connection.ConnectHibernate;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Gas;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
/**
*
* @author nathalianascimento
*/
public class GasDAO {
private Session session;
public void save(Gas gas) {
Transaction tx = null; //permite transacao com o BD
try {
session = (Session) ConnectHibernate.getSession();
tx = session.beginTransaction();
session.save(gas);
session.flush();
tx.commit();//faz a transacao
} catch (Exception e) {
e.printStackTrace();
//cancela a transcao em caso de falha
tx.rollback();
} finally {
session.close();
}
}
public Gas getGas(int id) {
try {
session = (Session) ConnectHibernate.getSession();
Gas gas = (Gas) session.get(model.Gas.class, new Integer(id));
session.close();
return gas;
} catch (Exception ex) {
Logger.getLogger(Gas.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public Gas getGas(String name) {
try {
session = (Session) ConnectHibernate.getSession();
Criteria criteria = session.createCriteria(model.Gas.class);
Gas gasObject = (Gas) criteria.add(Restrictions.eq("name", name)).uniqueResult();
session.close();
return gasObject;
} catch (Exception ex) {
Logger.getLogger(GasDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public Gas deleteGas(int id) {
Transaction tx = null; //permite transacao com o BD
try {
session = (Session) ConnectHibernate.getSession();
Gas gas = (Gas) session.get(model.Gas.class, new Integer(id));
tx = session.beginTransaction();
session.delete(gas);
session.flush();
tx.commit();//faz a transacao
} catch (Exception e) {
e.printStackTrace();
//cancela a transcao em caso de falha
tx.rollback();
} finally {
session.close();
}
return null;
}
public void deleteGas(Gas gas) {
Transaction tx = null; //permite transacao com o BD
try {
session = (Session) ConnectHibernate.getSession();
tx = session.beginTransaction();
session.delete(gas);
session.flush();
tx.commit();//faz a transacao
} catch (Exception e) {
e.printStackTrace();
//cancela a transcao em caso de falha
tx.rollback();
} finally {
session.close();
}
}
public List<Gas> getAll() {
try {
session = (Session) ConnectHibernate.getSession();
Query query = session.createQuery("from model.Gas");
List<Gas> list = query.list();
session.close();
return list;
} catch (Exception ex) {
Logger.getLogger(GasDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
| 29.743802 | 93 | 0.565157 |
81348227f8133489abc58430952ee7538412066d | 3,291 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.esigate.parser.future;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.esigate.HttpErrorPage;
/**
* This interface is similar to Appendable except that it is based on Future objects.
* <p>
* This allows to provide the content of the CharSequence to append at the very last moment, when all the CharSequences
* are effectively appended together.
* <p>
* While this interface allows concurrent implementation of an Appendable (based on Future), implementations are not
* required to be Thread-safe. This means that {@link #enqueueAppend(Future)}, {@link #performAppends()} and
* {@link #hasPending()} are supposed to be called for the same Thread.
* <p>
* Management of Threads concurrency must be implemented by the Future implementation which must perform all the
* synchronization work between any background Thread and the calling Thread.
*
* @author Nicolas Richeton
*
*/
public interface FutureAppendable {
/**
* Queue the Future<CharSequence> for append in this <tt>FutureAppendable</tt>.
*
* <p>
* Caller may start computing the content of the Future parameter before or after calling this method (using other
* Thread) or simply wait for Future#get() to be called (defered computation).
*
* @param csq
* The Future character sequence to append. If <tt>csq</tt> is <tt>null</tt>, then the four characters
* <tt>"null"</tt> are appended to this FutureAppendable.
*
* @return A reference to this <tt>FutureAppendable</tt>
*
* @throws IOException
* If an I/O error occurs
*/
FutureAppendable enqueueAppend(Future<CharSequence> csq) throws IOException;
/**
* Wait for all computation to complete and perform the pending append operations.
*
* @return A reference to this <tt>FutureAppendable</tt>
* @throws IOException
* @throws HttpErrorPage
*/
FutureAppendable performAppends() throws IOException, HttpErrorPage;
/**
*
* Wait for all computation to complete and perform the pending append operations.
*
* @param timeout
* @param unit
* @return FutureAppendable
* @throws IOException
* @throws HttpErrorPage
* @throws TimeoutException
*/
FutureAppendable performAppends(int timeout, TimeUnit unit) throws IOException, HttpErrorPage, TimeoutException;
/**
* Check if some append operations are still waiting for {@link #performAppends()} to be called.
*
* @return true if append operations are pending.
*/
boolean hasPending();
}
| 36.566667 | 119 | 0.701914 |
4a27e5b0169774c54c939afb6400292c479fceb7 | 2,773 | /*
* 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.aliyuncs.crm.model.v20150408;
import com.aliyuncs.RpcAcsRequest;
/**
* @author auto create
* @version
*/
public class AddIdentityCertifiedForBidUserRequest extends RpcAcsRequest<AddIdentityCertifiedForBidUserResponse> {
public AddIdentityCertifiedForBidUserRequest() {
super("Crm", "2015-04-08", "AddIdentityCertifiedForBidUser");
}
private String bidType;
private String licenseNumber;
private String licenseType;
private String phone;
private String name;
private String pK;
private Boolean isEnterprise;
public String getBidType() {
return this.bidType;
}
public void setBidType(String bidType) {
this.bidType = bidType;
if(bidType != null){
putQueryParameter("BidType", bidType);
}
}
public String getLicenseNumber() {
return this.licenseNumber;
}
public void setLicenseNumber(String licenseNumber) {
this.licenseNumber = licenseNumber;
if(licenseNumber != null){
putQueryParameter("LicenseNumber", licenseNumber);
}
}
public String getLicenseType() {
return this.licenseType;
}
public void setLicenseType(String licenseType) {
this.licenseType = licenseType;
if(licenseType != null){
putQueryParameter("LicenseType", licenseType);
}
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
if(phone != null){
putQueryParameter("Phone", phone);
}
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
if(name != null){
putQueryParameter("Name", name);
}
}
public String getPK() {
return this.pK;
}
public void setPK(String pK) {
this.pK = pK;
if(pK != null){
putQueryParameter("PK", pK);
}
}
public Boolean getIsEnterprise() {
return this.isEnterprise;
}
public void setIsEnterprise(Boolean isEnterprise) {
this.isEnterprise = isEnterprise;
if(isEnterprise != null){
putQueryParameter("IsEnterprise", isEnterprise.toString());
}
}
@Override
public Class<AddIdentityCertifiedForBidUserResponse> getResponseClass() {
return AddIdentityCertifiedForBidUserResponse.class;
}
}
| 22.007937 | 114 | 0.706816 |
bb8dd2fadd20ba7a9e2bb00b6bed9fe6e3dd1f6f | 8,119 | /*
* Copyright (c) 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eclipse.odi.cdi;
import org.eclipse.odi.cdi.context.NoOpDependentContext;
import io.micronaut.context.Qualifier;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.type.Argument;
import io.micronaut.inject.qualifiers.Qualifiers;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.AmbiguousResolutionException;
import jakarta.enterprise.inject.CreationException;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.UnsatisfiedResolutionException;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.util.TypeLiteral;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
final class OdiInstanceImpl<T> implements OdiInstance<T> {
private final OdiBeanContainer beanContainer;
private final Context context;
private final Argument<T> beanType;
private final InjectionPoint injectionPoint;
@Nullable
private final Qualifier<T> qualifier;
@Nullable
private OdiBean<T> bean;
private final Map<T, CreationalContext<T>> created = new HashMap<>();
OdiInstanceImpl(OdiBeanContainer beanContainer,
@Nullable
Context context,
Argument<T> beanType,
@Nullable InjectionPoint injectionPoint,
@Nullable Qualifier<T> qualifier) {
this.beanContainer = beanContainer;
this.context = context == null ? NoOpDependentContext.INSTANCE : context;
this.beanType = beanType;
this.qualifier = qualifier;
this.injectionPoint = injectionPoint;
}
OdiInstanceImpl(OdiBeanContainer beanContainer,
@Nullable
Context context,
Argument<T> beanType,
Annotation... annotations) {
this(beanContainer, context, beanType, null, beanContainer.getOdiAnnotations().resolveQualifier(annotations));
}
@Override
@NonNull
public <U extends T> Instance<U> select(@NonNull Argument<U> argument, @Nullable Qualifier<U> qualifier) {
if (InjectionPoint.class.equals(argument.getType()) && injectionPoint != null) {
//noinspection unchecked
return new ResolvedInstanceImpl<>((U) injectionPoint);
} else {
return new OdiInstanceImpl<>(
beanContainer,
context,
argument,
null,
withQualifier(qualifier)
);
}
}
@Override
public Instance<T> select(Annotation... qualifiers) {
return new OdiInstanceImpl<>(
beanContainer,
context,
beanType,
null,
withAnnotations(qualifiers)
);
}
@Override
public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers) {
return select(Argument.of(subtype), withAnnotations(qualifiers));
}
@SuppressWarnings({"unchecked"})
@Override
public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
return select((Argument<U>) Argument.of(subtype.getType()), withAnnotations(qualifiers));
}
@Override
public boolean isUnsatisfied() {
try {
getBean();
return false;
} catch (UnsatisfiedResolutionException e) {
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean isAmbiguous() {
try {
getBean();
return false;
} catch (AmbiguousResolutionException e) {
return true;
} catch (Exception e) {
return false;
}
}
@Override
public void destroy(T instance) {
CreationalContext<T> creationalContext = created.get(instance);
if (creationalContext != null) {
creationalContext.release();
} else {
beanContainer.getBeanContext().destroyBean(instance);
}
}
@Override
public Handle<T> getHandle() {
return toHandle(getBean());
}
private OdiBean<T> getBean() {
try {
Qualifier<T> beanQualifier = this.qualifier;
if (beanQualifier == null) {
beanQualifier = DefaultQualifier.instance();
}
if (bean == null) {
bean = beanContainer.getBean(beanType, beanQualifier);
}
return bean;
} catch (UnsatisfiedResolutionException | AmbiguousResolutionException e) {
throw e;
} catch (Exception e) {
throw new CreationException(e.getMessage(), e);
}
}
private Handle<T> toHandle(OdiBean<T> odiBean) {
return new Handle<>() {
private CreationalContext<T> creationalContext;
private boolean destroyed;
@Override
public T get() {
if (destroyed) {
throw new IllegalStateException("Instance already destroyed!");
}
if (creationalContext == null) {
creationalContext = beanContainer.createCreationalContext(odiBean);
}
return context.get(odiBean, creationalContext);
}
@Override
public Bean<T> getBean() {
return odiBean;
}
@Override
public void destroy() {
if (destroyed || creationalContext == null) {
return;
}
creationalContext.release();
creationalContext = null;
destroyed = true;
}
@Override
public void close() {
destroy();
}
};
}
@Override
public List<Handle<T>> handles() {
return beanContainer.getBeans(beanType, qualifier).stream()
.map(this::toHandle)
.collect(Collectors.toList());
}
@Override
public T get() {
Bean<T> resolvedBean = getBean();
CreationalContext<T> creationalContext = beanContainer.createCreationalContext(resolvedBean);
T instance = context.get(resolvedBean, creationalContext);
created.put(instance, creationalContext);
return instance;
}
@Override
@NonNull
public Iterator<T> iterator() {
return stream().iterator();
}
@Override
public Stream<T> stream() {
return handles().stream().map(Handle::get);
}
private <K> Qualifier<K> withAnnotations(Annotation[] qualifiers) {
return withQualifier(beanContainer.getOdiAnnotations().resolveQualifier(qualifiers));
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <K> Qualifier<K> withQualifier(Qualifier<?> newQualifier) {
if (qualifier == null) {
return (Qualifier<K>) newQualifier;
}
if (newQualifier != null) {
return Qualifiers.byQualifiers(qualifier, (Qualifier) newQualifier);
}
return (Qualifier<K>) qualifier;
}
}
| 31.964567 | 118 | 0.608572 |
6383c74e096b5841090f15bb4e77cb0a6aea795d | 194 | package com.betfair.aping.betting.enums;
import javax.annotation.Generated;
@Generated("pt.paulosantos.betfair.aping.codegen")
public enum TimeGranularity {
DAYS,
HOURS,
MINUTES
}
| 17.636364 | 50 | 0.752577 |
73fdb3671501cfa174d73d401ac7f79e8b313a80 | 689 | package com.heeexy.example.dao;
import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.util.model.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface StudentDao extends Mapper<Student> {
@Select("SELECT id, sname,sex*1 as sex,phone,studentnumber,academy,classes,resume FROM student WHERE '1' = '1' ORDER BY id DESC")
List<JSONObject> list();
@Update("UPDATE student set resume=#{resume} WHERE id=#{id};")
boolean updateResume(@Param("resume") String resume, @Param("id") Integer id);
}
| 36.263158 | 134 | 0.759071 |
cdfe54cd624a3f2603738f2e6af95299b0157e37 | 31,579 | package com.zw.platform.service.carbonmgt.impl;
import com.alibaba.fastjson.JSON;
import com.zw.platform.basic.dto.VehicleDTO;
import com.zw.platform.basic.repository.NewVehicleDao;
import com.zw.platform.commons.HttpClientUtil;
import com.zw.platform.commons.SystemHelper;
import com.zw.platform.domain.basicinfo.VehicleInfo;
import com.zw.platform.domain.core.OrganizationLdap;
import com.zw.platform.domain.oil.Positional;
import com.zw.platform.domain.vas.carbonmgt.EnergySavingProductsDataBeforeExport1;
import com.zw.platform.domain.vas.carbonmgt.EnergySavingProductsDataBeforeExport2;
import com.zw.platform.domain.vas.carbonmgt.TimingStored;
import com.zw.platform.domain.vas.carbonmgt.form.MileageForm;
import com.zw.platform.domain.vas.carbonmgt.form.MobileSourceEnergyReportForm;
import com.zw.platform.domain.vas.carbonmgt.query.MileageQuery;
import com.zw.platform.repository.vas.BasicManagementDao;
import com.zw.platform.service.carbonmgt.EnergySavingProductsDataBeforeService;
import com.zw.platform.service.core.UserService;
import com.zw.platform.util.CalculateUtil;
import com.zw.platform.util.CollectionsSortUtil;
import com.zw.platform.util.common.BusinessException;
import com.zw.platform.util.common.Converter;
import com.zw.platform.util.common.RegexUtils;
import com.zw.platform.util.common.UuidUtils;
import com.zw.platform.util.excel.ExportExcel;
import com.zw.platform.util.paas.PaasCloudUrlUtil;
import com.zw.platform.util.report.PaasCloudHBaseAccessEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@Service
public class EnergySavingProductsDataBeforeServiceImpl implements EnergySavingProductsDataBeforeService {
private static Logger log = LogManager.getLogger(EnergySavingProductsDataBeforeServiceImpl.class);
private static DecimalFormat df = new DecimalFormat("0.0000");
private static DecimalFormat df_1 = new DecimalFormat("0.0"); // 保留一位小数
private static DecimalFormat df_2 = new DecimalFormat("0.00"); // 保留两位小数
@Autowired
private UserService userService;
@Autowired
private NewVehicleDao newVehicleDao;
@Autowired
private BasicManagementDao basicManagementDao;
@Override
public List<VehicleInfo> getVehicleInfoList(String groupId) throws Exception {
// 获取当前用户id
String userId = SystemHelper.getCurrentUser().getId().toString();
List<OrganizationLdap> userOrgListId = userService.getOrgChild(groupId);
List<String> orgChildList = new ArrayList<>();
if (null != userOrgListId && userOrgListId.size() > 0) {
for (OrganizationLdap o : userOrgListId) {
orgChildList.add(Converter.toBlank(o.getUuid()));
}
}
List<VehicleInfo> list = newVehicleDao.findVehicleByUserAndGroupForVasMileage(userId, orgChildList);
return list;
}
@Override
public List<MobileSourceEnergyReportForm> queryByDate(String queryWay, String startDate, String endDate,
String groupId, String vehicleId) throws Exception {
List<MobileSourceEnergyReportForm> list = new ArrayList<>();
List<VehicleInfo> vehicleInfoList = null;
try {
vehicleInfoList = getVehicleInfoList(groupId);
} catch (BusinessException e) {
log.error("error", e);
}
List<Positional> positionalList = null;
// step1:查询出时间段内所有数据
final long startDate1 = Converter.convertToUnixTimeStamp(startDate);
final long endDate1 = Converter.convertToUnixTimeStamp(endDate);
if (Converter.toBlank(vehicleId).equals("")) {
List<String> vidList = new ArrayList<>();
if (null != vehicleInfoList && vehicleInfoList.size() > 0) {
for (VehicleInfo v : vehicleInfoList) {
vidList.add(Converter.toBlank(v.getId()));
}
}
positionalList = getPositionalList_statistics_time(vehicleId, startDate1, endDate1, vidList);
} else {
positionalList = getPositionalList_statistics_time(vehicleId, startDate1, endDate1, null);
}
if (Converter.toBlank(queryWay).equals("list1") || Converter.toBlank(queryWay).equals("list2")) { // 按日期统计
// step2:提取出所有的时间:时间格式yyyy-MM-dd(List<String> timeList)
List<String> timeList = getTimeList(positionalList);
// step3:把一个时间下面的所有记录整理出来:(Map<String, Map<String, List<Positional>>> map)
Map<String, Map<String, List<Positional>>> map = getMap(timeList, positionalList);
// step4:按查询方式,计算出相应统计方式下,对应的显示值
list = setFormValue_date(map, queryWay);
}
return list;
}
private List<Positional> getPositionalList_statistics_time(String vehicleId, long startDate1, long endDate1,
List<String> vidList) {
final Map<String, String> params = new HashMap<>(8);
params.put("vidList", JSON.toJSONString(vidList));
params.put("startTime", String.valueOf(startDate1));
params.put("endTime", String.valueOf(endDate1));
params.put("vehicle", vehicleId);
String str = HttpClientUtil.send(PaasCloudHBaseAccessEnum.FIND_POSITIONAL_LIST_STATISTICS_TIME, params);
return PaasCloudUrlUtil.getResultListData(str, Positional.class);
}
/**
* step2:提取出所有的时间:时间格式yyyy-MM-dd(List<String> timeList)
* @param positionalList
* @return List<String>
* @throws
* @Title: getTimeList
* @author Liubangquan
*/
private List<String> getTimeList(List<Positional> positionalList) {
List<String> timeList = null;
if (null != positionalList && positionalList.size() > 0) {
for (Positional p : positionalList) {
boolean flag = false; // 用来标记相同的时间是否已经放到list中
String vtimeStr =
Converter.toBlank(p.getVtime()).equals("") ? "" : Converter.convertUnixToDatetime(p.getVtime());
p.setVtimeStr(vtimeStr);
String time = Converter.toBlank(vtimeStr).equals("") ? "" : vtimeStr.substring(0, 10);
if (null == timeList) {
timeList = new ArrayList<>();
if (!"".equals(time)) {
timeList.add(time);
}
} else {
for (String str : timeList) {
if (time.equals(str)) {
flag = true;
break;
}
}
if (!flag) {
if (!"".equals(time)) {
timeList.add(time);
}
}
}
}
}
return timeList;
}
/**
* step3:把一个时间下面的所有记录整理出来:(Map<String, Map<String, List<Positional>>> map)
* @param timeList
* @param positionalList
* @return Map<String, Map < String, List < Positional>>>
* @throws
* @Title: getMap
* @author Liubangquan
*/
private Map<String, Map<String, List<Positional>>> getMap(List<String> timeList, List<Positional> positionalList) {
Map<String, Map<String, List<Positional>>> map = null;
Map<String, List<Positional>> positionalMap = null;
if (null != timeList && timeList.size() > 0) {
map = new HashMap<>();
for (String str : timeList) {
List<Positional> tempPList = new ArrayList<>(); // 相同时间下所有的车
for (Positional p : positionalList) {
String time = Converter.toBlank(p.getVtimeStr()).equals("") ? "" :
Converter.toBlank(p.getVtimeStr()).substring(0, 10);
if (str.equals(time)) {
tempPList.add(p);
}
}
if (null != tempPList && tempPList.size() > 0) {
List<String> vidList = new ArrayList<>(); // 车辆id集合
// 把所有不重复的vid放入vidList
for (Positional p1 : tempPList) {
String vid = String.valueOf(UuidUtils.getUUIDFromBytes(p1.getVehicleId()));
vidList.add(vid);
}
// 去重
if (null != vidList && vidList.size() > 0) {
vidList = removeDuplicateValue(vidList);
}
// 把vid一样的记录放入map
if (null != vidList && vidList.size() > 0) {
positionalMap = new HashMap<>();
List<Positional> poList = null;
for (String v : vidList) {
poList = new ArrayList<>();
for (Positional p : tempPList) {
if (v.equals(UuidUtils.getUUIDStrFromBytes(p.getVehicleId()))) {
poList.add(p);
}
}
positionalMap.put(v, poList);
}
}
}
map.put(str, positionalMap);
}
}
return map;
}
/**
* List去重
* @param list
* @return List<String>
* @throws
* @Title: removeDuplicateValue
* @author Liubangquan
*/
private List<String> removeDuplicateValue(List<String> list) {
if (null != list && list.size() > 0) {
HashSet<String> h = new HashSet<String>(list);
list.clear();
list.addAll(h);
return list;
}
return null;
}
/**
* step4:按查询方式,计算出相应统计方式下,对应的显示值
* @param map
* @param queryWay
* @return List<MobileSourceEnergyReportForm>
* @throws
* @Title: setFormValue_date
* @author Liubangquan
*/
private List<MobileSourceEnergyReportForm> setFormValue_date(Map<String, Map<String, List<Positional>>> map,
String queryWay) {
List<MobileSourceEnergyReportForm> list = new ArrayList<>();
if (null != map && map.size() > 0) {
for (Map.Entry<String, Map<String, List<Positional>>> entry : map.entrySet()) {
String time = entry.getKey();
Map<String, List<Positional>> map1 = entry.getValue();
if (null != map1 && map1.size() > 0) {
for (Map.Entry<String, List<Positional>> entry1 : map1.entrySet()) {
List<MobileSourceEnergyReportForm> list1 = new ArrayList<>();
List<Positional> positionalList = entry1.getValue();
mergePositional(time, positionalList, list1);
if (Converter.toBlank(queryWay).equals("list1")) {
calculateForm_queryByDate(list, list1);
} else {
calculateForm(list, list1);
}
}
}
}
}
CollectionsSortUtil sort = new CollectionsSortUtil();
sort.sortByMethod_mobileS(list, "getTime", true);
return list;
}
private void mergePositional(String time, List<Positional> positionalList,
List<MobileSourceEnergyReportForm> list) {
boolean flag = false; // acc开关标识
int acc = 0; // acc状态默认为0
int air = 0; // 空调开启状态默认为0
String startDateAir = ""; // 空调开启时间
String endDateAir = ""; // 空调关闭时间
double airTime = 0; // 空调开启时长
MobileSourceEnergyReportForm tesf = null;
if (null != positionalList && positionalList.size() > 0) {
for (int i = 0; i < positionalList.size(); i++) {
Positional p = positionalList.get(i);
acc = CalculateUtil.getStatus(Converter.toBlank(p.getStatus())).getInteger("acc");
air = Converter.toInteger(p.getAirConditionStatus(), 0);
String date =
Converter.toBlank(p.getVtimeStr()).equals("") ? Converter.convertUnixToDatetime(p.getVtime()) :
Converter.toBlank(p.getVtimeStr());
//-------------空调时长计算-start--------------
if (acc == 1 && air != 0 && startDateAir.equals("")) {
startDateAir = date;
}
if (acc == 1 && air == 0) { // 空调关
if (endDateAir.equals("") && !startDateAir.equals("")) {
endDateAir = date;
double duration = Converter.toDouble(CalculateUtil.toDateTime(endDateAir, startDateAir));
airTime += duration;
startDateAir = "";
endDateAir = "";
}
} else if (endDateAir.equals("") && !startDateAir.equals("")) {
if (i == positionalList.size() - 1) {
endDateAir =
Converter.toBlank(positionalList.get(positionalList.size() - 1).getVtimeStr()).equals("")
?
Converter
.convertUnixToDatetime(positionalList.get(positionalList.size() - 1).getVtime()) :
Converter.toBlank(positionalList.get(positionalList.size() - 1).getVtimeStr());
double duration = Converter.toDouble(CalculateUtil.toDateTime(endDateAir, startDateAir));
airTime += duration;
startDateAir = "";
endDateAir = "";
}
}
// --------------空调时长计算-end-------------------
if (flag) { // 表示acc为1了,已经打火用于判断打火熄火这一过程是否满足2次,如不满足则不记录
if (acc == 0) {
tesf.setEndDate(date);
tesf.setEndOil(Converter.toBlank(p.getTotalOilwearOne()));
tesf.setAirConditionerDuration(Converter.toBlank(airTime));
tesf.setTotalFuelConsumption(
Converter.toBlank(CalculateUtil.getTotalFuel(tesf.getStartOil(), tesf.getEndOil())));
tesf.setEndMileage(Converter.toBlank(p.getGpsMile(), "0"));
Double start = Double.parseDouble(tesf.getStartMileage());
Double end = Double.parseDouble(tesf.getEndMileage());
String mileage = String.valueOf((end - start) / 10);
tesf.setMileage(Converter.toBlank(mileage));
// 当【熄火时间】减去【打火时间】小于60秒的话过滤掉该条记录;
String duration = CalculateUtil.toDateTime(tesf.getEndDate(), tesf.getStartDate());
if (Converter.toDouble(duration) >= Converter.toDouble(1 / 60)) {
tesf.setDuration(CalculateUtil.toDateTime(tesf.getEndDate(), tesf.getStartDate()));
list.add(tesf);
}
tesf = null;
}
flag = false;
}
if (acc == 1 && tesf == null) { // 表示打火开始
flag = true;
tesf = new MobileSourceEnergyReportForm();
tesf.setTime(time);
tesf.setVehicleId(Converter.toBlank(p.getVehicleId()));
tesf.setBrand(Converter.toBlank(p.getPlateNumber()));
tesf.setVehicleType(Converter.toBlank(p.getVehicleType()));
tesf.setFuelType(Converter.toBlank(p.getFuelType()));
tesf.setStartDate(date);
tesf.setStartMileage(Converter.toBlank(p.getGpsMile(), "0"));
tesf.setStartOil(Converter.toBlank(p.getTotalOilwearOne()));
tesf.setAirConditionerDuration(Converter.toBlank(airTime));
}
if (tesf != null && !flag) {
if (acc == 1) {
// 行驶过程,每次更新行驶末尾状态
tesf.setEndDate(date);
tesf.setEndOil(Converter.toBlank(p.getTotalOilwearOne()));
tesf.setDuration(CalculateUtil.toDateTime(tesf.getEndDate(), tesf.getStartDate()));
tesf.setAirConditionerDuration(Converter.toBlank(airTime));
tesf.setTotalFuelConsumption(
Converter.toBlank(CalculateUtil.getTotalFuel(tesf.getStartOil(), tesf.getEndOil())));
tesf.setEndMileage(Converter.toBlank(p.getGpsMile(), "0"));
Double start = Double.parseDouble(tesf.getStartMileage());
Double end = Double.parseDouble(tesf.getEndMileage());
String mileage = String.valueOf((end - start) / 10);
tesf.setMileage(Converter.toBlank(mileage));
//如果是最后一条记录,则需要写入list,否则到不符合怠速再写入list已经超过查询时间范围了,就会丢失一段行驶记录
String tempS = Converter.toBlank(tesf.getStartDate()).substring(0, 10);
String tempE = Converter.toBlank(tesf.getEndDate()).substring(0, 10);
if (!tempS.equals(tempE)) { // 不是同一天的数据
// 找到前一天的最后一条记录
long begin1 = Converter.convertToUnixTimeStamp(tempS + " 00:00:00");
long end1 = Converter.convertToUnixTimeStamp(tempS + " 23:59:59");
final String vehicleId = String.valueOf(UuidUtils.getUUIDFromBytes(p.getVehicleId()));
List<Positional> tempList = getLastPositional(begin1, end1, vehicleId);
if (null != tempList && tempList.size() > 0) {
Positional pi = tempList.get(0);
tesf.setEndDate(Converter.convertUnixToDatetime(pi.getVtime()));
tesf.setEndOil(Converter.toBlank(pi.getTotalOilwearOne()));
tesf.setDuration(CalculateUtil.toDateTime(tesf.getEndDate(), tesf.getStartDate()));
tesf.setAirConditionerDuration(Converter.toBlank(airTime));
tesf.setTotalFuelConsumption(Converter
.toBlank(CalculateUtil.getTotalFuel(tesf.getStartOil(), tesf.getEndOil())));
list.add(tesf);
}
tesf = null;
}
if (i == positionalList.size() - 1) {
list.add(tesf);
tesf = null;
}
} else {
// 行驶结束,写入list
// 如果只有开始时间,则舍弃这条数据
if (tesf != null && tesf.getEndDate() != null) {
list.add(tesf);
}
tesf = null;
}
}
}
}
}
private List<Positional> getLastPositional(long startTime, long endTime, String vehicleId) {
final Map<String, String> params = new HashMap<>(8);
params.put("vehicleId", vehicleId);
params.put("startTime", String.valueOf(startTime));
params.put("endTime", String.valueOf(endTime));
String str = HttpClientUtil.send(PaasCloudHBaseAccessEnum.FIND_LAST_POSITIONAL, params);
return PaasCloudUrlUtil.getResultListData(str, Positional.class);
}
private void calculateForm(List<MobileSourceEnergyReportForm> list, List<MobileSourceEnergyReportForm> list1) {
if (null != list1 && list1.size() > 0) {
double totalFuel = 0;
double duration = 0;
double mileage = 0;
double airDuration = 0;
MobileSourceEnergyReportForm t = list1.get(0);
VehicleDTO vehicleDTO = newVehicleDao.getDetailById(t.getVehicleId());
String fuelType = getFuelTypeName(vehicleDTO.getFuelType());
String carCity = RegexUtils.getAreaByBrand(Converter.toBlank(vehicleDTO.getName())); // 根据车牌号首字获取其所在的省份
List<TimingStored> priceList =
basicManagementDao.oilPricesQuery(t.getTime(), t.getTime(), carCity, fuelType);
String oilPrice = (null != priceList && priceList.size() > 0) ? priceList.get(0).getOilPrice() : "0";
for (MobileSourceEnergyReportForm t1 : list1) {
totalFuel += Converter.toDouble(t1.getTotalFuelConsumption());
duration += Converter.toDouble(t1.getDuration());
airDuration += Converter.toDouble(t1.getAirConditionerDuration());
mileage += Converter.toDouble(t1.getMileage());
}
String averageSpeed = CalculateUtil.averageSpeed(Converter.toBlank(mileage), duration);
double totalFuelFee = Converter.toDouble(totalFuel, 0.0) * Converter.toDouble(oilPrice, 0.0);
String energy100 = Converter.toDouble(mileage) > 0
?
df.format(Converter.toDouble(totalFuel) / (Converter.toDouble(mileage) * 100)) : "0";
String reduceEmissionsCo2 = CalculateUtil.getReduceEmissions_CO2(Converter.toBlank(totalFuel), fuelType);
t.setVehicleType(vehicleDTO.getVehicleType());
t.setFuelType(vehicleDTO.getFuelType());
t.setDuration(CalculateUtil.converHourToYYYYMMDD(Converter.toBlank(duration)));
t.setAirConditionerDuration(CalculateUtil.converHourToYYYYMMDD(Converter.toBlank(airDuration)));
t.setTotalFuelConsumption(df_2.format(totalFuel));
t.setAverageSpeed(df_2.format(Converter.toDouble(averageSpeed)));
t.setMileage(df_1.format(Converter.toDouble(mileage)));
t.setEnergyPrice(df_2.format(Converter.toDouble(oilPrice)));
t.setEnergyTotalFee(df_2.format(totalFuelFee));
t.setEnergy_100(df_2.format(Converter.toDouble(energy100)));
t.setEmissions_CO2(df_2.format(Converter.toDouble(reduceEmissionsCo2)));
t.setEmissions_SO2("");
t.setEmissions_NOX("");
t.setEmissions_HCX("");
list.add(t);
}
}
private void calculateForm_queryByDate(List<MobileSourceEnergyReportForm> list,
List<MobileSourceEnergyReportForm> list1) {
if (null != list1 && list1.size() > 0) {
double totalFuel = 0;
double duration = 0;
double airDuration = 0;
double mileage = 0;
if (null != list1 && list1.size() > 0) {
for (MobileSourceEnergyReportForm t : list1) {
VehicleDTO vehicleDTO = newVehicleDao.getDetailById(t.getVehicleId());
String fuelType = getFuelTypeName(vehicleDTO.getFuelType());
String carCity =
RegexUtils.getAreaByBrand(Converter.toBlank(vehicleDTO.getName())); // 根据车牌号首字获取其所在的省份
List<TimingStored> priceList =
basicManagementDao.oilPricesQuery(t.getTime(), t.getTime(), carCity, fuelType);
String oilPrice =
(null != priceList && priceList.size() > 0) ? priceList.get(0).getOilPrice() : "0";
totalFuel = Converter.toDouble(t.getTotalFuelConsumption());
double totalFuelFee =
Converter.toDouble(t.getTotalFuelConsumption(), 0.0) * Converter.toDouble(oilPrice, 0.0);
duration = Converter.toDouble(t.getDuration());
airDuration = Converter.toDouble(t.getAirConditionerDuration());
mileage = Converter.toDouble(t.getMileage());
String averageSpeed = CalculateUtil.averageSpeed(t.getMileage(), duration);
String energy100 = Converter.toDouble(mileage) > 0
?
df.format(Converter.toDouble(totalFuel) / (Converter.toDouble(mileage) * 100)) : "0";
String reduceEmissionsCo2 =
CalculateUtil.getReduceEmissions_CO2(Converter.toBlank(totalFuel), fuelType);
t.setVehicleType(vehicleDTO.getVehicleType());
t.setFuelType(vehicleDTO.getFuelType());
t.setDuration(CalculateUtil.converHourToYYYYMMDD(Converter.toBlank(duration)));
t.setAirConditionerDuration(CalculateUtil.converHourToYYYYMMDD(Converter.toBlank(airDuration)));
t.setTotalFuelConsumption(df_2.format(totalFuel));
t.setAverageSpeed(df_2.format(Converter.toDouble(averageSpeed)));
t.setMileage(df_1.format(Converter.toDouble(mileage)));
t.setEnergyPrice(df_2.format(Converter.toDouble(oilPrice, 0.0)));
t.setEnergyTotalFee(df_2.format(totalFuelFee));
t.setEnergy_100(df_2.format(Converter.toDouble(energy100)));
t.setEmissions_CO2(df_2.format(Converter.toDouble(reduceEmissionsCo2)));
t.setEmissions_SO2("");
t.setEmissions_NOX("");
t.setEmissions_HCX("");
list.add(t);
}
}
}
}
public List<MileageForm> dealPositionalList(List<Positional> positionalList) {
List<MileageForm> list = new ArrayList<MileageForm>();
boolean flag = false;// 判断行驶状态开始标识
MileageForm energy = null;
int acc = 0;
Positional temp = null;
for (int i = 0, len = positionalList.size(); i < len; i++) {
temp = positionalList.get(i);
acc = CalculateUtil.getStatus(String.valueOf(temp.getStatus())).getInteger("acc");
String date = String.valueOf(temp.getVtimeStr());
String longtitude = String.valueOf(temp.getLongtitude());
String latitude = String.valueOf(temp.getLatitude());
String coordinate = String.valueOf(longtitude + "," + latitude);
// 表示前一次数据开始记录行驶,用于判断行驶状态是否满足2次,如不满足则不记录
if (flag) {
if (acc == 0) {
energy = null;
}
flag = false;
}
if (acc == 1 && energy == null) {
flag = true;
energy = new MileageForm();
energy.setStartDate(Converter.toBlank(date));
energy.setStartCoordinate(Converter.toBlank(coordinate));
energy.setStartOil(Converter.toBlank(temp.getTotalOilwearOne()));
energy.setFuelType(Converter.toBlank(temp.getFuelType()));
energy.setVehicleId(Converter.toBlank(temp.getVehicleId()));
energy.setVehicleType(Converter.toBlank(temp.getVehicleType()));
}
if (energy != null && !flag) {
if (acc == 1) {
// 行驶过程,每次更新行驶末尾状态
energy.setEndDate(Converter.toBlank(date));
energy.setEndCoordinate(Converter.toBlank(coordinate));
energy.setEndOil(Converter.toBlank(temp.getTotalOilwearOne()));
energy.setDuration(CalculateUtil.toDateTime(energy.getEndDate(), energy.getStartDate()));
energy.setBrand(Converter.toBlank(temp.getPlateNumber()));
//如果是最后一条记录,则需要写入list,否则到不符合怠速再写入list已经超过查询时间范围了,就会丢失一段行驶记录
if (i == positionalList.size() - 1) {
energy.setBrand(Converter.toBlank(temp.getPlateNumber()));
list.add(energy);
}
} else {
// 行驶结束,写入list
// 如果只有开始时间,则舍弃这条数据
if (energy != null && energy.getEndDate() != null) {
energy.setBrand(Converter.toBlank(temp.getPlateNumber()));
list.add(energy);
}
energy = null;
}
}
}
return list;
}
/**
* 获取燃料类型名称
* @param fuelType
* @return String
* @throws
* @Title: getFuelTypeName
* @author Liubangquan
*/
private String getFuelTypeName(String fuelType) {
String result = "";
if (Converter.toBlank(fuelType).indexOf("柴油") != -1) {
result = "柴油";
} else if (Converter.toBlank(fuelType).indexOf("汽油") != -1) {
result = "汽油";
} else if (Converter.toBlank(fuelType).indexOf("CNG") != -1) {
result = "CNG";
}
return result;
}
@Override
public boolean export(String title, int type, HttpServletResponse response, MileageQuery query) throws Exception {
String startTime = query.getStartDate();
String endTime = query.getEndDate();
String queryWay = query.getQueryWay();
String groupId = query.getGroupId();
String vehicleId = query.getBrand();
OrganizationLdap org = userService.findOrganization(groupId);
String groupName = org.getName();
String time = null;
if (queryWay.equals("list1") || queryWay.equals("list2")) {
time = startTime + "--" + endTime;
}
String groups = "企业名称:" + groupName;
ExportExcel export = null;
List<MobileSourceEnergyReportForm> list = queryByDate(queryWay, startTime, endTime, groupId, vehicleId);
if (queryWay.equals("list1")) {
export = new ExportExcel(title, EnergySavingProductsDataBeforeExport1.class, 1, time, groups, null);
List<EnergySavingProductsDataBeforeExport1> exportList2 =
new ArrayList<EnergySavingProductsDataBeforeExport1>();
for (MobileSourceEnergyReportForm info : list) {
EnergySavingProductsDataBeforeExport1 form = new EnergySavingProductsDataBeforeExport1();
info.setGroupName(groupName);
BeanUtils.copyProperties(info, form);
exportList2.add(form);
}
export.setDataList(exportList2);
} else {
export = new ExportExcel(title, EnergySavingProductsDataBeforeExport2.class, 1, time, groups, null);
List<EnergySavingProductsDataBeforeExport2> exportList1 =
new ArrayList<EnergySavingProductsDataBeforeExport2>();
for (MobileSourceEnergyReportForm info : list) {
EnergySavingProductsDataBeforeExport2 form = new EnergySavingProductsDataBeforeExport2();
info.setGroupName(groupName);
BeanUtils.copyProperties(info, form);
exportList1.add(form);
}
export.setDataList(exportList1);
}
OutputStream out = response.getOutputStream();
export.write(out);// 将文档对象写入文件输出流
out.close();
return true;
}
}
| 50.045959 | 119 | 0.561766 |
071cdefcce881821c8f1cfb10121c8fdd4839e65 | 3,038 | package com.scj.beilu.app.ui.course;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import com.mx.pro.lib.smartrefresh.layout.api.RefreshLayout;
import com.scj.beilu.app.R;
import com.scj.beilu.app.base.BaseMvpFragment;
import com.scj.beilu.app.listener.OnItemClickListener;
import com.scj.beilu.app.mvp.course.CourseListPre;
import com.scj.beilu.app.mvp.course.bean.CourseInfoBean;
import com.scj.beilu.app.ui.course.adapter.CourseListAdapter;
import java.util.List;
/**
* @author Mingxun
* @time on 2019/3/20 17:15
*/
public class CourseListFrag extends BaseMvpFragment<CourseListPre.CourseListView, CourseListPre>
implements CourseListPre.CourseListView, OnItemClickListener<CourseInfoBean> {
private static final String COURSE_TYPE_ID = "type_id";
private int mCourseTypeId;
private CourseListAdapter mHomeCourseListAdapter;
public static CourseListFrag newInstance(int courseTypeId) {
Bundle args = new Bundle();
args.putInt(COURSE_TYPE_ID, courseTypeId);
CourseListFrag fragment = new CourseListFrag();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null) {
mCourseTypeId = arguments.getInt(COURSE_TYPE_ID);
}
}
@Override
public CourseListPre createPresenter() {
return new CourseListPre(mFragmentActivity);
}
@Nullable
@Override
public int getLayout() {
return R.layout.frag_course_list;
}
@Override
public void initView() {
super.initView();
mRecyclerView = findViewById(R.id.rv_course_list);
mHomeCourseListAdapter = new CourseListAdapter(this);
mHomeCourseListAdapter.setOnItemClickListener(this);
mRecyclerView.setAdapter(mHomeCourseListAdapter);
mRefreshLayout.autoRefresh();
}
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
super.onRefresh(refreshLayout);
getPresenter().getCourseList(mCourseTypeId, mCurrentPage);
}
@Override
public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
super.onLoadMore(refreshLayout);
getPresenter().getCourseList(mCourseTypeId, mCurrentPage);
}
@Override
public void onCheckLoadMore(List<?> list) {
checkIsLoadMore(list);
}
@Override
public void onCourseListResult(List<CourseInfoBean> courseInfoBeanList) {
mHomeCourseListAdapter.setCourseInfoList(courseInfoBeanList);
}
@Override
public void onItemClick(int position, CourseInfoBean entity, View view) {
Intent intent = new Intent(mFragmentActivity, CourseInfoAct.class);
intent.putExtra(CourseInfoAct.EXTRA_COURSE_ID, entity.getCourseId());
startActivity(intent);
}
}
| 30.079208 | 96 | 0.718565 |
983cd00cd055d9448304fd3e4705334346247ce1 | 808 | /*
* @author Mg Than Htike Aung {@literal <[email protected]@address>}
* @Since 1.0
*
*/
package com.mycom.products.springMybatisGenericExample.core.service.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mycom.products.springMybatisGenericExample.core.bean.config.RoleBean;
import com.mycom.products.springMybatisGenericExample.core.dao.config.RoleDao;
import com.mycom.products.springMybatisGenericExample.core.service.base.JoinedServiceImpl;
import com.mycom.products.springMybatisGenericExample.core.service.config.api.RoleService;
@Service
public class RoleServiceImpl extends JoinedServiceImpl<RoleBean> implements RoleService {
@Autowired
public RoleServiceImpl(RoleDao dao) {
super(dao, dao);
}
}
| 32.32 | 90 | 0.821782 |
72babf84ce86b994594ec83d45e189f06c627490 | 4,242 | /*
* Copyright 2001-2013 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.time.chrono;
import java.util.Locale;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DurationField;
import org.joda.time.DurationFieldType;
import org.joda.time.field.BaseDateTimeField;
import org.joda.time.field.FieldUtils;
import org.joda.time.field.UnsupportedDurationField;
/**
* Provides time calculations for the era component of time.
*
* @author Stephen Colebourne
* @author Brian S O'Neill
* @since 1.0
*/
final class GJEraDateTimeField extends BaseDateTimeField {
/** Serialization version */
@SuppressWarnings("unused")
private static final long serialVersionUID = 4240986525305515528L;
private final BasicChronology iChronology;
/**
* Restricted constructor
*/
GJEraDateTimeField(BasicChronology chronology) {
super(DateTimeFieldType.era());
iChronology = chronology;
}
@Override
public boolean isLenient() {
return false;
}
/**
* Get the Era component of the specified time instant.
*
* @param instant
* the time instant in millis to query.
*/
@Override
public int get(long instant) {
if (iChronology.getYear(instant) <= 0) {
return DateTimeConstants.BCE;
} else {
return DateTimeConstants.CE;
}
}
@Override
public String getAsText(int fieldValue, Locale locale) {
return GJLocaleSymbols.forLocale(locale).eraValueToText(fieldValue);
}
/**
* Set the Era component of the specified time instant.
*
* @param instant
* the time instant in millis to update.
* @param era
* the era to update the time to.
* @return the updated time instant.
* @throws IllegalArgumentException
* if era is invalid.
*/
@Override
public long set(long instant, int era) {
FieldUtils.verifyValueBounds(this, era, DateTimeConstants.BCE, DateTimeConstants.CE);
int oldEra = get(instant);
if (oldEra != era) {
int year = iChronology.getYear(instant);
return iChronology.setYear(instant, -year);
} else {
return instant;
}
}
@Override
public long set(long instant, String text, Locale locale) {
return set(instant, GJLocaleSymbols.forLocale(locale).eraTextToValue(text));
}
@Override
public long roundFloor(long instant) {
if (get(instant) == DateTimeConstants.CE) {
return iChronology.setYear(0, 1);
} else {
return Long.MIN_VALUE;
}
}
@Override
public long roundCeiling(long instant) {
if (get(instant) == DateTimeConstants.BCE) {
return iChronology.setYear(0, 1);
} else {
return Long.MAX_VALUE;
}
}
@Override
public long roundHalfFloor(long instant) {
// In reality, the era is infinite, so there is no halfway point.
return roundFloor(instant);
}
@Override
public long roundHalfCeiling(long instant) {
// In reality, the era is infinite, so there is no halfway point.
return roundFloor(instant);
}
@Override
public long roundHalfEven(long instant) {
// In reality, the era is infinite, so there is no halfway point.
return roundFloor(instant);
}
@Override
public DurationField getDurationField() {
return UnsupportedDurationField.getInstance(DurationFieldType.eras());
}
@Override
public DurationField getRangeDurationField() {
return null;
}
@Override
public int getMinimumValue() {
return DateTimeConstants.BCE;
}
@Override
public int getMaximumValue() {
return DateTimeConstants.CE;
}
@Override
public int getMaximumTextLength(Locale locale) {
return GJLocaleSymbols.forLocale(locale).getEraMaxTextLength();
}
/**
* Serialization singleton
*/
private Object readResolve() {
return iChronology.era();
}
}
| 24.520231 | 87 | 0.719943 |
9310391ef052f8e092df12015f7f9c6b28dc9300 | 15,222 | import java.io.File;
import java.util.*;
/*
* Inverted Index for information retrieval
*
* Created by Tony Vazgar on 8/22/18.
* Copyright © 2018 Tony Vazgar. All rights reserved.
* Contact: [email protected]
*/
public class BooleanRetrieval{
/*
* Metodo para indexar los archivos.
*/
public static Map<String, LinkedList<Integer>> index(String[] files){
Scanner scanner;
File file;
Set<String> diccionario = new HashSet<String>(); //Here goes every word but its repited
List diccionariOrdenado; //To clone the dictionary but with no repited words
ArrayList<String[]> palabrasArchivos = new ArrayList<String[]>(); //Here goes every word of each document to storage them and have not to read the files many times
Map<String, LinkedList<Integer>> invertedIndex = new HashMap<String, LinkedList<Integer>>(); //The "dictionary" for the inverted index with its respective posting list
///////////////////////
System.out.println("Leyendo el archivo........");
//For every document in the array of documents we storage thw words to make it faster and not have to read every moment
for(int i = 0; i < files.length; i++){
try{
file = new File("./" + files[i] + ".txt");
scanner = new Scanner(file);
ArrayList<String> lecturas = new ArrayList<String>();
while (scanner.hasNext()){
String word = scanner.next().toLowerCase() ;
diccionario.add(word); //Se agregan al diccionario global
lecturas.add(word); //Se a palabras de cada archivo
}
int numberOfWords = lecturas.size(); //Para saber el numero de palabras para el texto en el que vamos
String[] palabras = new String[numberOfWords]; //Se hace arreglo para cada uno exacto
for (int j = 0; j < numberOfWords; j++) {
palabras[j] = lecturas.get(j); //Se agregan
}
Arrays.sort(palabras); //Se guardan en orden alfabetico
palabrasArchivos.add(palabras); //se agrega el conjuto de palabras al repositorio global
}catch (Exception e){
System.err.println("No existe ese documento :(");
}
}
System.out.println("Lectura finalizada.");
diccionariOrdenado = new ArrayList(diccionario); //To delete duplicates and only have one word
Collections.sort(diccionariOrdenado);
ArrayList<Map<String,Integer>> mapDeMaps = new ArrayList<>();
/*
*For each word in a document and for each word in the dictionary
* we create the linkedList to represent the posting lists
*/
//
for(int archivo = 0; archivo < palabrasArchivos.size(); archivo++){
LinkedList<Integer> post = new LinkedList<Integer>();
String[] conjuntoPalabras = palabrasArchivos.get(archivo);
String palabra = "";
Map<String, Integer> dictionary = new HashMap<String, Integer>();
for(int p = 0; p < conjuntoPalabras.length;p++){
palabra = conjuntoPalabras[p];
if(diccionario.contains(palabra)){
dictionary.put(palabra, archivo+1);
}
}
mapDeMaps.add(dictionary);
}
for(Object w: diccionariOrdenado){ //Cada palabra en el diccionariOrdenado
String word = (String) w;
LinkedList<Integer> post = new LinkedList<Integer>();
for(int i = 0; i < mapDeMaps.size(); i++){ //Cada diccionario (indica palabra = indice)
Map<String, Integer> cadaDictionary = mapDeMaps.get(i);
String[] palabras = cadaDictionary.keySet().toArray(new String[cadaDictionary.size()]);
Integer[] numDocs = cadaDictionary.values().toArray(new Integer[cadaDictionary.size()]);
for(int j = 0; j < palabras.length; j++){
if(word.equals(palabras[j])){
post.add(numDocs[i]);
}
}
}
invertedIndex.put(word, post);
}
return invertedIndex;
}
/*
* Metodos para buscar, intersectar y booleanos
*/
public static LinkedList<Integer> buscarPalabra(String palabra, Map<String, LinkedList<Integer>> invertedIndex) {
LinkedList<Integer> posts = new LinkedList<>();
Iterator word = invertedIndex.keySet().iterator();
while (word.hasNext()){
String p = (String)word.next();
if(p.equals(palabra)){
posts = invertedIndex.get(p);
}
}
return posts;
}
public static LinkedList<Integer> intersect(LinkedList<Integer> p1, LinkedList<Integer> p2){
/*
* IMPLEMENTATION OF THE NEXT ALGORITHM:
*
* INTERSECT(p1, p2)
* answer←⟨⟩
* while p1 ̸= NIL and p2 ̸= NIL
* do if docID(p1) = docID(p2)
* then ADD(answer, docID(p1))
* p1 ← next(p1)
* p2 ← next(p2)
* else if docID(p1) < docID(p2)
* then p1 ← next(p1)
* else p2 ← next(p2)
* return answer
*/
LinkedList<Integer> answer = new LinkedList<>();
LinkedList<Integer> pos1 = (LinkedList<Integer>) p1.clone();
LinkedList<Integer> pos2 = (LinkedList<Integer>) p2.clone();
while (!pos1.isEmpty() && !pos2.isEmpty()){
if(pos1.getFirst() == pos2.getFirst()){
answer.add(pos1.getFirst());
pos1.removeFirst();
pos2.removeFirst();
}else{
if (pos1.getFirst() < pos2.getFirst()){
pos1.removeFirst();
}else{
pos2.removeFirst();
}
}
}
print("Las palabras buscadas están en el archivo: " + answer.toString());
return answer;
}
public static List<Integer> not(LinkedList<Integer> p1, LinkedList<Integer> p2){
LinkedList<Integer> answer = (LinkedList<Integer>) p1.clone();
LinkedList<Integer> remove = (LinkedList<Integer>) p2.clone();
for (Integer i: remove) {
if(answer.contains(i)){
answer.remove(i);
}
}
return answer;
}
public static LinkedList<Integer> or(LinkedList<Integer> p1, LinkedList<Integer> p2){
LinkedList<Integer> answer = (LinkedList<Integer>) p1.clone();
LinkedList<Integer> remove = (LinkedList<Integer>) p2.clone();
for (Integer element: remove) {
if(!answer.contains(element))
answer.add(element);
}
Collections.sort(answer);
return answer;
}
/*
* Metodo para hacer la interfaz de usuario en consola
*/
public static void menu(Map<String, LinkedList<Integer>> invertedIndex){
boolean i = true;
/*
* word1 AND word2 AND NOT word3
* word1 AND word2 OR word3
* word1 OR word2 AND NOT word3
*/
try {
while (i) {
Scanner scanner = new Scanner(System.in);
print("________________________________________________");
print("Type the number of one of the options below:\n");
print("0) Print the inverted index.");
print("1) word1 AND word2 AND NOT word3");
print("2) word1 AND word2 OR word3");
print("3) word1 OR word2 AND NOT word3");
print("4) word1 AND word2");
print("5) word1 OR word2");
int option = scanner.nextInt();
switch (option) {
case 0:
imprimirIndex(invertedIndex);
print("");
break;
case 1:
print("word1 AND word2 AND NOT word3");
print(" word1: ");
String word1 = new Scanner(System.in).nextLine();
print(" word2: ");
String word2 = new Scanner(System.in).nextLine();
print(" word3: ");
String word3 = new Scanner(System.in).nextLine();
LinkedList<Integer> r1 = intersect(buscarPalabra(word1, invertedIndex), buscarPalabra(word2, invertedIndex));
print(word1 + " --> " + buscarPalabra(word1,invertedIndex).toString());
print(word2 + " --> " + buscarPalabra(word2,invertedIndex).toString());
print(word3 + " --> " + buscarPalabra(word3,invertedIndex).toString());
print("\nRESULT FOR THE QUERY:\n" + word1 + " AND " + word2 + " AND NOT " + word3 + " --> " + not(r1, buscarPalabra(word3, invertedIndex)).toString());
break;
case 2:
print("word1 AND word2 OR word3");
print(" word1: ");
String word21 = new Scanner(System.in).nextLine();
print(" word2: ");
String word22 = new Scanner(System.in).nextLine();
print(" word3: ");
String word23 = new Scanner(System.in).nextLine();
print(word21 + " --> " + buscarPalabra(word21,invertedIndex).toString());
print(word22 + " --> " + buscarPalabra(word22,invertedIndex).toString());
print(word23 + " --> " + buscarPalabra(word23,invertedIndex).toString());
LinkedList<Integer> and = intersect(buscarPalabra(word21, invertedIndex), buscarPalabra(word22, invertedIndex));
print("\nRESULT FOR THE QUERY:\n" + word21 + " AND " + word22 + " OR " + word23 + " --> " + or(and, buscarPalabra(word23, invertedIndex)).toString());
break;
case 3:
print("word1 OR word2 AND NOT word3");
print(" word1: ");
String word31 = new Scanner(System.in).nextLine();
print(" word2: ");
String word32 = new Scanner(System.in).nextLine();
print(" word3: ");
String word33 = new Scanner(System.in).nextLine();
LinkedList<Integer> or = or(buscarPalabra(word31,invertedIndex),buscarPalabra(word32,invertedIndex));
print(word31 + " --> " + buscarPalabra(word31,invertedIndex).toString());
print(word32 + " --> " + buscarPalabra(word32,invertedIndex).toString());
print(word33 + " --> " + buscarPalabra(word33,invertedIndex).toString());
print("\nRESULT FOR THE QUERY:\n" + word31 + " OR " + word32 + " AND NOT " + word33 + " --> " + not(or, buscarPalabra(word33, invertedIndex)).toString());
break;
case 4:
print("word1 AND word2");
print(" word1: ");
String word41 = new Scanner(System.in).nextLine();
print(" word2: ");
String word42 = new Scanner(System.in).nextLine();
print(word41 + " --> " + buscarPalabra(word41,invertedIndex).toString());
print(word42 + " --> " + buscarPalabra(word42,invertedIndex).toString());
print("\nRESULT FOR THE QUERY:\n" + word41 + " AND " + word42 + " --> " + intersect(buscarPalabra(word41, invertedIndex), buscarPalabra(word42, invertedIndex)).toString());
break;
case 5:
print("word1 OR word2");
print(" word1: ");
String word51 = new Scanner(System.in).nextLine();
print(" word2: ");
String word52 = new Scanner(System.in).nextLine();
print(word51 + " --> " + buscarPalabra(word51,invertedIndex).toString());
print(word52 + " --> " + buscarPalabra(word52,invertedIndex).toString());
print("\nRESULT FOR THE QUERY:\n" + word51 + " OR " + word52 + " --> " + or(buscarPalabra(word51, invertedIndex), buscarPalabra(word52, invertedIndex)).toString());
break;
default:
print("Only numbers bewteen 1 and 4");
}
}
}catch (InputMismatchException e){
System.err.println("Only numbers with the option acepted");
}
}
/*
* Main y metodos para impresion
*/
public static void main(String[] args) {
Map<String, LinkedList<Integer>> invertedIndex;
////////////
/*
*To chance the documents for the desired ones only chance the names of the files[] array
*
*/
String files[] = {"1", "2", "3"};
//String files[] = {"texto1", "texto2", "texto3"};
invertedIndex = index(files);
menu(invertedIndex);
}
private static void imprimirIndex(Map<String, LinkedList<Integer>> invertedIndex){
print("********************************************");
print("The inverted index for the documents are:\n");
print("DICTIONARY POSTINGS" );
for (String word: invertedIndex.keySet()) {
print(String.format("%-15s", word) + " --> " + invertedIndex.get(word).toString());
}
print("********************************************");
}
private static void print(String string){
System.out.println(string);
}
}
| 48.32381 | 202 | 0.477992 |
76efd89d515a3d1fc6d08159bd5b5f7c8335b26b | 2,605 | /*
* Copyright (C) 2012 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.example.android.fragments;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate 这个 fragment 的布局
return inflater.inflate(R.layout.article_view, container, false);
}
@Override
public void onStart() {
super.onStart();
// 在创建过程中,检查是否有参数传入 fragment,并据此设置 fragment 的内容
// onStart 是完成这种工作的好地方,因为在这时布局文件已经被应用到 fragment 上,
// 所以此时可以安全地调用下面的方法来设置文章的内容
Bundle args = getArguments();
if (args != null) {
// 依据传入参数设置文章内容
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// 依据在 onCreateView 期间获取的已保存实例状态设置文章内容
updateArticleView(mCurrentPosition);
}
}
/**
* 该方法更新显示文章的TextView
* 方法既对外提供又内部使用
*/
public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// 当需要重新创建 fragment 时,应该先保存当前显示的文章
outState.putInt(ARG_POSITION, mCurrentPosition);
}
} | 33.397436 | 79 | 0.685605 |
317a623a077569e4a3d389b009c38a7ec0105f76 | 1,140 | /*
* Copyright 2016 Davide Maestroni
*
* 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.github.dm.jrt.function;
/**
* Interface representing a function that accepts one argument and produces a result.
* <p>
* Created by davide-maestroni on 09/21/2015.
*
* @param <IN> the input data type.
* @param <OUT> the output data type.
*/
public interface Function<IN, OUT> {
/**
* Applies this function to the given argument.
*
* @param in the input argument.
* @return the function result.
* @throws java.lang.Exception if an unexpected error occurs.
*/
OUT apply(IN in) throws Exception;
}
| 30 | 85 | 0.712281 |
4937d5ff37237709c0b847d9e4447828e2395959 | 1,166 | package com.egoveris.ccomplejos.base.model;
import java.util.Date;
public class MedioTransporteDTO extends AbstractCComplejoDTO{
private static final long serialVersionUID = 18800162863976226L;
protected Date fechaEstimadaLlegada;
protected String ruta;
protected String patente;
protected ParticipantesDTO transportista;
protected String tipoMedioTranspote;
public Date getFechaEstimadaLlegada() {
return fechaEstimadaLlegada;
}
public void setFechaEstimadaLlegada(Date fechaEstimadaLlegada) {
this.fechaEstimadaLlegada = fechaEstimadaLlegada;
}
public String getRuta() {
return ruta;
}
public void setRuta(String ruta) {
this.ruta = ruta;
}
public String getPatente() {
return patente;
}
public void setPatente(String patente) {
this.patente = patente;
}
public ParticipantesDTO getTransportista() {
return transportista;
}
public void setTransportista(ParticipantesDTO transportista) {
this.transportista = transportista;
}
public String getTipoMedioTranspote() {
return tipoMedioTranspote;
}
public void setTipoMedioTranspote(String tipoMedioTranspote) {
this.tipoMedioTranspote = tipoMedioTranspote;
}
}
| 24.291667 | 65 | 0.789022 |
4fbd3a06f81061b0c80397fc50919f8463f84e0c | 6,527 | /* Copyright (c) 2009 Peter Troshin
*
* JAva Bioinformatics Analysis Web Services (JABAWS) @version: 1.0
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* Apache License version 2 as published by the Apache Software Foundation
*
* This library 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 Apache
* License for more details.
*
* A copy of the license is in apache_license.txt. It is also available here:
* @see: http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Any republication or derived work distributed in source code form
* must include this copyright and license notice.
*/
package compbio.engine.conf;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import compbio.util.SysPrefs;
public class RunnerConfigMarshaller<T> {
private static final Logger log = Logger
.getLogger(RunnerConfigMarshaller.class);
private final JAXBContext ctx;
@SuppressWarnings("all")
public RunnerConfigMarshaller(Class<?> rootClass) throws JAXBException {
this(rootClass, null);
}
public RunnerConfigMarshaller(Class<?> rootClass, Class<?>... classes)
throws JAXBException {
if (classes != null) {
List<Class<?>> classesList = new ArrayList<Class<?>>(
Arrays.asList(classes));
classesList.add(rootClass);
ctx = JAXBContext.newInstance(classesList.toArray(new Class<?>[0]));
} else {
ctx = JAXBContext.newInstance(rootClass);
}
}
public void write(Object xmlRootElement, OutputStream out)
throws JAXBException, IOException {
Marshaller marsh = ctx.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// disable validation
marsh.setSchema(null);
marsh.marshal(xmlRootElement, out);
}
public void writeAndValidate(Object xmlRootElement, String schemafile,
OutputStream out) throws JAXBException, IOException, SAXException {
Marshaller marsh = ctx.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,
schemafile);
marsh.setSchema(getSchema(schemafile));
marsh.marshal(xmlRootElement, out);
}
void generateSchema(String directoryForSchema, String schemaName)
throws JAXBException, IOException {
Marshaller marsh = ctx.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ctx.generateSchema(new MySchemaOutputResolver(directoryForSchema,
schemaName));
}
public static Schema getSchema(String schemafile) throws SAXException {
// define the type of schema - we use W3C:
String schemaLang = "http://www.w3.org/2001/XMLSchema";
// get validation driver:
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
// create schema by reading it from an XSD file:
Schema schema = factory.newSchema(new StreamSource(schemafile));
return schema;
}
/**
*
* @return validator instance
* @throws SAXException
*/
public static Validator getValidator(String schemafile) throws SAXException {
Schema schema = getSchema(schemafile);
Validator validator = schema.newValidator();
return validator;
}
public static Validator getValidator(Schema schema) throws SAXException {
Validator validator = schema.newValidator();
return validator;
}
public static boolean validate(Validator validator, String document)
throws IOException, SAXException {
try {
// at last perform validation:
validator.validate(new StreamSource(document));
} catch (SAXException ex) {
ex.printStackTrace();
log.warn("SAXException validating xml" + ex.getMessage());
// we are here if the document is not valid:
// ... process validation error...
return false;
}
return true;
}
public <V> V readAndValidate(InputStream document, Class<V> resultElemType)
throws JAXBException, IOException, SAXException {
String schemaFile = Long.toHexString(System.nanoTime());
generateSchema(SysPrefs.getSystemTmpDir(), schemaFile);
Unmarshaller um = ctx.createUnmarshaller();
um.setSchema(getSchema(SysPrefs.getSystemTmpDir() + File.separator
+ schemaFile));
JAXBElement<V> rconfig = um.unmarshal(new StreamSource(document),
resultElemType);
return rconfig.getValue();
}
static class MySchemaOutputResolver extends SchemaOutputResolver {
final String dir;
final String sname;
public MySchemaOutputResolver(String directory, String suggestedFileName) {
this.dir = directory;
this.sname = suggestedFileName;
}
@Override
public Result createOutput(String namespaceUri, String suggestedFileName)
throws IOException {
return new StreamResult(new File(dir, this.sname));
}
}
@SuppressWarnings("all")
public <V> V read(InputStream instream, Class<V> resultElemType)
throws JAXBException {
return read(instream, resultElemType, null);
}
public <V> V read(InputStream instream, Class<V> resultElemType,
Class<?>... classes) throws JAXBException {
if (instream == null) {
throw new NullPointerException("Input stream must be provided!");
}
JAXBContext ctx = null;
if (classes != null) {
List<Class<?>> classesList = new ArrayList<Class<?>>(
Arrays.asList(classes));
classesList.add(resultElemType);
ctx = JAXBContext.newInstance(classesList.toArray(new Class<?>[0]));
} else {
ctx = JAXBContext.newInstance(resultElemType);
}
Unmarshaller um = ctx.createUnmarshaller();
JAXBElement<V> rconfig = um.unmarshal(new StreamSource(instream),
resultElemType);
return rconfig.getValue();
}
}
| 32.472637 | 102 | 0.729432 |
6db1a6cd0d2b043629d63fdc6e87ee040d766467 | 4,760 | package com.scriptbasic.executors.rightvalues;
import com.scriptbasic.api.ScriptBasicException;
import com.scriptbasic.interfaces.BasicRuntimeException;
import com.scriptbasic.spi.BasicArray;
import com.scriptbasic.spi.BasicValue;
import com.scriptbasic.spi.Interpreter;
import com.scriptbasic.spi.RightValue;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
public class BasicArrayValue implements RightValue, BasicArray, BasicValue<Object[]> {
private static final Integer INCREMENT_GAP = 100;
private Object[] array = new Object[INCREMENT_GAP];
private int maxIndex = -1;
// TODO implement a function in the interpreter that can limit the
// allocation of arrays
// perhaps only the size of the individual arrays
private Interpreter interpreter;
private Integer indexLimit;
/**
* This constructor can be used by extension classes to instantiate a new
* BasicArrayValue when the extension function does not have access to the
* interpreter.
* <p>
* Note that in later versions this constructor will be deprecated as soon
* as the interface of the extensions will make it possible to pass the
* interpreter along to the extension methods.
*/
public BasicArrayValue() {
this.interpreter = null;
}
/**
* Create a new BasicArrayValue and remember the interpreter.
* <p>
* The interpreter can determine the maximum size allowed for arrays and
* therefore may suggest for a BasicArrayValue not to extend its size, but
* rather throw exception. This is to prevent allocating extraordinary large
* arrays in an interpreter by mistake.
*
* @param interpreter parameter
*/
public BasicArrayValue(final Interpreter interpreter) {
setInterpreter(interpreter);
}
@Override
public void setArray(final Object[] array) throws ScriptBasicException {
if (array == null) {
throw new ScriptBasicException("BasicArrayValue embedded array cannot be null");
}
this.array = objectArrayOf(array);
maxIndex = array.length - 1;
}
private Object[] objectArrayOf(final Object[] array) {
final Object[] objectArray;
if (array.getClass() == Object[].class) {
objectArray = array;
} else {
objectArray = Arrays.copyOf(array, array.length, Object[].class);
}
return objectArray;
}
/**
* Set the interpreter that this array belongs to.
* <p>
* Note that this method is used only from the code where the interpreter
* calls an extension method that returns a BasicArrayValue. In that case
* the parameter less constructor of this class is called by the extension
* method and thus the BasicArrayValue does not know the interpreter and can
* not request suggestion from the interpreter to perform resizing or throw
* exception.
* <p>
* When the parameterless version of the constructor becomes deprecated this
* setter will also become deprecated.
*
* @param interpreter parameter
*/
public final void setInterpreter(final Interpreter interpreter) {
this.interpreter = interpreter;
final Optional<String> maxConfig = interpreter.getConfiguration().getConfigValue("arrayMaxIndex");
maxConfig.ifPresent(s -> indexLimit = Integer.valueOf(s));
}
private void assertArraySize(final Integer index) throws ScriptBasicException {
if (index < 0) {
throw new BasicRuntimeException("Array index can not be negative");
}
if (array.length <= index) {
if (indexLimit != null && index > indexLimit) {
throw new BasicRuntimeException("Array index is too large, the configured limit is " + indexLimit);
}
array = Arrays.copyOf(array, index + INCREMENT_GAP);
}
}
@Override
public long getLength() {
return (long) maxIndex + 1;
}
@Override
public void set(final Integer index, final Object object) throws ScriptBasicException {
assertArraySize(index);
array[index] = object;
if (maxIndex < index) {
maxIndex = index;
}
}
@Override
public Object get(final Integer index) throws ScriptBasicException {
assertArraySize(index);
return array[index];
}
@Override
public String toString() {
return "[" +
Arrays.stream(array).limit(maxIndex + 1).map(Object::toString).collect(Collectors.joining(","))
+ "]";
}
@Override
public Object[] getValue() {
return Arrays.copyOf(array, maxIndex + 1);
}
}
| 35 | 115 | 0.665546 |
6c1a0e9e4459663a9d19af2b456d365ca73445ad | 3,135 | /*
* Copyright 2014-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli.net;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.intent.Constraint;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.IntentService;
import org.onosproject.net.intent.MultiPointToSinglePointIntent;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Installs connectivity intent between multiple ingress devices and a single egress device.
*/
@Command(scope = "onos", name = "add-multi-to-single-intent",
description = "Installs connectivity intent between multiple ingress devices and a single egress device")
public class AddMultiPointToSinglePointIntentCommand extends ConnectivityIntentCommand {
@Argument(index = 0, name = "ingressDevices egressDevice",
description = "ingressDevice/Port..ingressDevice/Port egressDevice/Port",
required = true, multiValued = true)
String[] deviceStrings = null;
@Override
protected void execute() {
IntentService service = get(IntentService.class);
if (deviceStrings.length < 2) {
return;
}
String egressDeviceString = deviceStrings[deviceStrings.length - 1];
ConnectPoint egress = ConnectPoint.deviceConnectPoint(egressDeviceString);
Set<ConnectPoint> ingressPoints = new HashSet<>();
for (int index = 0; index < deviceStrings.length - 1; index++) {
String ingressDeviceString = deviceStrings[index];
ConnectPoint ingress = ConnectPoint.deviceConnectPoint(ingressDeviceString);
ingressPoints.add(ingress);
}
TrafficSelector selector = buildTrafficSelector();
TrafficTreatment treatment = buildTrafficTreatment();
List<Constraint> constraints = buildConstraints();
Intent intent = MultiPointToSinglePointIntent.builder()
.appId(appId())
.key(key())
.selector(selector)
.treatment(treatment)
.ingressPoints(ingressPoints)
.egressPoint(egress)
.constraints(constraints)
.priority(priority())
.build();
service.submit(intent);
print("Multipoint to single point intent submitted:\n%s", intent.toString());
}
}
| 39.1875 | 114 | 0.697927 |
0227254b75f207f35a6e36855a36a89819f2e568 | 10,476 | package tccrouter.gbl.vrp.common.entity;
import tccrouter.diamante.core.graph.Graph;
import tccrouter.diamante.core.graph.Node;
import tccrouter.diamante.core.graph.property.ComponentProperties;
import tccrouter.diamante.extension.graph.property.ID;
import tccrouter.gbl.common.entity.TSProblemModel;
import tccrouter.gbl.common.util.TravelTimeUtil;
import tccrouter.gbl.vrp.tw.entity.TimeWindow;
import tccrouter.ring.gui.UIFacade;
/**
* model for an instance of a VRP definition.
*
* @author Guilherme
*
*/
public class VRProblemModel {
/*
* General CVRP Constants
*/
private static final int NUM_CONSTRAINTS = 1;
private static final int DEMAND_INDEX = 0;
public static final int DEFAULT_CLIENT_DEMAND = 10;
public static final int DEFAULT_VEHICLE_CAPACITY = 100;
public static final boolean LSD_DEFAULT_MEASURE_EXECUTION = true;
public static final boolean SA_DEFAULT_MEASURE_EXECUTION = true;
public static final boolean PFIH_DEFAULT_MEASURE_EXECUTION = true;
/*
* VRP-TW: Time constants Measured in hours
*/
private static final int NUM_TW_CONSTRAINTS = 1;
public static final double DFAULT_TRAVEL_TIME = 1;
public static final double DEFAULT_TRAVEL_STEP = 50;
public static final double DEFAULT_CLIENT_TW_BEGIN = 8;
public static final double DEFAULT_CLIENT_TW_END = 22;
public static final double DEFAULT_CLIENT_TW_SERVICE = 0.5;
private static final int TW_SERVICE_INDEX = 0;
public static final int DEFAULT_MEAN_VELOCITY = 50;
public static final double DEFAULT_TWVEHICLE_INITIAL = 6;
public static final double DEFAULT_TWVEHICLE_MAX_TRAVEL = 48;
public static final double MAX_TRAVEL_TIME = 48;
public static final double INITIAL_WORK_TIME = 6;
/*
* LSD
*/
public static final int DEFAULT_LAMBDA = 2;
public static final boolean DEFAULT_GLOBAL_BEST = true;
public static final boolean DEFAULT_ACCEPT_BAD_MOVES = false;
public static final int DEFAULT_LSD_ITERATIONS = 1;
/*
* SA
*/
public static final int DEFAULT_SA_LAMBDA = 2;
public static final double DEFAULT_FINAL_TEMP = 0.001;
public static final double DEFAULT_TIME_CONST = 0.5;
public static final int DEFAULT_NUM_RESETS = 8;
static VRProblemModel instance;
/*
* GENERAL
*/
int constraints[][];
private int vehicleCapacity;
/**
* if the execution should be analysed in terms of execution speed, mem. usage...
*/
boolean saExecutionMeasure;
boolean lsdExecutionMeasure;
boolean pfihExecutionMeasure;
/*
* For the local Search Method:
*/
private int lambda;
private int numIterationsLSD;
private boolean badMovesLSD;
private boolean globalBestLSD;
/*
* Time Window VRP specific
*/
double twConstraints[][];
private double maxTravelTime;
private double initialWorkTime;
private TimeWindow timeWindow[];
/*
* For the SA Method:
*/
private int saLambda;
double finalTemperature;
double timeConstant;
int numResets;
/**
*
* @return
*/
public static VRProblemModel getInstance() {
if (instance == null)
instance = new VRProblemModel();
return instance;
}
/**
*
*
*/
protected VRProblemModel() {
resetConstraints();
resetDataStructures();
}
public void setNewVRP(Graph g) {
if (g != null) {
if (constraints.length == 0) {
resetDataStructures();
}
}
}
public int getClientDemand(int clientIndex) {
return constraints[clientIndex][DEMAND_INDEX];
}
public void setClientDemand(int clientIndex, int demand) {
constraints[clientIndex][DEMAND_INDEX] = demand;
}
public double getTWClientServiceTime(int clientIndex) {
return twConstraints[clientIndex][TW_SERVICE_INDEX];
}
public int getVehicleCapacity() {
return vehicleCapacity;
}
public void setVehicleCapacity(int vehicleCapacity) {
this.vehicleCapacity = vehicleCapacity;
}
public int getNumIterationsLSD() {
return numIterationsLSD;
}
public void setNumIterationsLSD(int numIterationsLSD) {
this.numIterationsLSD = numIterationsLSD;
}
public boolean isBadMovesLSD() {
return badMovesLSD;
}
public void setBadMovesLSD(boolean badMovesLSD) {
this.badMovesLSD = badMovesLSD;
}
public boolean isGlobalBestLSD() {
return globalBestLSD;
}
public void setGlobalBestLSD(boolean globalBestLSD) {
this.globalBestLSD = globalBestLSD;
}
public TimeWindow getClientTimeWindow(int i) {
return timeWindow[i];
}
public void setClientTimeWindowBegin(int i, double value) {
timeWindow[i].begin = value;
}
public void setClientTimeWindowEnd(int i, double value) {
timeWindow[i].end = value;
}
public double getClientTimeWindowService(int i) {
return twConstraints[i][TW_SERVICE_INDEX];
}
public void setClientTimeWindowService(int i, double value) {
twConstraints[i][TW_SERVICE_INDEX] = value;
}
public int getCapacity() {
return vehicleCapacity;
}
public void setCapacity(int capacity) {
this.vehicleCapacity = capacity;
}
public double getInitialWorkTime() {
return initialWorkTime;
}
public void setInitialWorkTime(double initialWorkTime) {
this.initialWorkTime = initialWorkTime;
}
public double getMaxTravelTime() {
return maxTravelTime;
}
public void setMaxTravelTime(double maxTravelTime) {
this.maxTravelTime = maxTravelTime;
}
public double getMeanVelocity() {
return TravelTimeUtil.getMeanVelocity();
}
public void setMeanVelocity(double meanVelocity) {
TravelTimeUtil.setMeanVelocity(meanVelocity);
}
public int getNumResets() {
return numResets;
}
public void setNumResets(int numResets) {
this.numResets = numResets;
}
public double getFinalTemperature() {
return finalTemperature;
}
public void setFinalTemperature(double finalTemperature) {
this.finalTemperature = finalTemperature;
}
public double getTimeConstant() {
return timeConstant;
}
public void setTimeConstant(double timeConstant) {
this.timeConstant = timeConstant;
}
public int getLambda() {
return lambda;
}
public void setLambda(int lambda) {
this.lambda = lambda;
}
public int getSaLambda() {
return saLambda;
}
public void setSaLambda(int saLambda) {
this.saLambda = saLambda;
}
public boolean isSAExecutionMeasure() {
return saExecutionMeasure;
}
public void setSAExecutionMeasure(boolean executionMeasure) {
this.lsdExecutionMeasure = executionMeasure;
}
public boolean isLsdExecutionMeasure() {
return lsdExecutionMeasure;
}
public void setLsdExecutionMeasure(boolean lsdExecutionMeasure) {
this.lsdExecutionMeasure = lsdExecutionMeasure;
}
public boolean isPfihExecutionMeasure() {
return pfihExecutionMeasure;
}
public void setPfihExecutionMeasure(boolean pfihExecutionMeasure) {
this.pfihExecutionMeasure = pfihExecutionMeasure;
}
/**
* For use in UI settings.
*
* @return
*/
public Object[][] buildProblemDataModel() {
int clientNodes[] = TSProblemModel.getInstance().getAllProblemNodes();
Object[][] result = new Object[clientNodes.length][clientNodes.length];
for (int i = 0; i < clientNodes.length; i++) {
int index = clientNodes[i];
result[i][0] = new Integer(index); // ID
result[i][1] = new Integer(getClientDemand(index)); // Demand
TimeWindow tw = getClientTimeWindow(index); // TW
result[i][2] = new Double(tw.begin);
result[i][3] = new Double(tw.end);
result[i][4] = new Double(getTWClientServiceTime(index));
i++;
}
return result;
}
/**
* For use in UI settings.
*
* @return
*/
public Object[][] buildNewGraphDataModel() {
resetDataStructures();
Graph g = UIFacade.getInstance().getGraph();
Object[][] result = new Object[g.getN()][5];
for (int i = 0; i < g.getN(); i++) {
Node node = g.getNode(i);
ComponentProperties cp = node.getProperties();
// ID
result[i][0] = new Integer(
((ID)cp.getPropertyByName("ID")).getValue());
result[i][1] = new Integer(DEFAULT_CLIENT_DEMAND); // Demand
result[i][2] = new Double(DEFAULT_CLIENT_TW_BEGIN);
result[i][3] = new Double(DEFAULT_CLIENT_TW_END);
result[i][4] = new Double(DEFAULT_CLIENT_TW_SERVICE);
}
return result;
}
public Object[][] getGraphDataModel() {
Graph g = UIFacade.getInstance().getGraph();
Object[][] result = new Object[g.getN()][5];
for (int i = 0; i < g.getN(); i++) {
Node node = g.getNode(i);
ComponentProperties cp = node.getProperties();
// ID
int id = ((ID)cp.getPropertyByName("ID")).getValue();
result[i][0] = new Integer(id);
result[i][1] = new Integer(getClientDemand(id)); // Demand
TimeWindow tw = getClientTimeWindow(id);
result[i][2] = new Double(tw.begin);
result[i][3] = new Double(tw.end);
result[i][4] = new Double(getClientTimeWindowService(id));
}
return result;
}
public void resetConstraints() {
setCapacity(DEFAULT_VEHICLE_CAPACITY);
setMeanVelocity(DEFAULT_MEAN_VELOCITY);
setMaxTravelTime(DEFAULT_TWVEHICLE_MAX_TRAVEL);
setInitialWorkTime(DEFAULT_TWVEHICLE_INITIAL);
setNumIterationsLSD(DEFAULT_LSD_ITERATIONS);
setNumResets(DEFAULT_NUM_RESETS);
setFinalTemperature(DEFAULT_FINAL_TEMP);
setTimeConstant(DEFAULT_TIME_CONST);
setPfihExecutionMeasure(PFIH_DEFAULT_MEASURE_EXECUTION);
setLsdExecutionMeasure(LSD_DEFAULT_MEASURE_EXECUTION);
setSAExecutionMeasure(SA_DEFAULT_MEASURE_EXECUTION);
setLambda(DEFAULT_LAMBDA);
setSaLambda(DEFAULT_SA_LAMBDA);
}
public void resetDataStructures() {
int numNodes = UIFacade.getInstance().getGraph().getN();
constraints = new int[numNodes][NUM_CONSTRAINTS];
twConstraints = new double[numNodes][NUM_TW_CONSTRAINTS];
for (int i = 0; i < numNodes; i++) {
// setting the client DEMAND values
constraints[i][DEMAND_INDEX] = DEFAULT_CLIENT_DEMAND;
// setting the TW CONSTRAINTS:
twConstraints[i][TW_SERVICE_INDEX] = DEFAULT_CLIENT_TW_SERVICE;
}
timeWindow = new TimeWindow[numNodes];
for (int i = 0; i < timeWindow.length; i++) {
timeWindow[i] = new TimeWindow();
}
}
} | 25.304348 | 83 | 0.692726 |
4d7ed98b19925cd5306664bd9981c0fcc968d793 | 6,470 | package com.github.dockerjava.cmd;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.PullImageCmd;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Info;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.RemoteApiVersion;
import com.github.dockerjava.core.command.PullImageResultCallback;
import com.github.dockerjava.utils.RegistryUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import static com.github.dockerjava.utils.TestUtils.getVersion;
import static com.github.dockerjava.utils.TestUtils.isNotSwarm;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
public class PullImageCmdIT extends CmdIT {
private static final Logger LOG = LoggerFactory.getLogger(PullImageCmdIT.class);
@Rule
public ExpectedException exception = ExpectedException.none();
private static final PullImageCmd.Exec NOP_EXEC = new PullImageCmd.Exec() {
public Void exec(PullImageCmd command, ResultCallback<PullResponseItem> resultCallback) {
return null;
};
};
@Test
public void testPullImage() throws Exception {
Info info = dockerRule.getClient().infoCmd().exec();
LOG.info("Client info: {}", info.toString());
int imgCount = info.getImages();
LOG.info("imgCount1: {}", imgCount);
// This should be an image that is not used by other repositories
// already
// pulled down, preferably small in size. If tag is not used pull will
// download all images in that repository but tmpImgs will only
// deleted 'latest' image but not images with other tags
String testImage = "hackmann/empty";
LOG.info("Removing image: {}", testImage);
try {
dockerRule.getClient().removeImageCmd(testImage).withForce(true).exec();
} catch (NotFoundException e) {
// just ignore if not exist
}
info = dockerRule.getClient().infoCmd().exec();
LOG.info("Client info: {}", info.toString());
imgCount = info.getImages();
LOG.info("imgCount2: {}", imgCount);
LOG.info("Pulling image: {}", testImage);
dockerRule.getClient().pullImageCmd(testImage)
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
info = dockerRule.getClient().infoCmd().exec();
LOG.info("Client info after pull, {}", info.toString());
assertThat(imgCount, lessThanOrEqualTo(info.getImages()));
InspectImageResponse inspectImageResponse = dockerRule.getClient().inspectImageCmd(testImage).exec();
LOG.info("Image Inspect: {}", inspectImageResponse.toString());
assertThat(inspectImageResponse, notNullValue());
}
@Test
public void testPullNonExistingImage() throws Exception {
if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
.isGreaterOrEqual(RemoteApiVersion.VERSION_1_26)) {
exception.expect(NotFoundException.class);
} else {
exception.expect(DockerClientException.class);
}
// stream needs to be fully read in order to close the underlying connection
dockerRule.getClient().pullImageCmd("xvxcv/foo")
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
}
@Test
public void testPullImageWithValidAuth() throws Exception {
AuthConfig authConfig = RegistryUtils.runPrivateRegistry(dockerRule.getClient());
String imgName = RegistryUtils.createPrivateImage(dockerRule, "pull-image-with-valid-auth");
// stream needs to be fully read in order to close the underlying connection
dockerRule.getClient().pullImageCmd(imgName)
.withAuthConfig(authConfig)
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
}
@Test
public void testPullImageWithNoAuth() throws Exception {
RegistryUtils.runPrivateRegistry(dockerRule.getClient());
String imgName = RegistryUtils.createPrivateImage(dockerRule, "pull-image-with-no-auth");
if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
.isGreaterOrEqual(RemoteApiVersion.VERSION_1_30)) {
exception.expect(InternalServerErrorException.class);
} else {
exception.expect(DockerClientException.class);
}
// stream needs to be fully read in order to close the underlying connection
dockerRule.getClient().pullImageCmd(imgName)
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
}
@Test
public void testPullImageWithInvalidAuth() throws Exception {
AuthConfig validAuthConfig = RegistryUtils.runPrivateRegistry(dockerRule.getClient());
AuthConfig authConfig = new AuthConfig()
.withUsername("testuser")
.withPassword("testwrongpassword")
.withEmail("[email protected]")
.withRegistryAddress(validAuthConfig.getRegistryAddress());
String imgName = RegistryUtils.createPrivateImage(dockerRule, "pull-image-with-invalid-auth");
if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
.isGreaterOrEqual(RemoteApiVersion.VERSION_1_30)) {
exception.expect(InternalServerErrorException.class);
} else {
exception.expect(DockerClientException.class);
}
// stream needs to be fully read in order to close the underlying connection
dockerRule.getClient().pullImageCmd(imgName)
.withAuthConfig(authConfig)
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
}
}
| 40.691824 | 109 | 0.689335 |
9d44106c2c9751396ff9cdb737ddf6aa72d5f559 | 7,296 | /*
* L&N STEMpunks c 2017
*
* WOPR-JR.
*
* Full repo: github.com/ln-stempunks/WOPR-JR
*
* Full licensing here: programming.lnstempunks.org/licensing
*
* GPLv3
*/
package team3966.robot.commands;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import team3966.robot.Robot;
import team3966.robot.hardware.MotorEncoder;
import team3966.robot.subsystems.Subsystems;
import team3966.robot.values.PS4Buttons;
import team3966.robot.hardware.Controller;
import team3966.robot.pidcontrollers.MotorPIDOutput;
import team3966.robot.pidcontrollers.MotorPIDSource;
public class TankDrive extends BaseCommand {
private Controller cont;
private Subsystems systems;
private PIDController LPID, RPID;
private boolean isRestricted = true;
private boolean enabled = false, inwards = true;
private boolean psButtonLast = false;
// PID constants
public static final double kLP = .18;
public static final double kLI = 0.0;
public static final double kLD = 0.0;
public static final double kLF = 0.0;
public static final double kRP = .18;
public static final double kRI = 0.0;
public static final double kRD = 0.0;
public static final double kRF = 0.0;
public TankDrive() {
super(Robot.subsystems.drive);
systems = Robot.subsystems;
cont = systems.OI.controller;
MotorPIDSource Lsource = new MotorPIDSource(systems.drive.Lenc);
MotorPIDSource Rsource = new MotorPIDSource(systems.drive.Renc);
Lsource.useSpeed();
Rsource.useSpeed();
Lsource.setScale(-1);
Rsource.setScale(-1);
MotorPIDOutput Lout = new MotorPIDOutput(systems.drive.L0, systems.drive.L1);
MotorPIDOutput Rout = new MotorPIDOutput(systems.drive.R0, systems.drive.R1);
Lout.setScale(-1);
Rout.setScale(-1);
LPID = new PIDController(kLP, kLI, kLD, kLF, Lsource, Lout);
LPID.setInputRange(-MotorEncoder.MAX_HIGH_SPEED, MotorEncoder.MAX_HIGH_SPEED);
LPID.setOutputRange(-1, 1);
RPID = new PIDController(kRP, kRI, kRD, kRF, Rsource, Rout);
RPID.setInputRange(-MotorEncoder.MAX_HIGH_SPEED, MotorEncoder.MAX_HIGH_SPEED);
RPID.setOutputRange(-1, 1);
LPID.setAbsoluteTolerance(MotorEncoder.MAX_TOLERANCE_SPEED);
RPID.setAbsoluteTolerance(MotorEncoder.MAX_TOLERANCE_SPEED);
}
boolean LgearBox = false, lGate = false, lMouth = false;
protected void initialize() {
/*LPID.enable();
RPID.enable();
LPID.setSetpoint(0.0);
RPID.setSetpoint(0.0);
*/
}
protected void execute() {
if (cont.getPOV(0) != 0) {
boolean psButtonCur = (cont.getPOV(0) == 90);
// Could also be isRestricted = (psButtonCur != psButtonLast) ^ isRestricted
if (psButtonCur != psButtonLast) {
isRestricted = !isRestricted;
}
psButtonLast = psButtonCur;
}
//Only gear and climber
if (isRestricted) {
LPID.disable();
RPID.disable();
restrictedOperation();
} else {
LPID.enable();
RPID.enable();
normalOperation();
}
SmartDashboard.putBoolean("Restricted", isRestricted);
}
void restrictedOperation() {
double Lpow = -cont.getAxis(PS4Buttons.STICK_LEFT_Y_AXIS);
double Rpow = -cont.getAxis(PS4Buttons.STICK_RIGHT_Y_AXIS);
systems.drive.tank_power(Lpow, Rpow);
double Spow = cont.getAxis(PS4Buttons.R_TRIGGER_AXIS) + 1;
if (Spow != 1) {
systems.drive.shooter.set(Spow);
systems.drive.stir.set(-Spow * .55);
} else {
systems.drive.shooter.set(0);
systems.drive.stir.set(0);
}
double Cpow = cont.getAxis(PS4Buttons.L_TRIGGER_AXIS) + 1;
if (Cpow != 1) {
systems.drive.climb.set(Cpow);
} else {
systems.drive.climb.set(0);
}
/*
if (cont.getButton(PS4Buttons.TRIANGLE)) {
systems.drive.climb.set(.2);
} else if (cont.getButton(PS4Buttons.CIRCLE)) {
systems.drive.climb.set(1);
} else {
systems.drive.climb.set(0);
}*/
if (cont.getButton(PS4Buttons.R1)) {
systems.drive.gearBox.enable();
} else if (cont.getButton(PS4Buttons.L1)) {
systems.drive.gearBox.disable();
}
if (cont.getPOV(0) == 270) {
enabled = false;
}
if (cont.getPOV(0) == 0) {
enabled = true;
inwards = false;
}
if (cont.getPOV(0) == 180) {
enabled = true;
inwards = true;
}
if (enabled) {
double inpow = .75 + .25 * (Math.abs(Lpow) + Math.abs(Rpow)) / 2.0;
if (inwards) {
systems.drive.intake.set(inpow);
} else {
systems.drive.intake.set(-inpow);
}
} else {
systems.drive.intake.set(0);
}
systems.drive.mouth.set(cont.getButton(PS4Buttons.SQUARE));
systems.drive.gate.set(!cont.getButton(PS4Buttons.X));
}
void normalOperation() {
if (true) {
SmartDashboard.putData("L PID", LPID);
SmartDashboard.putData("R PID", RPID);
}
double Lpow = cont.getAxis(PS4Buttons.STICK_LEFT_Y_AXIS);
double Rpow = cont.getAxis(PS4Buttons.STICK_RIGHT_Y_AXIS);
if (systems.drive.gearBox.get()) {
LPID.setSetpoint(-Lpow * MotorEncoder.MAX_HIGH_SPEED);
RPID.setSetpoint(-Rpow * MotorEncoder.MAX_HIGH_SPEED);
} else {
LPID.setSetpoint(-Lpow * MotorEncoder.MAX_LOW_SPEED);
RPID.setSetpoint(-Rpow * MotorEncoder.MAX_LOW_SPEED);
}
double cpower = cont.getAxis(PS4Buttons.L_TRIGGER_AXIS) + 1;
systems.drive.climb.set(cpower * cpower);
systems.drive.shooter.set(cont.getAxis(PS4Buttons.R_TRIGGER_AXIS) + 1);
systems.drive.stir.set(-.5);
if (cont.getPOV(0) == 270) {
enabled = false;
}
if (cont.getPOV(0) == 0) {
enabled = true;
inwards = false;
}
if (cont.getPOV(0) == 180) {
enabled = true;
inwards = true;
}
if (enabled) {
double inpow = .6 + .4 * (Math.abs(Lpow) + Math.abs(Rpow)) / 2.0;
if (inwards) {
systems.drive.intake.set(inpow);
} else {
systems.drive.intake.set(-inpow);
}
} else {
systems.drive.intake.set(0);
}
if (cont.getButton(PS4Buttons.R1)) {
systems.drive.gearBox.enable();
} else if (cont.getButton(PS4Buttons.L1)) {
systems.drive.gearBox.disable();
}
systems.drive.mouth.set(cont.getButton(PS4Buttons.SQUARE));
systems.drive.gate.set(!cont.getButton(PS4Buttons.X));
}
protected void interrupted() {
end();
}
protected void end() {
systems.drive.stop();
LPID.disable();
RPID.disable();
}
}
| 30.78481 | 88 | 0.581277 |
01f5f16ec957089d1b346c95b4cc13577c667ccf | 1,154 | package com.ai.domain.bo;
import java.util.Date;
public class SipLog {
private Long id;
private Date createat;
private String accepter;
private String handler;
private String num;
private Long result;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreateat() {
return createat;
}
public void setCreateat(Date createat) {
this.createat = createat;
}
public String getAccepter() {
return accepter;
}
public void setAccepter(String accepter) {
this.accepter = accepter == null ? null : accepter.trim();
}
public String getHandler() {
return handler;
}
public void setHandler(String handler) {
this.handler = handler == null ? null : handler.trim();
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num == null ? null : num.trim();
}
public Long getResult() {
return result;
}
public void setResult(Long result) {
this.result = result;
}
} | 17.753846 | 66 | 0.581456 |
aa03a32f76e5f0cf6f4eb070572bc604436f3704 | 1,093 | package site.daipeng.boot.demo.utli;
/**
* @author daipeng
* @date 2019/9/24 14:28
* @description
*/
public class NumberUtil {
public static Long parseStringOrIntegerOrLongToLong(Object value) {
Long result = -1L;
if (value == null) {
return result;
}
if (value instanceof Long) {
return (Long) value;
}
if (value instanceof Integer) {
return ((Integer) value).longValue();
}
if (value instanceof String) {
return Long.valueOf((String) value);
}
return result;
}
public static Integer parseStringOrIntegerOrLongToInteger(Object value) {
Integer result = -1;
if (value == null) {
return result;
}
if (value instanceof Long) {
return ((Long) value).intValue();
}
if (value instanceof Integer) {
return ((Integer) value);
}
if (value instanceof String) {
return Integer.valueOf((String) value);
}
return result;
}
}
| 24.288889 | 77 | 0.537969 |
05d1b69d13b7303663373372ef835fc92d0ea635 | 3,191 | package com.chenantao.playtogether.chat.mvc.view.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.chenantao.autolayout.utils.AutoUtils;
import com.chenantao.playtogether.R;
import com.chenantao.playtogether.chat.AVImClientManager;
import com.chenantao.playtogether.chat.mvc.view.viewholder.ChatCommonViewHolder;
import com.chenantao.playtogether.chat.mvc.view.viewholder.ChatFromHolderChat;
import com.chenantao.playtogether.chat.mvc.view.viewholder.ChatToHolderChat;
import com.chenantao.playtogether.chat.utils.ChatConstant;
import java.util.List;
/**
* Created by Chenantao_gg on 2016/1/29.
*/
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
public static final int TYPE_FROM_MESSAGE = 0;
public static final int TYPE_TO_MESSAGE = 1;
private Context mContext;
private List<AVIMMessage> mDatas;
private AVIMConversation mConversation;
public ChatAdapter(Context context, List<AVIMMessage> datas, AVIMConversation conversation)
{
this.mContext = context;
this.mDatas = datas;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
switch (viewType)
{
case TYPE_FROM_MESSAGE:
return new ChatFromHolderChat(LayoutInflater.from(mContext).inflate(R.layout
.item_chat_from_message, parent, false), mContext, mConversation);
case TYPE_TO_MESSAGE:
return new ChatToHolderChat(LayoutInflater.from(mContext).inflate(R.layout
.item_chat_to_message, parent, false), mContext, mConversation);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
AutoUtils.autoSize(holder.itemView);
AVIMMessage message = mDatas.get(position);
((ChatCommonViewHolder) holder).bindData(message, shouldShowTime(position));
}
@Override
public int getItemViewType(int position)
{
AVIMMessage message = mDatas.get(position);
if (message.getFrom() != null && message.getFrom().equals(AVImClientManager.getInstance()
.getClientId()))//是发送出去的消息
{
return TYPE_TO_MESSAGE;
} else
{
return TYPE_FROM_MESSAGE;
}
}
@Override
public int getItemCount()
{
return mDatas.size();
}
public void addData(AVIMMessage message)
{
mDatas.add(message);
notifyItemInserted(mDatas.size());
}
public void addDatasToBottom(List<AVIMMessage> messages)
{
int startIndex = mDatas.size();
mDatas.addAll(messages);
notifyItemRangeInserted(startIndex, messages.size());
}
public void addDatasToHeader(List<AVIMMessage> messages)
{
mDatas.addAll(0, messages);
notifyItemRangeInserted(0, messages.size());
}
private boolean shouldShowTime(int position)
{
if (position == 0) return true;
long lastTime = mDatas.get(position - 1).getTimestamp();
long now = mDatas.get(position).getTimestamp();
return now - lastTime > ChatConstant.CHAT_SHOW_TIME_INTERVAL;
}
}
| 28.747748 | 93 | 0.745534 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.