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 |
|---|---|---|---|---|---|
af245a9f36f7d8bedb4d1cd938004cdaf378d111 | 4,957 | /*
* Copyright 2004-2013 the Seasar Foundation and the Others.
*
* 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 oscana.s2n.testCommon;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import mockit.Expectations;
import mockit.Mocked;
import nablarch.fw.ExecutionContext;
import nablarch.fw.Handler;
import nablarch.fw.dicontainer.annotation.AnnotationContainerBuilder;
import nablarch.fw.dicontainer.annotation.AnnotationScopeDecider;
import nablarch.fw.dicontainer.nablarch.AnnotationAutoContainerProvider;
import nablarch.fw.dicontainer.nablarch.Containers;
import nablarch.fw.dicontainer.nablarch.NablarchWebContextHandler;
import nablarch.fw.dicontainer.web.RequestScoped;
import nablarch.fw.dicontainer.web.SessionScoped;
import nablarch.fw.dicontainer.web.scope.RequestScope;
import nablarch.fw.dicontainer.web.scope.SessionScope;
import nablarch.fw.web.HttpRequest;
import nablarch.fw.web.servlet.ServletExecutionContext;
/**
* テストを実行するための共通クラス
*
*
*/
public abstract class S2NBaseTest {
private RequestScope requestScope;
private SessionScope sessionScope;
private AnnotationContainerBuilder builder;
private NablarchWebContextHandler supplier;
protected List<Class<?>> registClassList;
protected ExecutionContext executionContext;
// ExecutionContext作成用
@Mocked
protected HttpServletResponse httpServletResponse;
@Mocked
protected HttpServletRequest httpServletRequest;
@Mocked
protected ServletContext servletContext;
@Before
public void setUp() throws Exception {
new Expectations() {{
httpServletRequest.getContextPath();
result = "";
minTimes = 0;
httpServletRequest.getRequestURI();
result = "/dummy";
minTimes = 0;
}};
//ExecutionContextを設定
setExecutionContext();
supplier = new NablarchWebContextHandler();
requestScope = new RequestScope(supplier);
sessionScope = new SessionScope(supplier);
final AnnotationScopeDecider decider = AnnotationScopeDecider.builder()
.addScope(RequestScoped.class, requestScope).addScope(SessionScoped.class, sessionScope)
.build();
builder = AnnotationContainerBuilder.builder().scopeDecider(decider).build();
AnnotationAutoContainerProvider provider = new AnnotationAutoContainerProvider();
//クラスをregist
setClassToRegist();
if(registClassList == null) {
fail("コンテナに事前ロードする必要クラスを設定してください。");
}
//コンポーネント(クラス)をコンテナにロードする
for(Class<?> clazz : registClassList) {
builder.register(clazz);
}
provider.setAnnotationContainerBuilder(builder);
provider.initialize();
}
@After
public void tearDown() throws Exception {
Containers.clear();
}
/**
* テストコードを実施する
* - handlerListで定義しているハンドラを順番的に実施
* - 実行できるのはインタフェースHandler<TData, TResult>を実装したもののみ
*/
protected Object handle(List<Handler<HttpRequest, Object>> handlerList) {
if(executionContext == null ) {
fail("ExecutionContextを設定してください。");
}
if(handlerList.size()==0) {
fail("処理するハンドラを設定してください。");
}
for(Handler<HttpRequest, Object> handler : handlerList) {
executionContext.addHandler(handler);
}
return supplier.handle(null, executionContext);
}
/**
* 事前にコンテナにregist必要のクラスを定義
*/
protected abstract void setClassToRegist();
/**
* ExecutionContextを定義
* ハンドラを実施する際ExecutionContextが必要
*/
protected void setExecutionContext() {
executionContext = new ServletExecutionContext(httpServletRequest, httpServletResponse,
servletContext);
new Expectations(executionContext) {{
Map<String, Object> requestScope = new HashMap<String, Object>();
executionContext.getRequestScopeMap();
result = requestScope;
minTimes = 0;
}};
}
} | 32.611842 | 105 | 0.677829 |
dbd1506aca8f2937f69666aacaca908f567b3fb8 | 1,161 | package org.jeecg.modules.business.vo;
import lombok.Data;
/**
* Created by zj on 2021/4/1.
*/
@Data
public class DeviceBroadEntity {
//动态信息部分
public String broadRecId;//动态信息ID
public String broadTime;//动态信息时间
public String broadDec;//动态信息描述
//设备故障报警信息部分
public String errorRecId;//故障记录ID
public String errorTime;//故障记录时间
public String errorDec;//故障描述
public String machineCode;//故障机器编码
public String flowName;//流程名称
public String errorCode;//错误代码
public String errorPri;//故障优先级
public String dataStatusCode;//数据状态编码
public String dataStatus;//数据状态
public String errorConfirmStatusCode;//确认状态编码
public String errorConfirmStatus;//确认状态
public String errorConfirmOp;//确认人
public String errorConfirmTime;//确认时间
public String createOp;//创建人
public String opCode;//处理人ID
public String confirmOpCode;//确认人ID
public String bak;
public String deviceIp;
public String flowId;
public String machinName;//故障机器名称
private String deviceBroadPri;
private String beginTime;
private String endTime;
private String resCode;
private String resMsg;
}
| 25.23913 | 49 | 0.720069 |
ee5533b7ca54913e0f176247c9e4de22075d1d1a | 84 | package br.com.concretesolutions.audience.core;
public class ActorStorageTest {
}
| 14 | 47 | 0.809524 |
3f3dfc8f8b07d9b853aea9047ac7011a54657d8f | 378 | package mao.com.mao_wanandroid_client.compoent.event;
/**
* @author maoqitian
* @Description: 主题切换事件
* @date 2019/8/2 0002 11:26
*/
public class ThemeModeEvent {
int mode;
public ThemeModeEvent(int mode){
this.mode = mode;
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
}
| 15.75 | 53 | 0.608466 |
2fab542ac37539dd54ef2001c61d9ac9c63932af | 2,814 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.aggregate;
import java.io.*;
import org.eclipse.persistence.tools.schemaframework.TableDefinition;
public class Address implements Serializable {
public Number id;
public String address;
public static Address example1() {
Address example = new Address();
example.setAddress("1-1129 Meadowlands, Ottawa");
;
return example;
}
public static Address example2() {
Address example = new Address();
example.setAddress("2-1120 Meadowlands, Ottawa");
;
return example;
}
public static Address example3() {
Address example = new Address();
example.setAddress("3-1130 Meadowlands, Ottawa");
;
return example;
}
public static Address example4() {
Address example = new Address();
example.setAddress("4-1130 Meadowlands, Ottawa");
;
return example;
}
public static Address example5() {
Address example = new Address();
example.setAddress("5-1130 Meadowlands, Ottawa");
;
return example;
}
public static Address example6() {
Address example = new Address();
example.setAddress("6-1130 Meadowlands, Ottawa");
;
return example;
}
public static Address example7() {
Address example = new Address();
example.setAddress("Address Changed");
;
return example;
}
public void setAddress(String anAddress) {
address = anAddress;
}
/**
* Return a platform independant definition of the database table.
*/
public static TableDefinition tableDefinition() {
TableDefinition definition = new TableDefinition();
definition.setName("AGG_ADD");
definition.addIdentityField("ID", java.math.BigDecimal.class, 15);
definition.addField("ADDRESS", String.class, 30);
return definition;
}
}
| 29.3125 | 88 | 0.590618 |
e2a0218732b55842a8931ab68f2097297c532a66 | 3,080 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.tools.jlink.internal;
import java.nio.file.Path;
import java.util.Objects;
import jdk.tools.jlink.plugin.ResourcePoolEntry;
public final class ResourcePoolEntryFactory {
private ResourcePoolEntryFactory() {}
public static ResourcePoolEntry create(String path,
ResourcePoolEntry.Type type, byte[] content) {
return new ByteArrayResourcePoolEntry(moduleFrom(path), path, type, content);
}
public static ResourcePoolEntry create(String path,
ResourcePoolEntry.Type type, Path file) {
return new PathResourcePoolEntry(moduleFrom(path), path, type, file);
}
public static ResourcePoolEntry create(ResourcePoolEntry original, byte[] content) {
return new ByteArrayResourcePoolEntry(original.moduleName(),
original.path(), original.type(), content);
}
public static ResourcePoolEntry create(ResourcePoolEntry original, Path file) {
return new PathResourcePoolEntry(original.moduleName(),
original.path(), original.type(), file);
}
public static ResourcePoolEntry createSymbolicLink(String path,
ResourcePoolEntry.Type type,
ResourcePoolEntry target) {
return new SymLinkResourcePoolEntry(moduleFrom(path), path, type, target);
}
private static String moduleFrom(String path) {
Objects.requireNonNull(path);
if (path.isEmpty() || path.charAt(0) != '/') {
throw new IllegalArgumentException(path + " must start with /");
}
String noRoot = path.substring(1);
int idx = noRoot.indexOf('/');
if (idx == -1) {
throw new IllegalArgumentException("/ missing after module: " + path);
}
return noRoot.substring(0, idx);
}
}
| 42.191781 | 88 | 0.683117 |
c47333f96208eec1f5ec63d0a972759c096c5164 | 2,564 | package com.jtorregrosa.meteoasv.aemet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jtorregrosa.meteoasv.aemet.utils.ApiKeyInterceptor;
import com.jtorregrosa.meteoasv.aemet.utils.DefaultHeadersInterceptor;
import com.jtorregrosa.meteoasv.aemet.utils.TrustAllX509TrustManager;
import okhttp3.OkHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
class PartialClientFactory {
/**
* The API key.
*/
private final String apiKey;
/**
* Instantiates a new Aemet client.
*
* @param apiKey the api key
*/
public PartialClientFactory(String apiKey) {
this.apiKey = apiKey;
}
/**
* Create a Master partial client.
*
* @return a Master partial client
*/
public MasterClient createMasterClient(String baseUrl) {
return new MasterClient(baseUrl, this.createHttpClient(), new ObjectMapper());
}
/**
* Create a SpecificPrediction partial client.
*
* @return a SpecificPrediction partial client
*/
public SpecificPredictionClient createSpecificPredictionClient(String baseUrl) {
return new SpecificPredictionClient(baseUrl, this.createHttpClient(), new ObjectMapper());
}
/**
* Create a new HttpClient populated with defaults.
*
* @return a new configured HttpClient.
*/
OkHttpClient createHttpClient() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.addInterceptor(new ApiKeyInterceptor(this.apiKey));
httpClientBuilder.addInterceptor(new DefaultHeadersInterceptor());
httpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
httpClientBuilder.writeTimeout(10, TimeUnit.SECONDS);
httpClientBuilder.readTimeout(30, TimeUnit.SECONDS);
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLSv1.2");
TrustManager[] trustAllCerts = new TrustManager[]{new TrustAllX509TrustManager()};
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return httpClientBuilder.build();
}
}
| 33.736842 | 115 | 0.709828 |
e8f26857e1ad35c6d00c8314230976ad0c199a60 | 247 | import java.io.PrintWriter;
public class Using_PrintWriter_Class
{
public static void main(String args[])
{
PrintWriter out = new PrintWriter(System.out,true);
out.println("Used the PrintWriter Class.");
}
}
| 22.454545 | 60 | 0.651822 |
12309860e505432a0fbfb6fff48a4f5a90966c9e | 510 | package cn.xhh.leetcode._059;
import org.junit.Assert;
import org.junit.Test;
/**
* SpiralMatrixIITest
*
* @author <a href="mailto:bigtiger02@gmail.com">xhh</a>
* @date 2020/11/21
*/
public class SpiralMatrixIITest {
private Solution solution = new Solution();
@Test
public void case1(){
int[][] results = solution.generateMatrix(3);
Assert.assertArrayEquals(new int[][]{
{1,2,3},
{8,9,4},
{7,6,5}
},results);
}
}
| 20.4 | 56 | 0.570588 |
93400a9434f455e3847990aa392229bc69c88835 | 641 | package g1801_1900.s1805_number_of_different_integers_in_a_string;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void numDifferentIntegers() {
assertThat(new Solution().numDifferentIntegers("a123bc34d8ef34"), equalTo(3));
}
@Test
void numDifferentIntegers2() {
assertThat(new Solution().numDifferentIntegers("leet1234code234"), equalTo(2));
}
@Test
void numDifferentIntegers3() {
assertThat(new Solution().numDifferentIntegers("a1b01c001"), equalTo(1));
}
}
| 26.708333 | 87 | 0.728549 |
271c558be9b621c2248fb6377265a93e54f5c0f1 | 3,095 | /*
* CloudReactor API
* CloudReactor API Documentation
*
* The version of the OpenAPI document: 0.2.0
* Contact: jeff@cloudreactor.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.cloudreactor.tasksymphony.api;
import io.cloudreactor.tasksymphony.invoker.ApiException;
import io.cloudreactor.tasksymphony.model.PaginatedTaskExecutionList;
import io.cloudreactor.tasksymphony.model.PatchedTaskExecution;
import io.cloudreactor.tasksymphony.model.TaskExecution;
import java.util.UUID;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for TaskExecutionsApi
*/
@Ignore
public class TaskExecutionsApiTest {
private final TaskExecutionsApi api = new TaskExecutionsApi();
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsCreateTest() throws ApiException {
TaskExecution taskExecution = null;
TaskExecution response = api.taskExecutionsCreate(taskExecution);
// TODO: test validations
}
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsDestroyTest() throws ApiException {
UUID uuid = null;
api.taskExecutionsDestroy(uuid);
// TODO: test validations
}
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsListTest() throws ApiException {
Integer limit = null;
Integer offset = null;
String ordering = null;
String search = null;
Integer taskCreatedByGroupId = null;
String taskUuid = null;
PaginatedTaskExecutionList response = api.taskExecutionsList(limit, offset, ordering, search, taskCreatedByGroupId, taskUuid);
// TODO: test validations
}
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsPartialUpdateTest() throws ApiException {
UUID uuid = null;
PatchedTaskExecution patchedTaskExecution = null;
TaskExecution response = api.taskExecutionsPartialUpdate(uuid, patchedTaskExecution);
// TODO: test validations
}
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsRetrieveTest() throws ApiException {
UUID uuid = null;
TaskExecution response = api.taskExecutionsRetrieve(uuid);
// TODO: test validations
}
/**
* @throws ApiException
* if the Api call fails
*/
@Test
public void taskExecutionsUpdateTest() throws ApiException {
UUID uuid = null;
TaskExecution taskExecution = null;
TaskExecution response = api.taskExecutionsUpdate(uuid, taskExecution);
// TODO: test validations
}
}
| 27.633929 | 134 | 0.667851 |
3ec5af975d36ccd61325da57d61a3fd1c02e00de | 460 | //Code to demonstrate difference between concatenation [seen in case of strings] and addition
public class Concat
{
public static void main(String[] args)
{
int a=11;
int b=7;
//Summing both the numbers a and b [treating them as integers]
System.out.println("Summation: "+(a+b));
//Concatenating both the numbers a and b [treating them as strings]
System.out.println("Concatenation: "+a+b);
}
} | 32.857143 | 93 | 0.63913 |
787836d2e995e85476329646b110ebe056e1148e | 234 | package work.koreyoshi.constant;
/**
* @author zhoujx
*/
public class VideosUrl {
public final static String BASE_PATH = "https://www.nfmovies.com";
public final static String SEARCH = "/search.php?page=1&searchword=";
}
| 19.5 | 73 | 0.700855 |
8db037bc9bdc71bcfd738f9bac5eb5083f53ddb9 | 499 | /*
* Copyright (c) 2019 CascadeBot. All rights reserved.
* Licensed under the MIT license.
*/
package org.cascadebot.cascadebot.utils.language;
import org.cascadebot.cascadebot.data.language.Language;
import org.cascadebot.cascadebot.data.language.Locale;
public class LanguageUtils {
// TODO: Doc
public static <T extends Enum> String getEnumI18n(Locale locale, String base, T enumToGet) {
return Language.i18n(locale, base + "." + enumToGet.name().toLowerCase());
}
}
| 26.263158 | 96 | 0.725451 |
22d243adfb594b36303a2986ea91487b4eb27d3d | 99 | /*
*/
package gov.osti.doi;
/**
*
* @author ensornl
*/
public class DataCiteMetadata {
}
| 8.25 | 31 | 0.575758 |
6a87d3deca3238a1de059dca64e996f8af16cb88 | 2,312 | /*
* Copyright (c) 2018. Manuel D. Rossetti, rossetti@uark.edu
*
* 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 examples.montecarlo.dicepackage;
public class CrapsGame {
protected boolean winner = false;
protected int numberoftosses = 0;
protected RollIfc dice = new TwoSixSidedDice();
public boolean play() {
winner = false;
int point = dice.roll();
numberoftosses = 1;
if (point == 7 || point == 11) {
winner = true; // automatic winner
} else if (point == 2 || point == 3 || point == 12) {
winner = false; // automatic loser
} else { // now must roll to get point
boolean continueRolling = true;
while (continueRolling == true) {
// increment number of tosses
numberoftosses++;
// make next roll
int nextRoll = dice.roll();
// if next roll == point then winner = 1, contineRolling = false
// else if next roll = 7 then winner = 0, continueRolling = false
if (nextRoll == point) {
winner = true;
continueRolling = false;
} else if (nextRoll == 7) {
winner = false;
continueRolling = false;
}
}
}
return winner;
}
public boolean getResult() {
return winner;
}
public int getNumberOfTosses() {
return numberoftosses;
}
public static void main(String[] args) {
CrapsGame g = new CrapsGame();
g.play();
System.out.println("result = " + g.getResult());
System.out.println("# tosses = " + g.getNumberOfTosses());
}
}
| 32.111111 | 81 | 0.563581 |
be90d3730b22da499217c4af3ee573ffba8b350a | 2,919 | package net.toshirohex.lycurgus.materials;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.item.ArmorMaterial;
import net.minecraft.recipe.Ingredient;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.toshirohex.lycurgus.registry.ModItems;
import java.util.function.Supplier;
public enum ModArmorMaterials implements ArmorMaterial {
STEEL("steel", 33, new int[]{3, 6, 8, 3}, 10, SoundEvents.ITEM_ARMOR_EQUIP_CHAIN, 2.0F, 0.0F, () -> Ingredient.ofItems(ModItems.Ingots[0])),
HANDS_COLD("hands_cold", 25, new int[]{2, 5, 7, 2}, 9, SoundEvents.ITEM_ARMOR_EQUIP_CHAIN, 0.0F, 0.0F, () -> Ingredient.ofItems(ModItems.Ingots[1])),
ENDIUM("endium", 37, new int[]{4, 7, 9, 4}, 15, SoundEvents.ITEM_ARMOR_EQUIP_CHAIN, 3.0F, 0.1F, () -> Ingredient.ofItems(ModItems.Ingots[2])),
KNIGHT("knight", 25, new int[]{12, 20, 32, 12}, 9, SoundEvents.ITEM_ARMOR_EQUIP_CHAIN, 0.0F, 0.0F, () -> null);
private static final int[] BASE_DURABILITY = new int[]{13, 15, 16, 11};
private final String name;
private final int durabilityMultiplier;
private final int[] protectionAmounts;
private final int enchantability;
private final SoundEvent equipSound;
private final float toughness;
private final float knockbackResistance;
private final Supplier<Ingredient> repairIngredientSupplier;
ModArmorMaterials(String name, int durabilityMultiplier, int[] protectionAmounts, int enchantability, SoundEvent equipSound, float toughness, float knockbackResistance, Supplier<Ingredient> repairIngredientSupplier) {
this.name = name;
this.durabilityMultiplier = durabilityMultiplier;
this.protectionAmounts = protectionAmounts;
this.enchantability = enchantability;
this.equipSound = equipSound;
this.toughness = toughness;
this.knockbackResistance = knockbackResistance;
this.repairIngredientSupplier = repairIngredientSupplier;
}
@Override
public int getDurability(EquipmentSlot slot) {
return BASE_DURABILITY[slot.getEntitySlotId()] * durabilityMultiplier;
}
@Override
public int getProtectionAmount(EquipmentSlot slot) {
return protectionAmounts[slot.getEntitySlotId()];
}
@Override
public int getEnchantability() {
return enchantability;
}
@Override
public SoundEvent getEquipSound() {
return equipSound;
}
@Override
public Ingredient getRepairIngredient() {
return repairIngredientSupplier.get();
}
@Override
@Environment(EnvType.CLIENT)
public String getName() {
return name;
}
@Override
public float getToughness() {
return toughness;
}
@Override
public float getKnockbackResistance() {
return knockbackResistance;
}
}
| 35.168675 | 222 | 0.714628 |
f68b080ca69b1daf3e3dd3b40e63282bdb58d2aa | 8,411 | import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.*;
public class JUnit5MigrationTestCases {
Object x = new Object();
Class xClass = Object.class;
Object y = new Object();
Object[] xArray = new Object[] {};
Object[] yArray = new Object[] {};
Boolean xBoolean = false;
Float xFloat = 10f;
Float yFloat = 10f;
float deltaFloat = 10f;
Double xDouble = 10d;
Double yDouble = 10d;
double deltaDouble = 10d;
boolean b = true;
// Assert equals/not equals
void assertEquals_input() {
assertEquals(x, y);
}
void assertEquals_expected() {
assertThat(y).isEqualTo(x);
}
void assertEqualsWithMessage_input() {
assertEquals(x, y, "some msg");
}
void assertEqualsWithMessage_expected() {
assertThat(y).as("some msg").isEqualTo(x);
}
void assertEqualsAllStringsWithMessage_input() {
assertEquals("x", "y", "some msg");
}
void assertEqualsAllStringsWithMessage_expected() {
assertThat("y").as("some msg").isEqualTo("x");
}
void assertNotEquals_input() {
assertNotEquals(x, y);
}
void assertNotEquals_expected() {
assertThat(y).isNotEqualTo(x);
}
void assertNotEqualsWithMessage_input() {
assertNotEquals(x, y, "some msg");
}
void assertNotEqualsWithMessage_expected() {
assertThat(y).as("some msg").isNotEqualTo(x);
}
// Assert equals/not equals with delta
void assertEqualsFloatDelta_input() {
assertEquals(xFloat, yFloat, deltaFloat);
}
void assertEqualsFloatDelta_expected() {
assertThat(yFloat).isCloseTo(xFloat, within(deltaFloat));
}
void assertEqualsFloatDeltaWithMessage_input() {
assertEquals(xFloat, yFloat, deltaFloat, "some msg");
}
void assertEqualsFloatDeltaWithMessage_expected() {
assertThat(yFloat).as("some msg").isCloseTo(xFloat, within(deltaFloat));
}
void assertNotEqualsFloatDelta_input() {
assertNotEquals(xFloat, yFloat, deltaFloat);
}
void assertNotEqualsFloatDelta_expected() {
assertThat(yFloat).isNotCloseTo(xFloat, within(deltaFloat));
}
void assertNotEqualsFloatDeltaWithMessage_input() {
assertNotEquals(xFloat, yFloat, deltaFloat, "some msg");
}
void assertNotEqualsFloatDeltaWithMessage_expected() {
assertThat(yFloat).as("some msg").isNotCloseTo(xFloat, within(deltaFloat));
}
void assertEqualsDoubleDelta_input() {
assertEquals(xDouble, yDouble, deltaDouble);
}
void assertEqualsDoubleDelta_expected() {
assertThat(yDouble).isCloseTo(xDouble, within(deltaDouble));
}
void assertEqualsDoubleDeltaWithMessage_input() {
assertEquals(xDouble, yDouble, deltaDouble, "some msg");
}
void assertEqualsDoubleDeltaWithMessage_expected() {
assertThat(yDouble).as("some msg").isCloseTo(xDouble, within(deltaDouble));
}
void assertNotEqualsDoubleDelta_input() {
assertNotEquals(xDouble, yDouble, deltaDouble);
}
void assertNotEqualsDoubleDelta_expected() {
assertThat(yDouble).isNotCloseTo(xDouble, within(deltaDouble));
}
void assertNotEqualsDoubleDeltaWithMessage_input() {
assertNotEquals(xDouble, yDouble, deltaDouble, "some msg");
}
void assertNotEqualsDoubleDeltaWithMessage_expected() {
assertThat(yDouble).as("some msg").isNotCloseTo(xDouble, within(deltaDouble));
}
// Assert array equals
void assertArrayEquals_input() {
assertArrayEquals(xArray, yArray);
}
void assertArrayEquals_expected() {
assertThat(yArray).isEqualTo(xArray);
}
// Assert true/false
void assertTrue_input() {
assertTrue(xBoolean);
}
void assertTrue_expected() {
assertThat(xBoolean).isTrue();
}
void assertTrueWithMessage_input() {
assertTrue(xBoolean, "some msg");
}
void assertTrueWithMessage_expected() {
assertThat(xBoolean).as("some msg").isTrue();
}
void assertFalse_input() {
assertFalse(xBoolean);
}
void assertFalse_expected() {
assertThat(xBoolean).isFalse();
}
void assertFalseWithMessage_input() {
assertFalse(xBoolean, "some msg");
}
void assertFalseWithMessage_expected() {
assertThat(xBoolean).as("some msg").isFalse();
}
// Assert null/not null
void assertNull_input() {
assertNull(x);
}
void assertNull_expected() {
assertThat(x).isNull();
}
void assertNullWithMessage_input() {
assertNull(x, "some msg");
}
void assertNullWithMessage_expected() {
assertThat(x).as("some msg").isNull();
}
void assertNotNull_input() {
assertNotNull(x);
}
void assertNotNull_expected() {
assertThat(x).isNotNull();
}
void assertNotNullWithMessage_input() {
assertNotNull(x, "some msg");
}
void assertNotNullWithMessage_expected() {
assertThat(x).as("some msg").isNotNull();
}
// Assert same/not same
void assertSame_input() {
assertSame(x, y);
}
void assertSame_expected() {
assertThat(y).isSameAs(x);
}
void assertSameWithMessage_input() {
assertSame(x, y, "some msg");
}
void assertSameWithMessage_expected() {
assertThat(y).as("some msg").isSameAs(x);
}
void assertNotSame_input() {
assertNotSame(x, y);
}
void assertNotSame_expected() {
assertThat(y).isNotSameAs(x);
}
void assertNotSameWithMessage_input() {
assertNotSame(x, y, "some msg");
}
void assertNotSameWithMessage_expected() {
assertThat(y).as("some msg").isNotSameAs(x);
}
// Assert instanceOf
void assertInstanceOfWithClassLiteral_input() {
assertInstanceOf(Object.class, x);
}
void assertInstanceOfWithClassLiteral_expected() {
assertThat(x).isInstanceOf(Object.class);
}
void assertInstanceOfWithClassLiteralWithMessage_input() {
assertInstanceOf(Object.class, x, "some msg");
}
void assertInstanceOfWithClassLiteralWithMessage_expected() {
assertThat(x).as("some msg").isInstanceOf(Object.class);
}
void assertInstanceOfWithClassVariable_input() {
assertInstanceOf(xClass, x);
}
void assertInstanceOfWithClassVariable_expected() {
assertThat(x).isInstanceOf(xClass);
}
void assertInstanceOfWithClassVariableWithMessage_input() {
assertInstanceOf(xClass, x, "some msg");
}
void assertInstanceOfWithClassVariableWithMessage_expected() {
assertThat(x).as("some msg").isInstanceOf(xClass);
}
// Assert throws/does not throw
void assertThrows_input() {
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException();
});
}
void assertThrows_expected() {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
}).isInstanceOf(IllegalArgumentException.class);
}
void assertThrowsWithMessage_input() {
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException();
}, "some msg");
}
void assertThrowsWithMessage_expected() {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
}).as("some msg").isInstanceOf(IllegalArgumentException.class);
}
void assertDoesNotThrow_input() {
assertDoesNotThrow(() -> {
throw new IllegalArgumentException();
});
}
void assertDoesNotThrow_expected() {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
}).isNull();
}
void assertDoesNotThrowWithMessage_input() {
assertDoesNotThrow(() -> {
throw new IllegalArgumentException();
}, "some msg");
}
void assertDoesNotThrowWithMessage_expected() {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
}).as("some msg").isNull();
}
// Fail
void fail_input() {
org.junit.jupiter.api.Assertions.fail();
}
void fail_expected() {
fail("unknown failure");
}
void failWithMessage_input() {
org.junit.jupiter.api.Assertions.fail("a specific failure");
}
void failWithMessage_expected() {
fail("a specific failure");
}
void failWithThrowable_input() {
org.junit.jupiter.api.Assertions.fail(new IllegalArgumentException());
}
void failWithThrowable_expected() {
fail("unknown failure", new IllegalArgumentException());
}
void failWithMessageAndThrowable_input() {
org.junit.jupiter.api.Assertions.fail("a specific failure", new IllegalArgumentException());
}
void failWithMessageAndThrowable_expected() {
fail("a specific failure", new IllegalArgumentException());
}
}
| 23.170799 | 96 | 0.701343 |
a8ebb11f7238e263a59e59b6d413e63089958916 | 92 | package academy.pocu.comp2500.assignment2;
public enum StampColor {
RED, BLUE, GREEN
}
| 15.333333 | 42 | 0.75 |
a71ec79d92ab7589eb3b322f3ad4d09fb58ccc9d | 1,076 | package fr.poulpogaz.mandelbrot.explorer.colorpicker;
import fr.poulpogaz.mandelbrot.explorer.sliders.Slider;
import javax.swing.*;
import java.awt.*;
public class AlphaSlider extends Slider {
public AlphaSlider(int alpha) {
setModel(new DefaultBoundedRangeModel(alpha, 0, 0, 255));
}
@Override
protected void paintHorizontalTrack(Graphics2D g2d, Rectangle bounds) {
if (isInvert()) {
g2d.setPaint(new GradientPaint(0, 0, Color.WHITE, bounds.width, 0, new Color(0, 0, 0, 0)));
} else {
g2d.setPaint(new GradientPaint(bounds.width, 0, Color.WHITE, 0, 0, new Color(0, 0, 0, 0)));
}
g2d.fill(bounds);
}
@Override
protected void paintVerticalTrack(Graphics2D g2d, Rectangle bounds) {
if (isInvert()) {
g2d.setPaint(new GradientPaint(0, 0, Color.WHITE, 0, bounds.height, new Color(0, 0, 0, 0)));
} else {
g2d.setPaint(new GradientPaint(0, bounds.height, Color.WHITE, 0, 0, new Color(0, 0, 0, 0)));
}
g2d.fill(bounds);
}
} | 30.742857 | 104 | 0.625465 |
ccea02b54ec09ac2695453bf693d18f27cc0376b | 2,082 | /**
* Copyright 2011-2014 the original author or authors.
*/
package com.jetdrone.vertx.yoke.middleware.filters;
import org.jetbrains.annotations.NotNull;
import org.vertx.java.core.buffer.Buffer;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.regex.Pattern;
/**
* # AbstractWriterFilter
*/
public abstract class AbstractWriterFilter implements WriterFilter {
final Pattern filter;
final OutputStream stream;
final Buffer buffer = new Buffer();
public AbstractWriterFilter(@NotNull final Pattern filter) throws IOException {
this.filter = filter;
this.stream = createOutputStream();
}
private void write(byte[] b) {
try {
stream.write(b);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public abstract OutputStream createOutputStream() throws IOException;
private void end(byte[] b) {
try {
stream.write(b);
stream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void write(@NotNull final Buffer buffer) {
write(buffer.getBytes());
}
@Override
public void write(@NotNull final String chunk) {
write(chunk.getBytes());
}
@Override
public void write(@NotNull final String chunk, @NotNull final String enc) {
write(chunk.getBytes(Charset.forName(enc)));
}
@Override
public Buffer end(@NotNull final Buffer buffer) {
end(buffer.getBytes());
return this.buffer;
}
@Override
public Buffer end(@NotNull final String chunk) {
end(chunk.getBytes());
return buffer;
}
@Override
public Buffer end(@NotNull final String chunk, @NotNull final String enc) {
end(chunk.getBytes(Charset.forName(enc)));
return buffer;
}
@Override
public boolean canFilter(@NotNull final String contentType) {
return filter.matcher(contentType).find();
}
}
| 24.785714 | 83 | 0.64073 |
2bccfb8c76ca7f9ac52f68d314783fb44131763b | 649 | package com.ms.silverking.cloud.dht.daemon.storage.serverside;
public class LRUInfo {
private long accessTime;
private int size;
public LRUInfo(long accessTime, int size) {
this.accessTime = accessTime;
this.size = size;
}
public void updateAccessTime(long accessTime) {
this.accessTime = accessTime;
}
public void update(long accessTime, int size) {
this.accessTime = accessTime;
this.size = size;
}
public long getAccessTime() {
return accessTime;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return String.format("%d:%d", accessTime, size);
}
}
| 19.088235 | 62 | 0.677966 |
09f15e674309e4025da4176f00b864aac02677fd | 952 | package yuudaari.soulus.common.recipe.ingredient;
import com.google.gson.JsonObject;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraftforge.common.crafting.IIngredientFactory;
import net.minecraftforge.common.crafting.JsonContext;
import yuudaari.soulus.common.ModItems;
import yuudaari.soulus.common.item.CrystalBlood;
public class IngredientCrystalBlood extends Ingredient {
public static IngredientCrystalBlood INSTANCE = new IngredientCrystalBlood();
public IngredientCrystalBlood () {
super(ModItems.CRYSTAL_BLOOD.getFilledStack());
}
@Override
public boolean apply (ItemStack stack) {
return CrystalBlood.isFilled(stack);
}
@Override
public boolean isSimple () {
return false;
}
public static class Factory implements IIngredientFactory {
@Override
public Ingredient parse (JsonContext context, JsonObject json) {
return new IngredientCrystalBlood();
}
}
}
| 25.72973 | 78 | 0.80042 |
074d6a1779cc25b955d49affabbea7991c68abb8 | 130 | package com.design.patterns.creational.factory.simplefactory;
public abstract class Parser {
public abstract void parse();
}
| 21.666667 | 61 | 0.784615 |
11c22d4aca85c7e405b2a73635cd13fe9079cb95 | 851 | package com.sdu.calcite.api;
import com.sdu.calcite.plan.SduRelOptimizerFactory;
import java.util.List;
import java.util.Optional;
import org.apache.calcite.plan.RelOptCostFactory;
import org.apache.calcite.plan.RelTraitDef;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql2rel.SqlToRelConverter;
public interface SduTableConfig {
boolean replacesSqlOperatorTable();
Optional<SqlOperatorTable> getSqlOperatorTable();
// SQL解析配置参数
Optional<SqlParser.Config> getSqlParserConfig();
// SqlNode转RelNode配置参数
Optional<SqlToRelConverter.Config> getSqlToRelConvertConfig();
// RelNode默认特征属性
Optional<List<RelTraitDef>> getTraitDefs();
// RelNode代价
Optional<RelOptCostFactory> getCostFactory();
Optional<SduRelOptimizerFactory> getOptimizerFactory();
}
| 26.59375 | 64 | 0.807286 |
bb94273dd729a5362f3360e918aa8b6cc6032dda | 3,344 | package client;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class ClientScreen extends JFrame {
private User user;
private JPanel navPanel;
public ClientScreen(User user) {
super("Client");
this.user = user;
setSize(400, 120);
setResizable(false);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - getWidth();
int y = 0;
setLocation(x, y);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro = new JLabel();
intro.setText("안녕하세요, " + user.getUsername() + "님.");
add(intro, BorderLayout.NORTH);
navPanel = new JPanel();
add(navPanel, BorderLayout.SOUTH);
initTimerPanel();
initFoodOrderButton();
initChatButton();
initQuitButton();
setVisible(true);
}
private void initFoodOrderButton() {
JButton orderButton = new JButton();
orderButton.setName("먹거리");
orderButton.setText("먹거리");
orderButton.addActionListener(e -> new FoodScreen(user));
navPanel.add(orderButton, BorderLayout.CENTER);
}
private void initQuitButton() {
JButton quitButton = new JButton();
quitButton.setText("사용종료");
quitButton.addActionListener(e -> {
UserList.UPDATEUSER(user);
System.exit(0);
});
navPanel.add(quitButton, BorderLayout.CENTER);
}
private void initChatButton() {
JButton chatButton = new JButton();
chatButton.setText("채팅");
chatButton.addActionListener(e -> new ChatScreen(user));
navPanel.add(chatButton, BorderLayout.CENTER);
}
private JLabel timeLeftLabel;
private Timer timer;
private void initTimerPanel() {
JPanel timerPanel = new JPanel();
timer = new Timer();
timeLeftLabel = new JLabel();
timeLeftLabel.setFont(new Font("Serif", Font.PLAIN, 25));
timeLeftLabel.setText(timer.getTimeLeft());
Thread th = new Thread(timer);
th.setDaemon(true);
th.start();
timerPanel.add(timeLeftLabel);
add(timerPanel, BorderLayout.CENTER);
}
synchronized private void updateTime() {
timeLeftLabel.setText(timer.getTimeLeft());
}
private class Timer implements Runnable {
private int timeElapsed=0, timeLeft;
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeElapsed++;
timeLeft = user.getTimeLeft();
if (timeElapsed % 60 == 0) {
user.removeMinute();
}
updateTime();
}
}
public String getTimeLeft() {
int hours = timeLeft / 60;
int minutes = timeLeft % 60;
return String.format("남은 시간 %d시간 %02d분", hours, minutes);
}
}
}
| 27.866667 | 83 | 0.578947 |
0a959e4ed6aefa0f64f3e03aa74893bdb49feb50 | 2,494 | /*
* Copyright 2010 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package voldemort.store.socket.clientrequest;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import voldemort.client.protocol.RequestFormat;
import voldemort.common.nio.ByteBufferBackedOutputStream;
import voldemort.server.RequestRoutingType;
import voldemort.consistency.utils.ByteArray;
import voldemort.consistency.versioning.Versioned;
public class GetAllClientRequest extends
AbstractStoreClientRequest<Map<ByteArray, List<Versioned<byte[]>>>> {
private final Iterable<ByteArray> keys;
private final Map<ByteArray, byte[]> transforms;
public GetAllClientRequest(String storeName,
RequestFormat requestFormat,
RequestRoutingType requestRoutingType,
Iterable<ByteArray> keys,
Map<ByteArray, byte[]> transforms) {
super(storeName, requestFormat, requestRoutingType);
this.keys = keys;
this.transforms = transforms;
}
public boolean isCompleteResponse(ByteBuffer buffer) {
return requestFormat.isCompleteGetAllResponse(buffer);
}
@Override
protected void formatRequestInternal(ByteBufferBackedOutputStream outputStream)
throws IOException {
requestFormat.writeGetAllRequest(new DataOutputStream(outputStream),
storeName,
keys,
transforms,
requestRoutingType);
}
@Override
protected Map<ByteArray, List<Versioned<byte[]>>> parseResponseInternal(DataInputStream inputStream)
throws IOException {
return requestFormat.readGetAllResponse(inputStream);
}
}
| 36.144928 | 104 | 0.67482 |
5ddc919baf4b1209cc8907bb5446c3c98e8b0ee4 | 1,142 | /*
* Copyright (c) 2021 Callum Wong
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.callumwong.nullifier;
import com.callumwong.nullifier.client.event.ClientEventHandler;
import com.callumwong.nullifier.core.event.EventHandler;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@Mod(Nullifier.MOD_ID)
public class Nullifier {
public static final String MOD_ID = "nullifier";
public Nullifier() {
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
bus.register(EventHandler.class);
bus.register(ClientEventHandler.class);
}
}
| 36.83871 | 80 | 0.7662 |
e6f846f73009c0b78da18975a453715616cca413 | 10,779 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.example;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import com.archimatetool.editor.model.DiagramModelUtils;
import com.archimatetool.editor.model.IEditorModelManager;
import com.archimatetool.editor.model.IModelImporter;
import com.archimatetool.model.IArchimateComponent;
import com.archimatetool.model.IArchimateElement;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IArchimatePackage;
import com.archimatetool.model.IDiagramModel;
import com.archimatetool.model.IDiagramModelArchimateConnection;
import com.archimatetool.model.IDiagramModelArchimateObject;
import com.archimatetool.model.IDiagramModelComponent;
import com.archimatetool.model.IDiagramModelObject;
import com.archimatetool.model.IFolder;
import com.archimatetool.model.IRelationship;
/**
* Example Model Importer
* Shows basic import routines.
* You will need to read in the file somehow and model it in JDOM or DOM Sax parser or some representation and map
* this to Archi elements.
*
* @author Phillip Beauvoir
*/
@SuppressWarnings("nls")
public class MyImporter implements IModelImporter {
String MY_EXTENSION_WILDCARD = "*.mex"; //$NON-NLS-1$
// ID -> Object lookup table
Map<String, EObject> idLookup;
@Override
public void doImport() throws IOException {
File file = askOpenFile();
if(file == null) {
return;
}
// Load in the file and get its information here.
// Assuming you load in the data in some way, perhaps with JDOM, or a SAX Parser ot text reader then you will
// have a representation of it in memory that you need to map to Archi elements.
// Here is some example raw data in String format. This is a very simple example so the data
// is not in the best format. There is no error checking either.
// Elements
String[] elements = {
// Type, Name, ID
"BusinessActor", "Actor", "elementID1",
"BusinessRole", "Client", "elementID2",
"BusinessFunction", "My Function", "elementID3"
};
// Relationships
String[] relations = {
// Type, Name, ID, sourceID, targetID
"AssignmentRelationship", "Assigned to", "relID1", "elementID1", "elementID2",
"UsedByRelationship", "", "relID2", "elementID1", "elementID3",
"AssociationRelationship", "", "relID3", "elementID2", "elementID3"
};
// Views
String[] views = {
// Name, ID
"A View", "view1",
"Another View", "view2"
};
// View elements
String[] viewElements = {
// ID of parent View, ID of referenced element, x, y, width, height
"view1", "elementID1", "10", "10", "-1", "-1",
"view1", "elementID2", "310", "10", "-1", "-1",
"view1", "elementID3", "310", "110", "-1", "-1",
"view2", "elementID2", "10", "10", "-1", "-1",
"view2", "elementID3", "10", "110", "-1", "-1"
};
// View connections
String[] viewConnections = {
// ID of parent View, ID of relationship
"view1", "relID1",
"view1", "relID2",
"view2", "relID3",
};
// Create the model...
// Create a new Archimate Model and set its defaults
IArchimateModel model = IArchimateFactory.eINSTANCE.createArchimateModel();
model.setDefaults();
model.setName("My Model");
// Create and add elements matching imported data
// If an ID is not provided for an element then a unique ID will be generated when the model element is added to a parent
// model element, otherwise you can use your own IDs provided in the input data.
// Let's use an ID -> EObject mapping table for convenience
idLookup = new HashMap<String, EObject>();
// Create and add model elements
for(int i = 0; i < elements.length;) {
String type = elements[i++];
String name = elements[i++];
String id = elements[i++];
createAndAddArchimateElement(model, (EClass)IArchimatePackage.eINSTANCE.getEClassifier(type), name, id);
}
// Create and add model relationships and set source and target elements
for(int i = 0; i < relations.length;) {
String type = relations[i++];
String name = relations[i++];
String id = relations[i++];
String sourceID = relations[i++];
String targetID = relations[i++];
IRelationship relationship = createAndAddArchimateRelationship(model, (EClass)IArchimatePackage.eINSTANCE.getEClassifier(type), name, id);
// Find source and target elements from their IDs in the lookup table
IArchimateElement source = (IArchimateElement)idLookup.get(sourceID);
IArchimateElement target = (IArchimateElement)idLookup.get(targetID);
relationship.setSource(source);
relationship.setTarget(target);
}
// Create and add diagram views
for(int i = 0; i < views.length;) {
String name = views[i++];
String id = views[i++];
createAndAddView(model, name, id);
}
// Add diagram elements to views
for(int i = 0; i < viewElements.length;) {
String viewID = viewElements[i++];
String refID = viewElements[i++];
int x = Integer.parseInt(viewElements[i++]);
int y = Integer.parseInt(viewElements[i++]);
int width = Integer.parseInt(viewElements[i++]);
int height = Integer.parseInt(viewElements[i++]);
IDiagramModel diagramModel = (IDiagramModel)idLookup.get(viewID);
IArchimateElement element = (IArchimateElement)idLookup.get(refID);
createAndAddElementToView(diagramModel, element, x, y, width, height);
}
// Add diagram connections to views
for(int i = 0; i < viewConnections.length;) {
String viewID = viewConnections[i++];
String relationshipID = viewConnections[i++];
IDiagramModel diagramModel = (IDiagramModel)idLookup.get(viewID);
IRelationship relationship = (IRelationship)idLookup.get(relationshipID);
createAndAddConnectionsToView(diagramModel, relationship);
}
// And open the Model in the Editor
IEditorModelManager.INSTANCE.openModel(model);
}
protected void createAndAddConnectionsToView(IDiagramModel diagramModel, IRelationship relationship) {
List<IDiagramModelComponent> sources = DiagramModelUtils.findDiagramModelComponentsForArchimateComponent(diagramModel, relationship.getSource());
List<IDiagramModelComponent> targets = DiagramModelUtils.findDiagramModelComponentsForArchimateComponent(diagramModel, relationship.getTarget());
for(IDiagramModelComponent dmcSource : sources) {
for(IDiagramModelComponent dmcTarget : targets) {
IDiagramModelArchimateConnection dmc = IArchimateFactory.eINSTANCE.createDiagramModelArchimateConnection();
dmc.setRelationship(relationship);
dmc.connect((IDiagramModelObject)dmcSource, (IDiagramModelObject)dmcTarget);
idLookup.put(dmc.getId(), dmc);
}
}
}
protected IDiagramModelArchimateObject createAndAddElementToView(IDiagramModel diagramModel, IArchimateElement element, int x, int y, int width, int height) {
IDiagramModelArchimateObject dmo = IArchimateFactory.eINSTANCE.createDiagramModelArchimateObject();
dmo.setArchimateElement(element);
dmo.setBounds(x, y, width, height);
diagramModel.getChildren().add(dmo);
idLookup.put(dmo.getId(), dmo);
return dmo;
}
protected IDiagramModel createAndAddView(IArchimateModel model, String name, String id) {
IDiagramModel diagramModel = IArchimateFactory.eINSTANCE.createArchimateDiagramModel();
diagramModel.setName(name);
diagramModel.setId(id);
IFolder folder = model.getDefaultFolderForElement(diagramModel);
folder.getElements().add(diagramModel);
idLookup.put(diagramModel.getId(), diagramModel);
return diagramModel;
}
protected IRelationship createAndAddArchimateRelationship(IArchimateModel model, EClass type, String name, String id) {
if(!IArchimatePackage.eINSTANCE.getRelationship().isSuperTypeOf(type)) {
throw new IllegalArgumentException("Eclass type should be of relationship type");
}
return (IRelationship)createAndAddArchimateComponent(model, type, name, id);
}
protected IArchimateElement createAndAddArchimateElement(IArchimateModel model, EClass type, String name, String id) {
if(!IArchimatePackage.eINSTANCE.getArchimateElement().isSuperTypeOf(type)) {
throw new IllegalArgumentException("Eclass type should be of archimate element type");
}
return (IArchimateElement)createAndAddArchimateComponent(model, type, name, id);
}
protected IArchimateComponent createAndAddArchimateComponent(IArchimateModel model, EClass type, String name, String id) {
IArchimateComponent component = (IArchimateComponent)IArchimateFactory.eINSTANCE.create(type);
component.setName(name);
component.setId(id);
IFolder folder = model.getDefaultFolderForElement(component);
folder.getElements().add(component);
idLookup.put(component.getId(), component);
return component;
}
protected File askOpenFile() {
FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.OPEN);
dialog.setFilterExtensions(new String[] { MY_EXTENSION_WILDCARD, "*.*" } ); //$NON-NLS-1$
String path = dialog.open();
return path != null ? new File(path) : null;
}
}
| 43.46371 | 162 | 0.64672 |
51d5bfeca01464a2272ab1b207537eebb2329c6f | 6,812 | /*
* ******************************************************************************
* Copyright 2016
* Copyright (c) 2016 Technische Universität Darmstadt
*
* 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 tudarmstadt.lt.ABSentiment.featureExtractor;
import de.bwaldvogel.liblinear.Feature;
import de.bwaldvogel.liblinear.FeatureNode;
import org.apache.uima.jcas.JCas;
import org.jblas.FloatMatrix;
import tudarmstadt.lt.ABSentiment.featureExtractor.util.GenericWordSpace;
import tudarmstadt.lt.ABSentiment.featureExtractor.util.GloVeSpace;
import tudarmstadt.lt.ABSentiment.featureExtractor.util.VectorMath;
import tudarmstadt.lt.ABSentiment.featureExtractor.util.W2vSpace;
import tudarmstadt.lt.ABSentiment.uimahelper.Preprocessor;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
* Word Embedding {@link FeatureExtractor}, extracts the averaged word representation for an instance using a word embedding file.
*/
public class WordEmbeddingFeature implements FeatureExtractor {
private int offset = 0;
private int featureCount = 0;
private String weightedIdfFile;
private static GenericWordSpace<FloatMatrix> model;
private static TfIdfFeature tfIdfFeature;
private static HashMap<String, ArrayList<String>> DTExpansion = null;
/**
* Constructor; specifies the word embedding file. The type of word embedding. Feature offset is set to '0' by default.
* @param embeddingFile path to the file containing word embeddings
* @param wordRepresentation specifies the type of word embedding to be used
*/
public WordEmbeddingFeature(String embeddingFile, String weightedIdfFile, int wordRepresentation, String DTExpansionFile){
this.weightedIdfFile = weightedIdfFile;
if(wordRepresentation == 1){
model = GloVeSpace.load(embeddingFile, true, true);
}else{
model = W2vSpace.load(embeddingFile, true);
}
featureCount = model.getVectorLength();
if(this.weightedIdfFile != null){
tfIdfFeature = new TfIdfFeature(this.weightedIdfFile);
}
if(DTExpansionFile != null){
DTExpansion = new HashMap<>();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(DTExpansionFile));
String word = bufferedReader.readLine();
while(word!=null){
String words[] = word.split("\t");
String wordList[] = words[1].split(" ");
ArrayList<String> expansionWord = new ArrayList<>();
for(int i=0;i<wordList.length;i++){
expansionWord.add(wordList[i]);
}
DTExpansion.put(words[0], expansionWord);
word = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Constructor; specifies the word embedding file. The type of word embedding. Feature offset is specified.
* @param embeddingFile path to the file containing word embeddings
* @param wordRepresentation specifies the type of word embedding to be used
* @param offset the feature offset, all features start from this offset
*/
public WordEmbeddingFeature(String embeddingFile, String weightedIdfFile, int wordRepresentation, String DTExpansionFile, int offset){
this(embeddingFile, weightedIdfFile, wordRepresentation, DTExpansionFile);
this.offset = offset;
}
private Preprocessor preprocessor = new Preprocessor(true);
@Override
public Feature[] extractFeature(JCas cas) {
Collection<String> documentText = preprocessor.getTokenStrings(cas);
FloatMatrix wordVector = new FloatMatrix(featureCount);
int num = 0;
float termTfIdfWeight;
if(weightedIdfFile != null){
for (String token : documentText) {
termTfIdfWeight = 1;
if(tfIdfFeature.containsToken(token)){
termTfIdfWeight = (float) tfIdfFeature.getIdfScore(token);
}
if(model.contains(token)){
wordVector = wordVector.add(model.vector(token).mul(termTfIdfWeight));
num++;
}else{
if((DTExpansion != null) && (DTExpansion.containsKey(token))) {
for (String word : DTExpansion.get(token)) {
if (model.contains(word)) {
wordVector = wordVector.add(model.vector(word).mul(termTfIdfWeight));
num++;
break;
}
}
}
}
}
}else{
for (String token : documentText) {
if(model.contains(token)){
wordVector = wordVector.add(model.vector(token));
num++;
}else{
if((DTExpansion != null) && (DTExpansion.containsKey(token))) {
for (String word : DTExpansion.get(token)) {
if (model.contains(word)) {
wordVector = wordVector.add(model.vector(word));
num++;
break;
}
}
}
}
}
}
Feature[] instance = new Feature[featureCount];
if(VectorMath.sum(wordVector) != 0.0){
wordVector = VectorMath.normalize(wordVector);
}
for(int i=0;i<featureCount;i++){
instance[i] = new FeatureNode(i+offset+1, wordVector.get(i));
}
return instance;
}
@Override
public int getFeatureCount() {
return featureCount;
}
@Override
public int getOffset() {
return offset;
}
}
| 40.070588 | 138 | 0.582208 |
1a0c5dc41f7f7a3b68f4aa24d14d5fc7461e4fd9 | 2,107 | package com.miqt.wand;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import com.miqt.wand.anno.ParentalEntrustmentLevel;
/**
* Created by miqt on 2019/2/21.
* 获取插件apk中的布局,图片,颜色,尺寸等资源
*/
public class PluginResources {
AssetManager mManager;
Resources mResources;
private String packageName;
Context context;
/**
* @param context 上下文
* @param apkPath 插件apk路径
*/
public PluginResources(@NonNull Context context, @NonNull String apkPath) {
this.context = context;
init(apkPath);
}
private void init(String apkPath) {
mManager = ObjectFactory.make(AssetManager.class);
int cookie = ObjectFactory.invokeMethod(mManager, AssetManager.class.getName(),
"addAssetPath", ParentalEntrustmentLevel.PROJECT, apkPath);
mResources = new Resources(mManager,
context.getResources().getDisplayMetrics(),
context.getResources().getConfiguration());
PackageManager packageManager = context.getPackageManager();
PackageInfo info = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
packageName = appInfo.packageName;
}
}
public Resources getResources() {
return mResources;
}
public String getPackageName() {
return packageName;
}
public int getId(String name, String type) {
return mResources.getIdentifier(name, type, packageName);
}
public View getLayout(String name) {
XmlResourceParser parser = mResources.getLayout(getId(name, "layout"));
return LayoutInflater.from(context).inflate(parser, null, false);
}
}
| 31.447761 | 104 | 0.699098 |
d028b5fe42481089b8c7417a10b41254daa9c428 | 259 | package main.java.utils;
/**
* Created by johnchronis on 25/5/2016.
*/
public class Tuple3<X, Y, Z> {
public X x;
public Y y;
public Z z;
public Tuple3(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
}
| 13.631579 | 39 | 0.498069 |
579ba4b956aeb800961403e1bd4583b5a7c42cc9 | 1,840 | package org.zalando.stups.fullstop.web.test.builder;
import com.google.common.base.Optional;
import org.joda.time.DateTime;
import org.zalando.stups.fullstop.domain.AbstractModifiableEntity;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.fromNullable;
import static org.joda.time.DateTime.now;
/**
* @author ahartmann
*/
@SuppressWarnings({ "unchecked", "unused" })
public abstract class AbstractModifiableEntityBuilder<ENTITY_TYPE extends AbstractModifiableEntity, BUILDER_TYPE extends AbstractModifiableEntityBuilder>
extends AbstractCreatableEntityBuilder<ENTITY_TYPE, BUILDER_TYPE> {
private static final String DEFAULT_MODIFIER = "unit.test";
private Optional<DateTime> optionalLastModified = absent();
private Optional<String> optionalLastModifiedBy = absent();
private Optional<Long> optionalVersion = absent();
public AbstractModifiableEntityBuilder(final Class<ENTITY_TYPE> entityClass) {
super(entityClass);
}
@Override
public ENTITY_TYPE build() {
final ENTITY_TYPE entity = super.build();
entity.setLastModified(optionalLastModified.or(now()));
entity.setLastModifiedBy(optionalLastModifiedBy.or(DEFAULT_MODIFIER));
entity.setVersion(optionalVersion.orNull());
return entity;
}
public BUILDER_TYPE lastModified(final DateTime lastModified) {
optionalLastModified = fromNullable(lastModified);
return (BUILDER_TYPE) this;
}
public BUILDER_TYPE lastModifiedBy(final String lastModifiedBy) {
optionalLastModifiedBy = fromNullable(lastModifiedBy);
return (BUILDER_TYPE) this;
}
public BUILDER_TYPE version(final Long version) {
optionalVersion = fromNullable(version);
return (BUILDER_TYPE) this;
}
}
| 34.074074 | 153 | 0.747283 |
c22783918f17b20ad622d4d96d6e557947d04ef1 | 1,037 | package io.github.muxiaobai.java.java.construtorTest;
/**
*
* @author zhang
* @date 2016年7月22日 下午4:06:24
*
*/
public class StaticConstrutorTest {
static{
System.out.println("StaticConstrutorTest static ");
}
{
System.out.println("StaticConstrutorTest {}");
}
public static void main(String[] args) {
new HelloB();
System.out.println("========================");
new HelloB();
}
}
class HelloA {
static {
System.out.println("static A");
}
public HelloA() {
System.out.println("HelloA");
}
{
System.out.println("I'm A class");
}
}
class HelloB extends HelloA {
static {
System.out.println("static B");
}
public HelloB() {
System.out.println("HelloB");
}
{
System.out.println("I'm B class");
}
}
//静态块在第一个对象创建时运行static{}
//初始化块在每个对象创建时运行{}
//构造块public className{}
//区别是静态块只执行一次,操作的内存在静态区
//初始化块每个对象构造时都需要执行一次,操作的内存在用户区
//复制代码 答案: static A static B I'm A class HelloA I'm B class HelloB | 19.203704 | 77 | 0.591128 |
082c675e3ed776e7d00bd4e510f342c31afdde79 | 6,381 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.weblayer_private.payments;
import androidx.annotation.Nullable;
import org.chromium.components.payments.BrowserPaymentRequest;
import org.chromium.components.payments.JourneyLogger;
import org.chromium.components.payments.PaymentApp;
import org.chromium.components.payments.PaymentAppFactoryDelegate;
import org.chromium.components.payments.PaymentAppService;
import org.chromium.components.payments.PaymentAppType;
import org.chromium.components.payments.PaymentRequestService;
import org.chromium.components.payments.PaymentRequestService.Delegate;
import org.chromium.components.payments.PaymentRequestSpec;
import org.chromium.components.payments.PaymentResponseHelper;
import org.chromium.components.payments.PaymentResponseHelperInterface;
import org.chromium.payments.mojom.PaymentDetails;
import org.chromium.payments.mojom.PaymentErrorReason;
import org.chromium.payments.mojom.PaymentItem;
import org.chromium.payments.mojom.PaymentValidationErrors;
import java.util.ArrayList;
import java.util.List;
/** The WebLayer-specific part of the payment request service. */
public class WebLayerPaymentRequestService implements BrowserPaymentRequest {
private final List<PaymentApp> mAvailableApps = new ArrayList<>();
private final JourneyLogger mJourneyLogger;
private PaymentRequestService mPaymentRequestService;
private PaymentRequestSpec mSpec;
private boolean mHasClosed;
private boolean mShouldSkipAppSelector;
private PaymentApp mSelectedApp;
/**
* Create an instance of {@link WebLayerPaymentRequestService}.
* @param paymentRequestService The payment request service.
* @param delegate The delegate of the payment request service.
*/
public WebLayerPaymentRequestService(
PaymentRequestService paymentRequestService, Delegate delegate) {
mPaymentRequestService = paymentRequestService;
mJourneyLogger = mPaymentRequestService.getJourneyLogger();
}
// Implements BrowserPaymentRequest:
@Override
public void onPaymentDetailsUpdated(
PaymentDetails details, boolean hasNotifiedInvokedPaymentApp) {}
// Implements BrowserPaymentRequest:
@Override
public void onPaymentDetailsNotUpdated(String selectedShippingOptionError) {}
@Override
public boolean onPaymentAppCreated(PaymentApp paymentApp) {
// Ignores the service worker payment apps in WebLayer until -
// TODO(crbug.com/1224420): WebLayer supports Service worker payment apps.
return paymentApp.getPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP;
}
// Implements BrowserPaymentRequest:
@Override
public void complete(int result, Runnable onCompleteHandled) {
onCompleteHandled.run();
}
// Implements BrowserPaymentRequest:
@Override
public void onRetry(PaymentValidationErrors errors) {}
// Implements BrowserPaymentRequest:
@Override
public void close() {
if (mHasClosed) return;
mHasClosed = true;
if (mPaymentRequestService != null) {
mPaymentRequestService.close();
mPaymentRequestService = null;
}
}
// Implements BrowserPaymentRequest:
@Override
public boolean hasAvailableApps() {
return !mAvailableApps.isEmpty();
}
// Implements BrowserPaymentRequest:
@Override
public void notifyPaymentUiOfPendingApps(List<PaymentApp> pendingApps) {
assert mAvailableApps.isEmpty()
: "notifyPaymentUiOfPendingApps() should be called at most once.";
mAvailableApps.addAll(pendingApps);
mSelectedApp = mAvailableApps.size() == 0 ? null : mAvailableApps.get(0);
}
// Implements BrowserPaymentRequest:
@Override
public void onSpecValidated(PaymentRequestSpec spec) {
mSpec = spec;
}
// Implements BrowserPaymentRequest:
@Override
public void addPaymentAppFactories(
PaymentAppService service, PaymentAppFactoryDelegate delegate) {
// There's no WebLayer specific factories.
}
// Implements BrowserPaymentRequest:
@Override
@Nullable
public String showOrSkipAppSelector(boolean isShowWaitingForUpdatedDetails, PaymentItem total,
boolean shouldSkipAppSelector) {
mShouldSkipAppSelector = shouldSkipAppSelector;
if (!mShouldSkipAppSelector) {
return "This request is not supported in Web Layer. Please try in Chrome, or make sure "
+ "that: (1) show() is triggered by user gesture, or"
+ "(2) do not request any contact information.";
}
return null;
}
// Implements BrowserPaymentRequest:
@Override
@Nullable
public String onShowCalledAndAppsQueriedAndDetailsFinalized(boolean isUserGestureShow) {
assert !mAvailableApps.isEmpty()
: "triggerPaymentAppUiSkipIfApplicable() should be called only when there is any "
+ "available app.";
PaymentApp selectedPaymentApp = mAvailableApps.get(0);
if (mShouldSkipAppSelector) {
mJourneyLogger.setSkippedShow();
PaymentResponseHelperInterface paymentResponseHelper =
new PaymentResponseHelper(selectedPaymentApp, mSpec.getPaymentOptions());
mPaymentRequestService.invokePaymentApp(selectedPaymentApp, paymentResponseHelper);
}
return null;
}
// Implements BrowserPaymentRequest:
@Override
public PaymentApp getSelectedPaymentApp() {
return mAvailableApps.get(0);
}
// Implements BrowserPaymentRequest:
@Override
public List<PaymentApp> getPaymentApps() {
return mAvailableApps;
}
// Implements BrowserPaymentRequest:
@Override
public boolean hasAnyCompleteApp() {
return !mAvailableApps.isEmpty() && mAvailableApps.get(0).isComplete();
}
private void disconnectFromClientWithDebugMessage(String debugMessage) {
if (mPaymentRequestService != null) {
mPaymentRequestService.disconnectFromClientWithDebugMessage(
debugMessage, PaymentErrorReason.USER_CANCEL);
}
close();
}
}
| 37.098837 | 100 | 0.724024 |
b2d69de377837f51c5104b3934ec7c24b637e4d1 | 1,145 | package com.michaelbradleymods.firstmod.util.handlers;
import com.michaelbradleymods.firstmod.init.ModItems;
import com.michaelbradleymods.firstmod.util.IHasModel;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class RegistryHandler
{
private final ModItems modItems;
/**
* Create a handler for registry events.
*
* @param modItems should be an initialised ModItems instance
*/
public RegistryHandler(final ModItems modItems)
{
this.modItems = modItems;
}
@SubscribeEvent
public void onItemRegister(final RegistryEvent.Register<Item> event)
{
event.getRegistry().registerAll(modItems.items.toArray(new Item[0]));
}
@SubscribeEvent
public void onModelRegister(final ModelRegistryEvent event)
{
for (final Item item : modItems.items)
{
if (item instanceof IHasModel)
{
((IHasModel) item).registerModels();
}
}
}
}
| 27.261905 | 77 | 0.692576 |
8802651aae8b4abb73fb4dd4fe05842df95056af | 14,796 | package com.mysql.cj.xdevapi;
import com.mysql.cj.Messages;
import com.mysql.cj.exceptions.AssertionFailedException;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.WrongArgumentException;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class JsonParser {
enum Whitespace {
TAB('\t'),
LF('\n'),
CR('\r'),
SPACE(' ');
public final char CHAR;
Whitespace(char character) {
this.CHAR = character;
}
}
enum StructuralToken {
LSQBRACKET('['),
RSQBRACKET(']'),
LCRBRACKET('{'),
RCRBRACKET('}'),
COLON(':'),
COMMA(',');
public final char CHAR;
StructuralToken(char character) {
this.CHAR = character;
}
}
enum EscapeChar {
QUOTE('"', "\\\""),
RSOLIDUS('\\', "\\\\"),
SOLIDUS('/', "\\/"),
BACKSPACE('\b', "\\b"),
FF('\f', "\\f"),
LF('\n', "\\n"),
CR('\r', "\\r"),
TAB('\t', "\\t");
public final char CHAR;
public final String ESCAPED;
EscapeChar(char character, String escaped) {
this.CHAR = character;
this.ESCAPED = escaped;
}
}
static Set<Character> whitespaceChars = new HashSet<>();
static HashMap<Character, Character> unescapeChars = new HashMap<>();
static {
for (EscapeChar ec : EscapeChar.values())
unescapeChars.put(Character.valueOf(ec.ESCAPED.charAt(1)), Character.valueOf(ec.CHAR));
for (Whitespace ws : Whitespace.values())
whitespaceChars.add(Character.valueOf(ws.CHAR));
}
private static boolean isValidEndOfValue(char ch) {
return (StructuralToken.COMMA.CHAR == ch || StructuralToken.RCRBRACKET.CHAR == ch || StructuralToken.RSQBRACKET.CHAR == ch);
}
public static DbDoc parseDoc(String jsonString) {
try {
return parseDoc(new StringReader(jsonString));
} catch (IOException ex) {
throw AssertionFailedException.shouldNotHappen(ex);
}
}
public static DbDoc parseDoc(StringReader reader) throws IOException {
DbDoc doc = new DbDocImpl();
int leftBrackets = 0;
int rightBrackets = 0;
int intch;
while ((intch = reader.read()) != -1) {
String key = null;
char ch = (char)intch;
if (ch == StructuralToken.LCRBRACKET.CHAR || ch == StructuralToken.COMMA.CHAR) {
if (ch == StructuralToken.LCRBRACKET.CHAR)
leftBrackets++;
if ((key = nextKey(reader)) != null) {
try {
JsonValue val;
if ((val = nextValue(reader)) != null) {
doc.put(key, val);
continue;
}
reader.reset();
} catch (WrongArgumentException ex) {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.0", new String[] { key }), ex);
}
continue;
}
reader.reset();
continue;
}
if (ch == StructuralToken.RCRBRACKET.CHAR) {
rightBrackets++;
break;
}
if (!whitespaceChars.contains(Character.valueOf(ch)))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
if (leftBrackets == 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.2"));
if (leftBrackets > rightBrackets)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.3", new Character[] { Character.valueOf(StructuralToken.RCRBRACKET.CHAR) }));
return doc;
}
public static JsonArray parseArray(StringReader reader) throws IOException {
JsonArray arr = new JsonArray();
int openings = 0;
int intch;
while ((intch = reader.read()) != -1) {
char ch = (char)intch;
if (ch == StructuralToken.LSQBRACKET.CHAR || ch == StructuralToken.COMMA.CHAR) {
if (ch == StructuralToken.LSQBRACKET.CHAR)
openings++;
JsonValue val;
if ((val = nextValue(reader)) != null) {
arr.add(val);
continue;
}
reader.reset();
continue;
}
if (ch == StructuralToken.RSQBRACKET.CHAR) {
openings--;
break;
}
if (!whitespaceChars.contains(Character.valueOf(ch)))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
if (openings > 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.3", new Character[] { Character.valueOf(StructuralToken.RSQBRACKET.CHAR) }));
return arr;
}
private static String nextKey(StringReader reader) throws IOException {
reader.mark(1);
JsonString val = parseString(reader);
if (val == null)
reader.reset();
char ch = ' ';
int intch;
while ((intch = reader.read()) != -1) {
ch = (char)intch;
if (ch == StructuralToken.COLON.CHAR)
break;
if (ch == StructuralToken.RCRBRACKET.CHAR)
break;
if (!whitespaceChars.contains(Character.valueOf(ch)))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
if (ch != StructuralToken.COLON.CHAR && val != null && val.getString().length() > 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.4", new String[] { val.getString() }));
return (val != null) ? val.getString() : null;
}
private static JsonValue nextValue(StringReader reader) throws IOException {
reader.mark(1);
int intch;
while ((intch = reader.read()) != -1) {
char ch = (char)intch;
if (ch == EscapeChar.QUOTE.CHAR) {
reader.reset();
return parseString(reader);
}
if (ch == StructuralToken.LSQBRACKET.CHAR) {
reader.reset();
return parseArray(reader);
}
if (ch == StructuralToken.LCRBRACKET.CHAR) {
reader.reset();
return parseDoc(reader);
}
if (ch == '-' || (ch >= '0' && ch <= '9')) {
reader.reset();
return parseNumber(reader);
}
if (ch == JsonLiteral.TRUE.value.charAt(0)) {
reader.reset();
return parseLiteral(reader);
}
if (ch == JsonLiteral.FALSE.value.charAt(0)) {
reader.reset();
return parseLiteral(reader);
}
if (ch == JsonLiteral.NULL.value.charAt(0)) {
reader.reset();
return parseLiteral(reader);
}
if (ch == StructuralToken.RSQBRACKET.CHAR)
return null;
if (!whitespaceChars.contains(Character.valueOf(ch)))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
reader.mark(1);
}
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.5"));
}
private static void appendChar(StringBuilder sb, char ch) {
if (sb == null) {
if (!whitespaceChars.contains(Character.valueOf(ch)))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.6", new Character[] { Character.valueOf(ch) }));
} else {
sb.append(ch);
}
}
static JsonString parseString(StringReader reader) throws IOException {
int quotes = 0;
boolean escapeNextChar = false;
StringBuilder sb = null;
int intch;
while ((intch = reader.read()) != -1) {
char ch = (char)intch;
if (escapeNextChar) {
if (unescapeChars.containsKey(Character.valueOf(ch))) {
appendChar(sb, ((Character)unescapeChars.get(Character.valueOf(ch))).charValue());
} else {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.7", new Character[] { Character.valueOf(ch) }));
}
escapeNextChar = false;
continue;
}
if (ch == EscapeChar.QUOTE.CHAR) {
if (sb == null) {
sb = new StringBuilder();
quotes++;
continue;
}
quotes--;
break;
}
if (quotes == 0 && ch == StructuralToken.RCRBRACKET.CHAR)
break;
if (ch == EscapeChar.RSOLIDUS.CHAR) {
escapeNextChar = true;
continue;
}
appendChar(sb, ch);
}
if (quotes > 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.3", new Character[] { Character.valueOf(EscapeChar.QUOTE.CHAR) }));
return (sb == null) ? null : (new JsonString()).setValue(sb.toString());
}
static JsonNumber parseNumber(StringReader reader) throws IOException {
StringBuilder sb = null;
char lastChar = ' ';
boolean hasFractionalPart = false;
boolean hasExponent = false;
int intch;
while ((intch = reader.read()) != -1) {
char ch = (char)intch;
if (sb == null) {
if (ch == '-') {
sb = new StringBuilder();
sb.append(ch);
} else if (ch >= '0' && ch <= '9') {
sb = new StringBuilder();
sb.append(ch);
} else if (!whitespaceChars.contains(Character.valueOf(ch))) {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
} else if (ch == '-') {
if (lastChar == 'E' || lastChar == 'e') {
sb.append(ch);
} else {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.8", new Object[] { Character.valueOf(ch), sb.toString() }));
}
} else if (ch >= '0' && ch <= '9') {
sb.append(ch);
} else if (ch == 'E' || ch == 'e') {
if (lastChar >= '0' && lastChar <= '9') {
hasExponent = true;
sb.append(ch);
} else {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.8", new Object[] { Character.valueOf(ch), sb.toString() }));
}
} else if (ch == '.') {
if (hasFractionalPart)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.10", new Object[] { Character.valueOf(ch), sb.toString() }));
if (hasExponent)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.11"));
if (lastChar >= '0' && lastChar <= '9') {
hasFractionalPart = true;
sb.append(ch);
} else {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.8", new Object[] { Character.valueOf(ch), sb.toString() }));
}
} else if (ch == '+') {
if (lastChar == 'E' || lastChar == 'e') {
sb.append(ch);
} else {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("JsonParser.8", new Object[] { Character.valueOf(ch), sb.toString() }));
}
} else {
if (whitespaceChars.contains(Character.valueOf(ch)) || isValidEndOfValue(ch)) {
reader.reset();
break;
}
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
lastChar = ch;
reader.mark(1);
}
if (sb == null || sb.length() == 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.5"));
return (new JsonNumber()).setValue(sb.toString());
}
static JsonLiteral parseLiteral(StringReader reader) throws IOException {
StringBuilder sb = null;
JsonLiteral res = null;
int literalIndex = 0;
int intch;
while ((intch = reader.read()) != -1) {
char ch = (char)intch;
if (sb == null) {
if (ch == JsonLiteral.TRUE.value.charAt(0)) {
res = JsonLiteral.TRUE;
sb = new StringBuilder();
sb.append(ch);
literalIndex++;
} else if (ch == JsonLiteral.FALSE.value.charAt(0)) {
res = JsonLiteral.FALSE;
sb = new StringBuilder();
sb.append(ch);
literalIndex++;
} else if (ch == JsonLiteral.NULL.value.charAt(0)) {
res = JsonLiteral.NULL;
sb = new StringBuilder();
sb.append(ch);
literalIndex++;
} else if (!whitespaceChars.contains(Character.valueOf(ch))) {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
} else if (literalIndex < res.value.length() && ch == res.value.charAt(literalIndex)) {
sb.append(ch);
literalIndex++;
} else {
if (whitespaceChars.contains(Character.valueOf(ch)) || isValidEndOfValue(ch)) {
reader.reset();
break;
}
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.1", new Character[] { Character.valueOf(ch) }));
}
reader.mark(1);
}
if (sb == null)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.5"));
if (literalIndex == res.value.length())
return res;
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("JsonParser.12", new String[] { sb.toString() }));
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\xdevapi\JsonParser.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 38.232558 | 198 | 0.619965 |
de4151eb3038f53e69cd37a4938deab6d267eb60 | 421 | package chachichat.packets;
import com.esotericsoftware.kryo.Kryo;
public class Packets {
public static void registerPackets(Kryo kryo) {
kryo.register(PacketMessage.class);
}
public static class PacketMessage {
public String msg;
public PacketMessage() {
// Necesario para poder enviarlo
}
public PacketMessage(String msg) {
this.msg = msg;
}
}
}
| 15.035714 | 49 | 0.646081 |
cdc317977564dab196feeeaacd5636983f88a3af | 507 | package DB;
import java.io.Serializable;
/**
* Created by Anil on 19/03/2018
*/
public class LabInstructor implements Serializable {
private LabBatch labBatch;
private Teacher teacher;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public LabBatch getLabBatch() {
return labBatch;
}
public void setLabBatch(LabBatch labBatch) {
this.labBatch = labBatch;
}
}
| 18.107143 | 52 | 0.650888 |
cea79ba52305863896c7b9e3effe9c9acb253133 | 1,808 | package com.shangame.fiction.ui.popup;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.fiction.bar.R;
/**
* Create by Speedy on 2019/5/9
*/
public class DeleteBookPopupWindow {
private Activity mActivity;
private View.OnClickListener deleteOnClickListener;
public DeleteBookPopupWindow(Activity activity) {
mActivity = activity;
}
public void show(final int count) {
new XPopup.Builder(mActivity).asCustom(new BottomPopupView(mActivity) {
@Override
protected void initPopupContent() {
super.initPopupContent();
findViewById(R.id.tvDelete).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
if (deleteOnClickListener != null) {
deleteOnClickListener.onClick(v);
}
}
});
TextView tvInfo = findViewById(R.id.tvInfo);
tvInfo.setText("从书架删除选中的" + count + "本书吗?");
findViewById(R.id.tvCancel).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
@Override
protected int getImplLayoutId() {
return R.layout.popup_delete_book;
}
}).show();
}
public void setDeleteOnClickListener(View.OnClickListener deleteOnClickListener) {
this.deleteOnClickListener = deleteOnClickListener;
}
}
| 30.644068 | 86 | 0.561947 |
50e8b07b3bc5fe02bc572a1046f556d7bc232776 | 500 | package com.company.managers;
import com.company.models.Revenues;
import java.util.ArrayList;
import java.util.List;
public class RevenuesManager {
private List<Revenues> revenues = new ArrayList<>();
private static RevenuesManager revenuesManagersin = new RevenuesManager();
private RevenuesManager() {
}
public static RevenuesManager getInstance()
{
return revenuesManagersin;
}
public List<Revenues> getRevenues() {
return revenues;
}
}
| 19.230769 | 78 | 0.704 |
ee356ac9aa436da759c70f15c4b62494bc1dd838 | 4,507 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.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 org.pentaho.di.core.osgi.api;
import org.pentaho.metastore.api.IMetaStore;
import org.pentaho.metastore.api.exceptions.MetaStoreException;
import java.util.List;
import java.util.Map;
/**
* Created by tkafalas on 7/6/2017.
*/
public interface NamedClusterServiceOsgi {
/**
* This method returns the named cluster template used to configure new NamedClusters.
* <p/>
* Note that this method returns a clone (deep) of the template.
*
* @return the NamedCluster template
*/
NamedClusterOsgi getClusterTemplate();
/**
* This method will set the cluster template used when creating new NamedClusters
*
* @param clusterTemplate the NamedCluster template to set
*/
void setClusterTemplate( NamedClusterOsgi clusterTemplate );
/**
* Saves a named cluster in the provided IMetaStore
*
* @param namedCluster the NamedCluster to save
* @param metastore the IMetaStore to operate with
* @throws MetaStoreException
*/
void create( NamedClusterOsgi namedCluster, IMetaStore metastore ) throws MetaStoreException;
/**
* Reads a NamedCluster from the provided IMetaStore
*
* @param clusterName the name of the NamedCluster to load
* @param metastore the IMetaStore to operate with
* @return the NamedCluster that was loaded
* @throws MetaStoreException
*/
NamedClusterOsgi read( String clusterName, IMetaStore metastore ) throws MetaStoreException;
/**
* Updates a NamedCluster in the provided IMetaStore
*
* @param namedCluster the NamedCluster to update
* @param metastore the IMetaStore to operate with
* @throws MetaStoreException
*/
void update( NamedClusterOsgi namedCluster, IMetaStore metastore ) throws MetaStoreException;
/**
* Deletes a NamedCluster from the provided IMetaStore
*
* @param clusterName the NamedCluster to delete
* @param metastore the IMetaStore to operate with
* @throws MetaStoreException
*/
void delete( String clusterName, IMetaStore metastore ) throws MetaStoreException;
/**
* This method lists the NamedCluster in the given IMetaStore
*
* @param metastore the IMetaStore to operate with
* @return the list of NamedClusters in the provided IMetaStore
* @throws MetaStoreException
*/
List<NamedClusterOsgi> list( IMetaStore metastore ) throws MetaStoreException;
/**
* This method returns the list of NamedCluster names in the IMetaStore
*
* @param metastore the IMetaStore to operate with
* @return the list of NamedCluster names (Strings)
* @throws MetaStoreException
*/
List<String> listNames( IMetaStore metastore ) throws MetaStoreException;
/**
* This method checks if the NamedCluster exists in the metastore
*
* @param clusterName the name of the NamedCluster to check
* @param metastore the IMetaStore to operate with
* @return true if the NamedCluster exists in the given metastore
* @throws MetaStoreException
*/
boolean contains( String clusterName, IMetaStore metastore ) throws MetaStoreException;
NamedClusterOsgi getNamedClusterByName( String namedCluster, IMetaStore metastore );
/**
* This method load the properties for named cluster from /etc/config folder
*
* @return map with properties for named cluster
*/
Map<String, Object> getProperties();
/**
* If the metastore object temporary and should not be kept active indefinitely, this method will release all
* resources associated with the metastore.
* @param metastore the IMetaStore being disposed.
*/
void close( IMetaStore metastore );
}
| 33.634328 | 111 | 0.694697 |
85f07276e99346f5a54a50c109a9201bbb70e324 | 2,119 | /*
* Copyright (c) 2018, hiwepy (https://github.com/hiwepy).
*
* 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.hiwepy.fastpoi.publisher;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hpbf.extractor.PublisherTextExtractor;
import com.github.hiwepy.fastpoi.utils.ExtensionUtils;
import com.github.hiwepy.fastpoi.utils.LogUtils;
public class PublisherReader {
private static PublisherReader instance = null;
private static Object initLock = new Object();
private PublisherReader(){};
public static PublisherReader getInstance(){
if (instance == null) {
synchronized(initLock) {
instance= new PublisherReader();
}
}
return instance;
}
public PublisherTextExtractor getTextExtactor(File file) throws IOException{
if(file.exists()){
if(ExtensionUtils.isPublisher(file.getAbsolutePath())){
PublisherTextExtractor extactor = null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
extactor = new PublisherTextExtractor(inputStream);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
LogUtils.error(e);
}
}
}
return extactor;
}else{
throw new IOException("the file input is not a Outlook file ! ");
}
}else{
throw new IOException("the file not exists ! ");
}
}
public PublisherTextExtractor getTextExtactor(String inFilePath) throws IOException{
return this.getTextExtactor(new File(inFilePath) );
}
}
| 28.253333 | 85 | 0.717791 |
c55ad966c1c53922ec5a4c849fe10a6b2d4d8796 | 43 | package java.lang;
public class Byte {
} | 8.6 | 19 | 0.697674 |
69a257c2f6a14a3db1a668259dad0dfbf14404f7 | 829 | package com.anshul.interview.ds.trees;
public class Soutions {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
return toBST(head, null);
}
public TreeNode toBST(ListNode head, ListNode tail) {
ListNode slow = head;
ListNode fast = head;
if (head == tail)
return null;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode thead = new TreeNode(slow.val);
thead.left = toBST(head, slow);
thead.right = toBST(slow.next, tail);
return thead;
}
}
}
| 16.918367 | 55 | 0.624849 |
4ef226d29d51e30ffd686839b47dc45784d96ffa | 1,820 | package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.UserData;
import ru.stqa.pft.addressbook.model.Users;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class UserDeletionTest extends TestBase {
@BeforeTest
public void ensurePreconditions(){
if (app.db().users().size() == 0){
if (app.db().groups().size() == 0) {
app.goTo().groupPage();
app.group().create(new GroupData().withGroupName("Name").withGroupHeader("test1"));
}
app.goTo().pageHome();
app.contact().createNewUser(new UserData().withFirstName("first name").withMiddleName("middle name")
.withLastName("last name").inGroup(app.db().groups().iterator().next()), true);
}
}
@Test
public void testDeletionGroup() throws InterruptedException {
Users before = app.db().users();
app.goTo().pageHome();
UserData deletedUser = before.iterator().next();
System.out.println("deletedUser ---> " + deletedUser);
app.contact().delete(deletedUser);
app.goTo().pageHome();
Thread.sleep(3000);
Users after = app.db().users();
//проверка размера - пока они отличаются,новый элемнт никуда не добавляла\удаляла
Assert.assertEquals(after.size(), before.size()-1);
assertThat(after, equalTo(before.without(deletedUser)));
assertThat(after.size(), equalTo(before.size()-1));
System.out.println("DeleteTest: Before: " + before);
System.out.println("DeleteTest: After: " + after);
}
}
| 36.4 | 112 | 0.644505 |
ff8879dd1c10db28f3b7e38fdd298420b3631b38 | 122 | package co.kr.ingeni.twitterloginexample;
public interface TwitterWriteTaskFunction {
void doFinish(Boolean result);
}
| 17.428571 | 43 | 0.819672 |
f320548a8ef15ae1f9de5ff9739ec5fb5b85ac7d | 1,555 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.lob;
import java.util.Random;
import org.junit.Test;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
/**
* @author Chris Cranford
*/
@RequiresDialectFeature(DialectChecks.ForceLobAsLastValue.class)
@TestForIssue(jiraKey = "HHH-8382")
public class LobAsLastValueTest extends BaseCoreFunctionalTestCase {
@Override
protected String[] getMappings() {
return new String[] { "lob/LobAsLastValue.hbm.xml" };
}
@Test
public void testInsertLobAsLastValue() {
doInHibernate( this::sessionFactory, session -> {
byte[] details = new byte[4000];
byte[] title = new byte[2000];
Random random = new Random();
random.nextBytes( details );
random.nextBytes( title );
// This insert will fail on Oracle without the fix to ModelBinder flagging SimpleValue and Property as Lob
// because the fields will not be placed at the end of the insert, resulting in an Oracle failure.
final LobAsLastValueEntity entity = new LobAsLastValueEntity( "Test", new String( details ), new String( title ) );
session.save( entity );
} );
}
}
| 31.734694 | 118 | 0.752412 |
d377ee5c3e635fa106645a43d583d275a09a3454 | 1,642 | package com.revolsys.ui.html.serializer.key;
import com.revolsys.record.io.format.xml.XmlWriter;
import com.revolsys.ui.web.utils.HttpServletUtils;
import com.revolsys.util.HtmlAttr;
import com.revolsys.util.HtmlElem;
import com.revolsys.util.JavaBeanUtil;
public class BooleanImageKeySerializer extends AbstractKeySerializer {
public static boolean serialize(final XmlWriter out, final Object object, final String name) {
final Object value = JavaBeanUtil.getBooleanValue(object, name);
String text;
String imageName;
final boolean result = Boolean.TRUE.equals(value);
if (result) {
imageName = "tick";
text = "Yes";
} else {
imageName = "cross";
text = "No";
}
out.startTag(HtmlElem.IMG);
out.attribute(HtmlAttr.SRC, HttpServletUtils.getAbsoluteUrl("/images/" + imageName + ".png"));
out.attribute(HtmlAttr.ALT, text);
out.attribute(HtmlAttr.TITLE, text);
out.endTag(HtmlElem.IMG);
return result;
}
public BooleanImageKeySerializer() {
setProperty("searchable", false);
}
public BooleanImageKeySerializer(final String name) {
super(name);
setProperty("searchable", false);
}
public BooleanImageKeySerializer(final String name, final String label) {
super(name, label);
setProperty("searchable", false);
}
/**
* Serialize the value to the XML writer.
*
* @param out The XML writer to serialize to.
* @param object The object to get the value from.
*/
@Override
public void serialize(final XmlWriter out, final Object object) {
final String name = getName();
serialize(out, object, name);
}
}
| 29.321429 | 98 | 0.701583 |
987f9590b2cd470539f7981c8bc3edff25c3be7a | 2,482 | package br.com.caulox.luizalabscommunicationapi.controller;
import br.com.caulox.luizalabscommunicationapi.domain.Schedule;
import br.com.caulox.luizalabscommunicationapi.requests.SchedulePatchRequest;
import br.com.caulox.luizalabscommunicationapi.requests.SchedulePostRequest;
import br.com.caulox.luizalabscommunicationapi.service.ScheduleService;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RequiredArgsConstructor
@RestController
@RequestMapping("communication-api/schedules")
public class ScheduleController {
private final ScheduleService scheduleService;
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Agendamento criado com sucesso"),
@ApiResponse(responseCode = "400", description = "Erro nos parâmetros da requisição"),
})
@PostMapping
public ResponseEntity<Schedule> save(@RequestBody @Valid SchedulePostRequest schedulePostRequest) {
return new ResponseEntity<>(this.scheduleService.save(schedulePostRequest), HttpStatus.CREATED);
}
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Consulta de agendamento com sucesso"),
@ApiResponse(responseCode = "400", description = "Tipo de id inválido"),
@ApiResponse(responseCode = "404", description = "Agendamento não encontrado")
})
@GetMapping("{id}")
public ResponseEntity<Schedule> findById(@PathVariable Long id) {
return ResponseEntity.ok(this.scheduleService.findByIdOrThrowObjectNotFoundException(id));
}
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Operação com Sucesso"),
@ApiResponse(responseCode = "400", description = "Erro nos parâmetros da requisição"),
@ApiResponse(responseCode = "404", description = "Agendamento não encontrado")
})
@PatchMapping("{id}")
public ResponseEntity<Void> updateStatus(@PathVariable Long id,
@RequestBody SchedulePatchRequest schedulePatchRequest) {
this.scheduleService.updateStatus(id, schedulePatchRequest);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
| 45.962963 | 104 | 0.737309 |
cb6731f9d4082c426f48aa84669bb3e29172a9f5 | 6,289 | /*
* 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.geronimo.console.car;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.enterprise.deploy.spi.DeploymentManager;
import javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException;
import javax.enterprise.deploy.spi.factories.DeploymentFactory;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import org.apache.geronimo.console.util.PortletManager;
import org.apache.geronimo.deployment.plugin.factories.DeploymentFactoryWithKernel;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.kernel.GBeanNotFoundException;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.system.plugin.PluginInstaller;
import org.apache.geronimo.system.plugin.PluginRepositoryList;
import org.apache.geronimo.system.plugin.ServerArchiver;
/**
* @version $Rev$ $Date$
*/
public class ManagementHelper {
private final static String PLUGIN_HELPER_KEY = "org.apache.geronimo.console.PluginManagementHelper";
private final Kernel kernel;
private PluginInstaller pluginInstaller;
private ServerArchiver archiver;
private List<PluginRepositoryList> pluginRepositoryLists;
public static ManagementHelper getManagementHelper(PortletRequest request) {
ManagementHelper helper = (ManagementHelper) request.getPortletSession(true).getAttribute(PLUGIN_HELPER_KEY, PortletSession.APPLICATION_SCOPE);
if (helper == null) {
Kernel kernel = PortletManager.getKernel();
helper = new ManagementHelper(kernel);
request.getPortletSession().setAttribute(PLUGIN_HELPER_KEY, helper, PortletSession.APPLICATION_SCOPE);
}
return helper;
}
public ManagementHelper(Kernel kernel) {
this.kernel = kernel;
}
public PluginInstaller getPluginInstaller() {
if (pluginInstaller == null) {
Set<AbstractName> pluginInstallers = kernel.listGBeans(new AbstractNameQuery(PluginInstaller.class.getName()));
if (pluginInstallers.size() == 0) {
throw new IllegalStateException("No plugin installer registered");
}
try {
pluginInstaller = (PluginInstaller) kernel.getGBean(pluginInstallers.iterator().next());
} catch (GBeanNotFoundException e) {
throw new IllegalStateException("Plugin installer cannot be retrieved from kernel");
}
}
return pluginInstaller;
}
public ServerArchiver getArchiver() {
if (archiver == null) {
Set<AbstractName> archivers = kernel.listGBeans(new AbstractNameQuery(ServerArchiver.class.getName()));
if (archivers.size() == 0) {
throw new IllegalStateException("No plugin installer registered");
}
try {
archiver = (ServerArchiver) kernel.getGBean(archivers.iterator().next());
} catch (GBeanNotFoundException e) {
throw new IllegalStateException("Plugin installer cannot be retrieved from kernel");
}
}
return archiver;
}
public List<PluginRepositoryList> getPluginRepositoryLists() {
if (this.pluginRepositoryLists == null) {
Set<AbstractName> names = kernel.listGBeans(new AbstractNameQuery(PluginRepositoryList.class.getName()));
List<PluginRepositoryList> pluginRepositoryLists = new ArrayList<PluginRepositoryList>(names.size());
for (AbstractName name : names) {
try {
pluginRepositoryLists.add((PluginRepositoryList) kernel.getGBean(name));
} catch (GBeanNotFoundException e) {
//ignore?
}
}
this.pluginRepositoryLists = pluginRepositoryLists;
}
return this.pluginRepositoryLists;
}
public DeploymentManager getDeploymentManager() {
DeploymentFactory factory = new DeploymentFactoryWithKernel(kernel);
try {
return factory.getDeploymentManager("deployer:geronimo:inVM", null, null);
} catch (DeploymentManagerCreationException e) {
// log.error(e.getMessage(), e);
return null;
}
}
public List<String> getApplicationModuleLists() {
List<String> apps = new ArrayList<String>();
Set<AbstractName> gbeans = this.kernel.listGBeans((AbstractNameQuery) null);
for (Iterator<AbstractName> it = gbeans.iterator(); it.hasNext();) {
AbstractName name = (AbstractName) it.next();
if (isApplicationModule(name)) {
apps.add(name.getNameProperty("name"));
}
}
return apps;
}
private static boolean isApplicationModule(AbstractName abstractName) {
String type = abstractName.getNameProperty("j2eeType");
String app = abstractName.getNameProperty("J2EEApplication");
String name = abstractName.getNameProperty("name");
if (type != null) {
return (type.equals("WebModule") || type.equals("J2EEApplication") || type.equals("EJBModule") || type.equals("AppClientModule") || type.equals("ResourceAdapterModule")) && !name.startsWith("geronimo/system");
}
return false;
}
}
| 41.375 | 222 | 0.683415 |
9f30bd29cd16000b5c8685764e0f804d42f62599 | 4,139 | package com.wavefront.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.wavefront.helpers.ApplicationConfigValidator;
import java.util.ArrayList;
import java.util.List;
/**
* Application configuration object for setting sender related information.
*
* @author Sirak Ghazaryan (sghazaryan@vmware.com)
*/
@JsonDeserialize(converter = ApplicationConfigValidator.class)
public class ApplicationConfig {
/**
* Input file name for parse Wavefront traces from file and re-ingest them.
*/
@JsonProperty
private String wfTracesFile;
/**
* Number of times the program should execute.
*/
@JsonProperty
private String cycle = "1";
/**
* Output file name for exporting the plain list of spans. Saving to file has the highest
* priority.
*/
@JsonProperty
private String spanOutputFile = null;
/**
* Output file name for exporting consistent traces. Saving to file has the highest priority.
*/
@JsonProperty
private String traceOutputFile = null;
/**
* Pattern/topology Trace Type files
*/
@JsonProperty
private List<String> inputJsonFiles = new ArrayList<>();
/**
* Proxy server for routing traffic to wavefront. If it's set, the direct ingestion configs will
* be ignored.
*/
@JsonProperty
private String proxyServer = null;
/**
* Metrics port.
*/
@JsonProperty
private Integer metricsPort = 2878;
/**
* Port used for distribution.
*/
@JsonProperty
private Integer distributionPort = 40000;
/**
* Port used for tracing.
*/
@JsonProperty
private Integer tracingPort = 30000;
/**
* Port used for additional tracing data.
*/
@JsonProperty
private Integer customTracingPorts = 30001;
/**
* Server URL used for direct ingestion.
*/
@JsonProperty
private String server = null;
/**
* Token to auto-register proxy with an account, used for direct ingestion only.
*/
@JsonProperty
private String token = null;
/**
* Server URL used for sending statistics. If not specified, will be sent to the same address
* as the traces.
*/
@JsonProperty
private String statServer = null;
/**
* Token for the statistics server.
*/
@JsonProperty
private String statToken = null;
/**
* Token for the statistics server.
*/
@JsonProperty
private boolean reportStat = false;
public String getWfTracesFile() {
return wfTracesFile;
}
public String getCycle() {
return cycle;
}
public void setCycle(String cycle) {
this.cycle = cycle;
}
public String getSpanOutputFile() {
return spanOutputFile;
}
public String getTraceOutputFile() {
return traceOutputFile;
}
public String getServer() {
return server;
}
public String getToken() {
return token;
}
public String getProxyServer() { return proxyServer; }
public List<String> getInputJsonFiles() { return inputJsonFiles; }
public Integer getMetricsPort() {
return metricsPort;
}
public Integer getDistributionPort() {
return distributionPort;
}
public Integer getTracingPort() {
return tracingPort;
}
public Integer getCustomTracingPorts() {
return customTracingPorts;
}
public String getStatServer() { return statServer; }
public String getStatToken() { return statToken; }
public boolean getReportStat(){ return reportStat; }
@Override
public String toString() {
return "ApplicationConfig{" +
"wfTracesFile='" + wfTracesFile + '\'' +
", spanOutputFile='" + spanOutputFile + '\'' +
", traceOutputFile='" + traceOutputFile + '\'' +
", inputJsonFiles=" + inputJsonFiles +
", proxyServer='" + proxyServer + '\'' +
", metricsPort=" + metricsPort +
", distributionPort=" + distributionPort +
", tracingPort=" + tracingPort +
", customTracingPorts=" + customTracingPorts +
", server='" + server + '\'' +
", token='" + token + '\'' +
", statServer='" + statServer + '\'' +
", statToken='" + statToken + '\'' +
'}';
}
} | 24.491124 | 98 | 0.666345 |
2d57db181bd50e2a44a20bf67a78674e0d1bcd9c | 3,037 | /*
* 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.facebook.presto.druid;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import static java.util.Objects.requireNonNull;
public abstract class DruidAggregationColumnNode
{
private final ExpressionType expressionType;
private final VariableReferenceExpression outputColumn;
public DruidAggregationColumnNode(ExpressionType expressionType, VariableReferenceExpression outputColumn)
{
this.expressionType = requireNonNull(expressionType, "expressionType is null");
this.outputColumn = requireNonNull(outputColumn, "outputColumn is null");
}
public VariableReferenceExpression getOutputColumn()
{
return outputColumn;
}
public ExpressionType getExpressionType()
{
return expressionType;
}
public enum ExpressionType
{
GROUP_BY,
AGGREGATE,
}
public static class GroupByColumnNode
extends DruidAggregationColumnNode
{
private final VariableReferenceExpression inputColumn;
public GroupByColumnNode(VariableReferenceExpression inputColumn, VariableReferenceExpression output)
{
super(ExpressionType.GROUP_BY, output);
this.inputColumn = requireNonNull(inputColumn, "inputColumn is null");
}
public VariableReferenceExpression getInputColumn()
{
return inputColumn;
}
@Override
public String toString()
{
return inputColumn.toString();
}
}
public static class AggregationFunctionColumnNode
extends DruidAggregationColumnNode
{
private final CallExpression callExpression;
private final String alias;
public AggregationFunctionColumnNode(VariableReferenceExpression output, CallExpression callExpression, String alias)
{
super(ExpressionType.AGGREGATE, output);
this.callExpression = requireNonNull(callExpression, "callExpression is null");
this.alias = requireNonNull(alias, "alias is null");
}
public CallExpression getCallExpression()
{
return callExpression;
}
public String getAlias()
{
return alias;
}
@Override
public String toString()
{
return callExpression.toString() + ", " + alias;
}
}
}
| 30.069307 | 125 | 0.68324 |
80145d4397eeedfe49917eb2f43a31d86cce30a2 | 3,131 | package com.itcast.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.itcast.entity.Result;
import com.itcast.mapper.MemberMapper;
import com.itcast.mapper.OrderMapper;
import com.itcast.service.ReportService;
import com.itcast.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author :yh
* @version :
* @date :Created in 2019/10/21 9:38
* @description :
*/
@Service(interfaceClass = ReportService.class)
@Transactional
public class ReportServiceImpl implements ReportService {
@Autowired
private MemberMapper memberMapper;
@Autowired
private OrderMapper orderMapper;
/**
* 获取运营统计数据
* @return
*/
@Override
public Map<String, Object> getBusinessReport() throws Exception {
String today = DateUtils.parseDate2String(DateUtils.getToday());
//当前星期第一天
String monday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday());
//当前月第一天
String firstDayOfMonth = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());
//今日新增会员
Integer todayNewMember = memberMapper.findCountThisDate(today);
//本周新增会员
Integer thisWeekNewMember = memberMapper.findCountAfterDate(monday);
//本月新增会员
Integer thisMonthNewMember = memberMapper.findCountAfterDate(firstDayOfMonth);
//会员总数
Integer totalMember = memberMapper.findAllCount();
//今天预约数
Integer todayOrderNumber = orderMapper.findCountThisDate(today);
//本周预约数
Integer thisWeekOrderNumber = orderMapper.findCountAfterDate(monday);
//本月预约数
Integer thisMonthOrderNumber = orderMapper.findCountAfterDate(firstDayOfMonth);
//今日到诊数
Integer todayVisitsNumber = orderMapper.findVisitedCountByDate(today);
//本周到诊数
Integer thisWeekVisitsNumber = orderMapper.findVisitedCountAfterDate(monday);
//本月到诊数
Integer thisMonthVisitsNumber = orderMapper.findVisitedCountAfterDate(firstDayOfMonth);
//套餐信息
List<Map> hotSetMeal = orderMapper.findHotSetMeal();
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("reportDate",today);
resultMap.put("todayNewMember",todayNewMember);
resultMap.put("thisWeekNewMember",thisWeekNewMember);
resultMap.put("thisMonthNewMember",thisMonthNewMember);
resultMap.put("totalMember",totalMember);
resultMap.put("todayOrderNumber",todayOrderNumber);
resultMap.put("thisWeekOrderNumber",thisWeekOrderNumber);
resultMap.put("thisMonthOrderNumber",thisMonthOrderNumber);
resultMap.put("todayVisitsNumber",todayVisitsNumber);
resultMap.put("thisWeekVisitsNumber",thisWeekVisitsNumber);
resultMap.put("thisMonthVisitsNumber",thisMonthVisitsNumber);
resultMap.put("hotSetmeal",hotSetMeal);
return resultMap;
}
}
| 31.94898 | 95 | 0.721495 |
5297f5bf6c8f3235f6c08348f4235798816b836e | 1,148 | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.palava.ipc;
import java.io.Serializable;
import java.util.Map;
/**
* Will be triggered as soon as a session will be resumed.
*
* @author Tobias Sarnowski
*/
public interface IpcSessionResumeEvent {
/**
* Allows to hook into session resuming process to
* restore specific elements.
*
* @param session the session which will be resumed
* @param data the deserialized context information
*/
void eventIpcSessionResume(IpcSession session, Map<String, ? extends Serializable> data);
}
| 29.435897 | 93 | 0.722997 |
fd6f448b032382298bf89fcdf9080163ce0c8ee1 | 910 | package com.cy.onepush.common.exception;
/**
* abstract application runtime exception
*
* @author WhatAKitty
* @date 2020-12-12
* @since 0.1.0
*/
public class AbstractAppRuntimeException extends RuntimeException {
public AbstractAppRuntimeException() {
super();
}
public AbstractAppRuntimeException(String message, Object... params) {
super(String.format(message, params));
}
public AbstractAppRuntimeException(String message, Throwable cause, Object... params) {
super(String.format(message, params), cause);
}
public AbstractAppRuntimeException(Throwable cause) {
super(cause);
}
protected AbstractAppRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object... params) {
super(String.format(message, params), cause, enableSuppression, writableStackTrace);
}
}
| 27.575758 | 149 | 0.714286 |
e82ab8da2058e140a3605157a2f76f98c95c4a5a | 756 | package qunar.tc.qconfig.admin.service;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import qunar.tc.qconfig.admin.dto.CandidateDTO;
import java.util.List;
import java.util.Map;
/**
* @author zhenyu.nie created on 2016 2016/3/2 16:26
*/
public interface FileDescriptionService {
String getDescription(String group, String dataId);
void batchSetDescription(List<CandidateDTO> candidateDTOList, boolean skipEmptyDesc);
void setDescription(String group, String dataId, String description);
//dataId-description
Map<String, String> getDescriptions(String group);
// group-dataId-description
Table<String, String, String> getDescriptions(Multimap<String, String> groupDataIdMappings);
}
| 30.24 | 96 | 0.77381 |
4ded66893ce0eb5fc46b658bbcfe4f3c1d82e6cc | 955 | package com.byteowls.vaadin.selectize.config.options;
import com.byteowls.vaadin.selectize.config.annotation.SelectizeOptionLabel;
import com.byteowls.vaadin.selectize.config.annotation.SelectizeOptionSearch;
import com.byteowls.vaadin.selectize.config.annotation.SelectizeOptionValue;
public class BasicOption {
@SelectizeOptionValue
private Object value;
@SelectizeOptionLabel
@SelectizeOptionSearch
private String text;
public BasicOption(Object value, String text) {
this.value = value;
this.text = text;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "BasicOption [value=" + value + ", text=" + text + "]";
}
}
| 22.738095 | 77 | 0.668063 |
7ab4fc40459d0cde4930493e44b3e6d3eea30c90 | 769 | class ExceptionOne {
static void validAge(int age) throws MyException { // We need to declare the exception; that the method may throw.
if (age < 18) {
throw new MyException("You should be 18+ to cast vote.");
} else {
System.out.println("You can vote.");
}
}
public static void main(String[] args) {
// If we don't catch the exception : error: unreported exception MyException;
// must be caught or declared to be thrown.
// So we are calling the function under try catch block.
try {
validAge(19); // During call of the method, programmer must use try catch mechanism.
} catch (MyException error) {
error.printStackTrace();
}
}
} | 36.619048 | 118 | 0.596879 |
c86ea98dcfe413e880959ef36bd99d5687012109 | 2,220 |
package com.compositesw.services.system.admin.server;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.compositesw.services.system.util.common.BaseRequest;
/**
* <p>Java class for removeFromClusterRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="removeFromClusterRequest">
* <complexContent>
* <extension base="{http://www.compositesw.com/services/system/util/common}baseRequest">
* <sequence>
* <element name="remoteHostName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="remotePort" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "removeFromClusterRequest", propOrder = {
"remoteHostName",
"remotePort"
})
public class RemoveFromClusterRequest
extends BaseRequest
{
protected String remoteHostName;
protected Integer remotePort;
/**
* Gets the value of the remoteHostName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemoteHostName() {
return remoteHostName;
}
/**
* Sets the value of the remoteHostName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemoteHostName(String value) {
this.remoteHostName = value;
}
/**
* Gets the value of the remotePort property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getRemotePort() {
return remotePort;
}
/**
* Sets the value of the remotePort property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setRemotePort(Integer value) {
this.remotePort = value;
}
}
| 24.395604 | 108 | 0.61982 |
945cd79e68edab8bec57f76b517a62c9313c717a | 3,086 | package de.metas.banking.payment.paymentallocation.model;
/*
* #%L
* de.metas.banking.swingui
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.math.BigDecimal;
import java.util.Date;
import org.compiere.swing.table.ColumnInfo;
import org.compiere.swing.table.TableInfo;
import de.metas.banking.payment.paymentallocation.service.IPaymentDocument;
@TableInfo(defaultHideAll = true)
public interface IPaymentRow extends IAllocableDocRow
{
//@formatter:off
@ColumnInfo(columnName = PROPERTY_Selected, seqNo = 10, displayName=" ", translate = false, selectionColumn = true)
@Override
boolean isSelected();
@Override
void setSelected(boolean selected);
@ColumnInfo(columnName = "C_DocType_ID", seqNo = 20)
String getDocTypeName();
@Override
@ColumnInfo(columnName = "DocumentNo", seqNo = 30)
String getDocumentNo();
@ColumnInfo(columnName = "C_BPartner_ID", seqNo = 40)
String getBPartnerName();
@ColumnInfo(columnName = "DocumentDate", seqNo = 50)
@Override
Date getDocumentDate();
String PROPERTY_DocumentCurrency = "DocumentCurrency";
@ColumnInfo(columnName = PROPERTY_DocumentCurrency, seqNo = 60)
String getCurrencyISOCodeAsString();
@ColumnInfo(columnName = "OriginalAmt", seqNo = 70)
BigDecimal getPayAmt();
String PROPERTY_ConvertedAmt = "ConvertedAmt";
@ColumnInfo(columnName = PROPERTY_ConvertedAmt, seqNo = 80)
BigDecimal getPayAmtConv();
@ColumnInfo(columnName = "OpenAmt", seqNo = 90)
@Override
BigDecimal getOpenAmtConv();
String PROPERTY_DiscountAmt = "DiscountAmt";
@ColumnInfo(columnName = PROPERTY_DiscountAmt, seqNo = 100)
BigDecimal getDiscountAmt();
void setDiscountAmt(BigDecimal discountAmt);
@ColumnInfo(columnName = "AppliedAmt", seqNo = 130)
@Override
BigDecimal getAppliedAmt();
@Override
void setAppliedAmt(BigDecimal appliedAmt);
//@formatter:on
int getC_Payment_ID();
IPaymentDocument copyAsPaymentDocument();
/**
* Reset discount amount
*/
void resetDiscountAmount();
/**
* Sets the discount amount and then updates the AppliedAmt
*
* @param context
* @param discountAmt
*/
void setDiscountManual(PaymentAllocationContext context, BigDecimal discountAmt);
/**
* <ul>
* <li>Set DiscountAmt=0 if it does not apply anymore
* <li>update AppliedAmt=Open-Discount if discount applies.
* </ul>
*
* @param context
*/
void recalculateDiscountAmount(PaymentAllocationContext context);
}
| 27.309735 | 116 | 0.747894 |
9a15f303dd03e104ef4989f27df34c58303e22ac | 4,089 | package egovframework.com.god.codegen.oracle.alltabcols.service.impl;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import egovframework.com.cmm.ComDefaultCodeVO;
import egovframework.com.cmm.service.CmmnDetailCode;
import egovframework.com.cmm.service.impl.CmmUseDAO;
import egovframework.rte.psl.dataaccess.util.EgovMap;
import god.codegen.oracle.alltabcols.service.AllTabColsVO;
import god.codegen.oracle.alltabcols.service.impl.AllTabColsDAO;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AllTabColsDAOTest_selectList.class })
@ActiveProfiles({ "oracle", "dummy" })
@Configuration
//@ImportResource({ "classpath*:/egovframework/spring/com/test-context-dao.xml" })
@ImportResource({ "classpath*:/egovframework/spring/com/context-crypto.xml",
"classpath*:/egovframework/spring/com/context-datasource.xml",
"classpath*:/egovframework/spring/com/context-mapper.xml",
"classpath*:/egovframework/spring/com/context-mapper-god-oracle.xml",
"classpath*:/egovframework/spring/com/test-context-common.xml" })
@ComponentScan(useDefaultFilters = false, basePackages = { "god.codegen.oracle.alltabcols.service.impl",
"egovframework.com.cmm.service.impl" }, includeFilters = {
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { AllTabColsDAO.class, CmmUseDAO.class }) })
public class AllTabColsDAOTest_selectList {
@Autowired
ApplicationContext context;
@Autowired
AllTabColsDAO dao;
@Autowired
CmmUseDAO cmmUseDAO;
@Before
public void setUp() throws Exception {
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
log.debug("beanDefinitionName={}", beanDefinitionName);
}
}
@Test
public void test() throws Exception {
log.debug("test");
// given
AllTabColsVO vo = new AllTabColsVO();
vo.setOwner("COM");
// when
List<EgovMap> results = dao.selectList(vo);
// then
assertEquals(results.get(0).get("owner"), vo.getOwner());
log.debug("results={}", results);
results.forEach(result -> {
log.debug("result={}", result);
log.debug("owner={}", result.get("owner"));
log.debug("tableName={}", result.get("tableName"));
log.debug("columnName={}", result.get("columnName"));
log.debug("dataType={}", result.get("dataType"));
log.debug("dataLength={}", result.get("dataLength"));
log.debug("dataPrecision={}", result.get("dataPrecision"));
log.debug("dataScale={}", result.get("dataScale"));
log.debug("nullable={}", result.get("nullable"));
log.debug("columnId={}", result.get("columnId"));
log.debug("dataDefault={}", result.get("dataDefault"));
log.debug("columnComments={}", result.get("columnComments"));
});
}
@Test
public void test2() throws Exception {
log.debug("test2");
// given
ComDefaultCodeVO vo = new ComDefaultCodeVO();
vo.setCodeId("COM001");
// when
List<CmmnDetailCode> results = cmmUseDAO.selectCmmCodeDetail(vo);
// then
assertEquals(results.get(0).getCodeId(), vo.getCodeId());
log.debug("results={}", results);
results.forEach(result -> {
log.debug("result={}", result);
log.debug("getCodeId={}", result.getCodeId());
log.debug("getCode={}", result.getCode());
log.debug("getCodeNm={}", result.getCodeNm());
log.debug("getCodeDc={}", result.getCodeDc());
});
}
}
| 32.975806 | 104 | 0.744436 |
d571d3fe560e02486ae870ee5c267a380c63b480 | 15,517 | // Copyright (c) 2016 FUKUI Association of information & system industry. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package net.e_fas.oss.tabijiman;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TakePicture extends Activity implements SurfaceHolder.Callback {
//サーフェイスをコントロールするholderオブジェクト
static SurfaceHolder holder;
//カメラオブジェクトの取得
static Camera camera;
static ImageButton shutterButton;
static ImageButton selectFrame;
static HorizontalScrollView FrameSelectView;
static LinearLayout ScrollViewLinear;
static LinearLayout FrameViewLinear;
static RelativeLayout FrameViewRelative;
static ImageButton FramePreview;
static ImageView FrameView;
static SurfaceView PreviewView;
static SQLiteHelper helper;
static SQLiteDatabase db;
public static void e_print(Object object) {
Log.e("d_tabiziman", object.toString());
}
//YUVをBitmapに変換する関数
public static Bitmap getBitmapImageFromYUV(byte[] data, int width, int height) {
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
byte[] jdata = baos.toByteArray();
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeByteArray(jdata, 0, jdata.length, bitmapFatoryOptions);
}
// Frame_Initializer
public void Frame_initialize() {
FrameView = (ImageView) findViewById(R.id.FrameView);
FrameViewLinear = (LinearLayout) findViewById(R.id.FrameViewLinear);
FrameViewRelative = (RelativeLayout) findViewById(R.id.FrameViewRelative);
FrameSelectView = (HorizontalScrollView) findViewById(R.id.FrameSelectView);
ScrollViewLinear = (LinearLayout) findViewById(R.id.ScrollViewLinear);
PreviewView = (SurfaceView) findViewById(R.id.PreviewView);
ScrollViewLinear.removeAllViews();
helper = new SQLiteHelper(this);
db = helper.getWritableDatabase();
List<String> NameList = AppSetting.GetFileNames();
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, LinearLayout.LayoutParams.MATCH_PARENT);
for (int i = 0; i < AppSetting.initFrameName.length; i++) {
FrameViewLinear = new LinearLayout(this);
FrameViewLinear.setBackground(null);
FramePreview = new ImageButton(this);
try {
InputStream is = getResources().getAssets().open(AppSetting.initFrameName[i]);
final Bitmap bm = BitmapFactory.decodeStream(is);
FramePreview.setImageBitmap(bm);
FramePreview.setBackground(null);
FramePreview.setScaleType(ImageView.ScaleType.FIT_CENTER);
FramePreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shutterButton.setActivated(true);
FrameView.setImageBitmap(bm);
FrameView.setScaleType(ImageView.ScaleType.FIT_CENTER);
FrameView.setAlpha(0.8f);
}
});
} catch (IOException e) { /* 例外処理 */
e.printStackTrace();
}
FrameViewLinear.addView(FramePreview, params);
ScrollViewLinear.addView(FrameViewLinear);
}
for (String name : NameList) {
e_print("name >> " + name);
FrameViewLinear = new LinearLayout(this);
FrameViewLinear.setBackground(null);
FramePreview = new ImageButton(this);
try {
final Bitmap temp = AppSetting.loadBitmapSDCard(name);
FramePreview.setImageBitmap(temp);
FramePreview.setBackground(null);
FramePreview.setScaleType(ImageView.ScaleType.FIT_CENTER);
FramePreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shutterButton.setActivated(true);
FrameView.setImageBitmap(temp);
FrameView.setScaleType(ImageView.ScaleType.FIT_CENTER);
FrameView.setAlpha(0.8f);
}
});
} catch (IOException e) {
e.printStackTrace();
}
FrameViewLinear.addView(FramePreview, params);
ScrollViewLinear.addView(FrameViewLinear);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_picture);
Frame_initialize();
shutterButton = (ImageButton) findViewById(R.id.Shutter);
shutterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.isActivated()) {
e_print("shutter >> enable");
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
camera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
//プレビューのフォーマットはYUVなので、YUVをBmpに変換する
int w = camera.getParameters().getPreviewSize().width;
int h = camera.getParameters().getPreviewSize().height;
//切り取った画像を保存
Bitmap bmp = getBitmapImageFromYUV(data, w, h);
//回転
Matrix m = new Matrix();
m.setRotate(90);
//保存用 bitmap生成
Bitmap rotated_bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
Bitmap result_bmp = captureScreen(rotated_bmp);
String imageName = "temp.png";
File imageFile = new File(getFilesDir(), imageName);
FileOutputStream out;
try {
out = new FileOutputStream(imageFile);
result_bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
///画像をアプリの内部領域に保存
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Intent SaveShareView = new Intent(getApplicationContext(), SaveShareView.class);
SaveShareView.putExtra("PictureData", imageFile.getAbsolutePath());
startActivity(SaveShareView);
}
});
}
});
} else {
e_print("shutter >> disable");
}
}
});
selectFrame = (ImageButton) findViewById(R.id.SelectFrame);
selectFrame.setActivated(true);
selectFrame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.isActivated()) {
FrameSelectView.setVisibility(View.INVISIBLE);
v.setActivated(false);
} else {
FrameSelectView.setVisibility(View.VISIBLE);
v.setActivated(true);
}
}
});
//SurfaceViewからholderオブジェクトを取得
SurfaceView s = (SurfaceView) findViewById(R.id.PreviewView);
s.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
});
holder = s.getHolder();
holder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
//カメラリソースの取得
camera = Camera.open();
camera.setDisplayOrientation(90);
if (camera != null) {
try {
//SurfaceViewをプレビューディスプレイとして設定
camera.setPreviewDisplay(holder);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
params.setPreviewSize(sizes.get(0).width, sizes.get(0).height);
camera.setParameters(params);
if (camera != null) {
camera.startPreview();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
//プレビューの停止
camera.stopPreview();
//カメラ解放
camera.release();
camera = null;
}
}
private Bitmap captureScreen(Bitmap bitmap) {
// フォトフレーム部のキャプチャ取得
FrameView.setDrawingCacheEnabled(false);
FrameView.setDrawingCacheEnabled(true);
Bitmap Frame = ((BitmapDrawable) FrameView.getDrawable()).getBitmap();
Rect previewview = new Rect();
PreviewView.getDrawingRect(previewview);
Rect frameview = new Rect();
FrameView.getDrawingRect(frameview);
Rect tabbar = new Rect();
findViewById(R.id.Tabbar).getDrawingRect(tabbar);
// カメラとフレーム(オーバレイ)を重ねる
Bitmap temp = Bitmap.createBitmap(
bitmap.getWidth(),
bitmap.getHeight() - tabbar.height(),
Bitmap.Config.ARGB_8888);
// "offBitmap"が2つを張り合わせたBitmap(キャプチャ画像)となります。
Canvas C_temp = new Canvas(temp);
Rect temp_Rect = new Rect(
0,
0,
bitmap.getWidth(),
bitmap.getHeight() - tabbar.height()
);
C_temp.drawBitmap(bitmap, temp_Rect, temp_Rect, null);
bitmap = temp;
new PictureUtil();
// カメラとフレーム(オーバレイ)を重ねる
Bitmap offBitmap = Bitmap.createBitmap(
Frame.getWidth(),
Frame.getHeight(),
Bitmap.Config.ARGB_8888);
// "offBitmap"が2つを張り合わせたBitmap(キャプチャ画像)となります。
Canvas offScreen = new Canvas(offBitmap);
float scale;
float[] f_Matrix = new float[9];
TakePicture.FrameView.getImageMatrix().getValues(f_Matrix);
Matrix matrix = TakePicture.FrameView.getImageMatrix();
if (f_Matrix[Matrix.MTRANS_Y] == 0) {
scale = PictureUtil.getInitialScale(bitmap, offScreen)[1];
e_print("scale based on Height");
} else {
scale = PictureUtil.getInitialScale(bitmap, offScreen)[0];
e_print("scale based on Width");
}
matrix.postScale(scale, scale);
TakePicture.FrameView.setImageMatrix(matrix);
TakePicture.FrameView.getImageMatrix().getValues(f_Matrix);
e_print("Frame_Bitmap >> width:: " + Frame.getWidth() + " height:: " + Frame.getHeight());
e_print("bitmap_Size >> width:: " + bitmap.getWidth() + " height:: " + bitmap.getHeight());
e_print("scale >> " + scale);
e_print("matrix_X >> " + f_Matrix[Matrix.MTRANS_X] + " matrix_Y >> " + f_Matrix[Matrix.MTRANS_Y]);
e_print("matrix_X_scale >> " + f_Matrix[Matrix.MSCALE_X] + " matrix_Y_scale >> " + f_Matrix[Matrix.MSCALE_Y]);
e_print("matrix_X / scale >> " + f_Matrix[Matrix.MTRANS_X] / scale + " matrix_Y / scale >> " + f_Matrix[Matrix.MTRANS_Y] / scale);
float zureX = f_Matrix[Matrix.MTRANS_X] / f_Matrix[Matrix.MSCALE_X];
float zureY = f_Matrix[Matrix.MTRANS_Y] / f_Matrix[Matrix.MSCALE_Y];
e_print("zureX >> " + zureX + " zureY >> " + zureY);
float frameX = zureX * scale;
float frameY = zureY * scale;
e_print("frameX >> " + frameX + " frameY >> " + frameY);
Rect srcRect = new Rect(
(int) frameX,
(int) frameY,
bitmap.getWidth() - (int) frameX,
bitmap.getHeight() - (int) frameY
);
Rect dstRect = new Rect(
0,
0,
Frame.getWidth(),
Frame.getHeight()
);
e_print("srcRect >> " + srcRect + " dstRect >> " + dstRect);
offScreen.drawBitmap(bitmap, srcRect, dstRect, null);
offScreen.drawBitmap(Frame, dstRect, dstRect, null);
return offBitmap;
}
} | 36.170163 | 138 | 0.583747 |
214ce0face325109e45da84d19e04627271845d0 | 13,058 | package org.opensrp.web.controller;
import static ch.lambdaj.collection.LambdaCollections.with;
import static java.text.MessageFormat.format;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.http.HttpStatus.OK;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.opensrp.api.domain.Client;
import org.opensrp.api.domain.Event;
import org.opensrp.connector.OpenmrsConnector;
import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold;
import org.opensrp.connector.openmrs.constants.OpenmrsConstants.Person;
import org.opensrp.connector.openmrs.service.EncounterService;
import org.opensrp.connector.openmrs.service.HouseholdService;
import org.opensrp.connector.openmrs.service.OpenmrsUserService;
import org.opensrp.connector.openmrs.service.PatientService;
import org.opensrp.domain.Multimedia;
import org.opensrp.dto.form.FormSubmissionDTO;
import org.opensrp.dto.form.MultimediaDTO;
import org.opensrp.form.domain.FormSubmission;
import org.opensrp.form.service.FormSubmissionConverter;
import org.opensrp.form.service.FormSubmissionService;
import org.opensrp.register.mcare.OpenSRPScheduleConstants.OpenSRPEvent;
import org.opensrp.register.mcare.service.HHService;
import org.opensrp.repository.MultimediaRepository;
import org.opensrp.scheduler.SystemEvent;
import org.opensrp.scheduler.TaskSchedulerService;
import org.opensrp.service.MultimediaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import ch.lambdaj.function.convert.Converter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@Controller
public class FormSubmissionController {
private static Logger logger = LoggerFactory.getLogger(FormSubmissionController.class.toString());
private FormSubmissionService formSubmissionService;
private TaskSchedulerService scheduler;
private EncounterService encounterService;
private OpenmrsConnector openmrsConnector;
private PatientService patientService;
private HouseholdService householdService;
private HHService hhService;
private OpenmrsUserService openmrsUserService;
private MultimediaService multimediaService;
private MultimediaRepository multimediaRepository;
@Autowired
public FormSubmissionController(FormSubmissionService formSubmissionService, TaskSchedulerService scheduler,
EncounterService encounterService, OpenmrsConnector openmrsConnector, PatientService patientService,
HouseholdService householdService, MultimediaService multimediaService, OpenmrsUserService openmrsUserService,
MultimediaRepository multimediaRepository) {
this.formSubmissionService = formSubmissionService;
this.scheduler = scheduler;
this.encounterService = encounterService;
this.openmrsConnector = openmrsConnector;
this.patientService = patientService;
this.householdService = householdService;
this.hhService = hhService;
this.openmrsUserService = openmrsUserService;
this.multimediaService = multimediaService;
this.multimediaRepository = multimediaRepository;
}
@RequestMapping(method = GET, value = "/form-submissions")
@ResponseBody
private List<FormSubmissionDTO> getNewSubmissionsForANM(@RequestParam("anm-id") String anmIdentifier,
@RequestParam("timestamp") Long timeStamp,
@RequestParam(value = "batch-size", required = false)
Integer batchSize) {
List<FormSubmission> newSubmissionsForANM = formSubmissionService
.getNewSubmissionsForANM(anmIdentifier, timeStamp, batchSize);
return with(newSubmissionsForANM).convert(new Converter<FormSubmission, FormSubmissionDTO>() {
@Override
public FormSubmissionDTO convert(FormSubmission submission) {
return FormSubmissionConverter.from(submission);
}
});
}
@RequestMapping(method = GET, value="/all-form-submissions")
@ResponseBody
private List<FormSubmissionDTO> getAllFormSubmissions(@RequestParam("timestamp") Long timeStamp,
@RequestParam(value = "batch-size", required = false)
Integer batchSize) {
List<FormSubmission> allSubmissions = formSubmissionService
.getAllSubmissions(timeStamp, batchSize);
return with(allSubmissions).convert(new Converter<FormSubmission, FormSubmissionDTO>() {
@Override
public FormSubmissionDTO convert(FormSubmission submission) {
return FormSubmissionConverter.from(submission);
}
});
}
@RequestMapping(headers = {"Accept=application/json"}, method = POST, value = "/form-submissions")
public ResponseEntity<HttpStatus> submitForms(@RequestBody List<FormSubmissionDTO> formSubmissionsDTO) {
try {
if (formSubmissionsDTO.isEmpty()) {
return new ResponseEntity<>(BAD_REQUEST);
}
scheduler.notifyEvent(new SystemEvent<>(OpenSRPEvent.FORM_SUBMISSION, formSubmissionsDTO));
try{
////////TODO MAIMOONA : SHOULD BE IN EVENT but event needs to be moved to web so for now kept here
String json = new Gson().toJson(formSubmissionsDTO);
System.out.println("MMMMMMMMMMMYYYYYYYYYYYYYY::"+json);
List<FormSubmissionDTO> formSubmissions = new Gson().fromJson(json, new TypeToken<List<FormSubmissionDTO>>() {
}.getType());
List<FormSubmission> fsl = with(formSubmissions).convert(new Converter<FormSubmissionDTO, FormSubmission>() {
@Override
public FormSubmission convert(FormSubmissionDTO submission) {
return FormSubmissionConverter.toFormSubmission(submission);
}
});
for (FormSubmission formSubmission : fsl) {
if(openmrsConnector.isOpenmrsForm(formSubmission)){
System.out.println("Sending data to openMRS/***********************************************************************/");
JSONObject p = patientService.getPatientByIdentifier(formSubmission.entityId());
JSONObject r = patientService.getPatientByIdentifier(formSubmission.getField("relationalid"));
//System.out.println("Existing patient found into openMRS with relationalid : " + q);
if(p != null || r != null){ // HO
System.out.println("Existing patient found into openMRS with id : " + p==null?formSubmission.getField("relationalid"):formSubmission.entityId() + "/***********************************************************************/");
Event e;
Map<String, Map<String, Object>> dep;
dep = openmrsConnector.getDependentClientsFromFormSubmission(formSubmission);
if(dep.size()>0){ //HOW(n)
System.out.println("Dependent client exist into formsubmission /***********************************************************************/ ");
for (Map<String, Object> cm : dep.values()) {
System.out.println(patientService.createPatient((Client)cm.get("client")));
System.out.println(encounterService.createEncounter((Event)cm.get("event")));
}
}
//HOW(0)
e = openmrsConnector.getEventFromFormSubmission(formSubmission);
System.out.println("Creates encounter for client id: " + e.getBaseEntityId());
System.out.println(encounterService.createEncounter(e));
}
else { //Hn
Map<String, Map<String, Object>> dep;
dep = openmrsConnector.getDependentClientsFromFormSubmission(formSubmission);
if(dep.size()>0){ //HnW(n)
System.out.println("Dependent client exist into formsubmission /***********************************************************************/ ");
Client hhhClient = openmrsConnector.getClientFromFormSubmission(formSubmission);
Event hhhEvent = openmrsConnector.getEventFromFormSubmission(formSubmission);
OpenmrsHouseHold hh = new OpenmrsHouseHold(hhhClient, hhhEvent);
for (Map<String, Object> cm : dep.values()) {
hh.addHHMember((Client)cm.get("client"), (Event)cm.get("event"));
}
householdService.saveHH(hh);
}
else {//HnW(0)
System.out.println("Patient and Dependent client not exist into openmrs /***********************************************************************/ ");
Client c = openmrsConnector.getClientFromFormSubmission(formSubmission);
System.out.println(patientService.createPatient(c));
Event e = openmrsConnector.getEventFromFormSubmission(formSubmission);
System.out.println(encounterService.createEncounter(e));
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
logger.debug(format("Added Form submissions to queue.\nSubmissions: {0}", formSubmissionsDTO));
}
catch (Exception e) {
logger.error(format("Form submissions processing failed with exception {0}.\nSubmissions: {1}", e, formSubmissionsDTO));
return new ResponseEntity<>(INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(CREATED);
}
@RequestMapping(method = GET, value = "/entity-id")
@ResponseBody
public ResponseEntity<String> getEntityIdForBRN(@RequestParam("brn-id") List<String> brnIdList)
{
return new ResponseEntity<>(new Gson().toJson(hhService.getEntityIdBybrnId(brnIdList)),OK);
}
@RequestMapping(method = GET, value = "/user-location")
@ResponseBody
public ResponseEntity<String> getUserByLocation(@RequestParam("location-name") String locationName)
{
JSONObject usersAssignedToLocation=null;
String userName = "";
try {
usersAssignedToLocation = openmrsUserService.getTeamMemberByLocation(locationName);
userName = usersAssignedToLocation.getJSONArray("results").getJSONObject(0).getJSONObject("user").getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ResponseEntity<>(userName, OK);
}
@RequestMapping(headers = {"Accept=application/json"}, method = GET, value = "/multimedia-file")
@ResponseBody
public List<MultimediaDTO> getFiles(@RequestParam("anm-id") String providerId) {
List<Multimedia> allMultimedias = multimediaService.getMultimediaFiles(providerId);
return with(allMultimedias).convert(new Converter<Multimedia, MultimediaDTO>() {
@Override
public MultimediaDTO convert(Multimedia md) {
return new MultimediaDTO(md.getCaseId(), md.getProviderId(), md.getContentType(), md.getFilePath(), md.getFileCategory());
}
});
}
@RequestMapping(headers = {"Accept=multipart/form-data"}, method = POST, value = "/multimedia-file")
public ResponseEntity<String> uploadFiles(@RequestParam("anm-id") String providerId, @RequestParam("entity-id") String entityId,@RequestParam("content-type") String contentType, @RequestParam("file-category") String fileCategory, @RequestParam("file") MultipartFile file) throws ClientProtocolException, IOException {
MultimediaDTO multimediaDTO = new MultimediaDTO(entityId, providerId, contentType, null, fileCategory);
String status = multimediaService.saveMultimediaFile(multimediaDTO, file);
if(status.equals("success"))
{
Multimedia multimedia = multimediaRepository.findByCaseId(entityId);
patientService.patientImageUpload(multimedia);
}
return new ResponseEntity<>(new Gson().toJson(status), OK);
}
} | 52.023904 | 321 | 0.6792 |
c1d36c915a84c842d4f5c1808e14f1e37a78c685 | 1,066 | package me.nokko.bexment.mixin;
import me.nokko.bexment.common.registry.BSMTransformations;
import moriyashiine.bewitchment.api.interfaces.entity.BloodAccessor;
import moriyashiine.bewitchment.common.item.BottleOfBloodItem;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(BottleOfBloodItem.class)
public class BottleOfBloodItemMixin {
@Inject(method = "finishUsing", at = @At("HEAD"), cancellable = true)
private void finishUsing(ItemStack stack, World world, LivingEntity user, CallbackInfoReturnable<ItemStack> cir){
if (BSMTransformations.isWerepyre(user, true)) {
((BloodAccessor) user).fillBlood(20, false);
cir.setReturnValue(Items.POTION.finishUsing(stack, world, user));
}
}
}
| 42.64 | 117 | 0.781426 |
3c9a67e50ff392717e4e8ec38895ac69b7100f61 | 607 | package algorithms.a301_to_a350.a337_HouseRobberIII_Medium;
/**
* Created by 31798 on 2016/9/14.
*/
public class SolutionNotEfficientEnough {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
int robThis = root.val;
if (root.left != null) {
robThis += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
robThis += rob(root.right.left) + rob(root.right.right);
}
int leaveThis = rob(root.left) + rob(root.right);
return Math.max(leaveThis, robThis);
}
}
| 27.590909 | 68 | 0.566722 |
6b2d3b824b749b3197bd60da92ade340064e9bce | 8,246 | /*
Copyright (c) 2010, NullNoname
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of NullNoname nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package mu.nu.nullpo.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Properties;
/**
* String以外も格納できるプロパティセット
*/
public class CustomProperties extends Properties {
/**
* Serial version
*/
private static final long serialVersionUID = 2L;
/**
* byte型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, byte value) {
return setProperty(key, String.valueOf(value));
}
/**
* short型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, short value) {
return setProperty(key, String.valueOf(value));
}
/**
* int型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, int value) {
return setProperty(key, String.valueOf(value));
}
/**
* long型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, long value) {
return setProperty(key, String.valueOf(value));
}
/**
* float型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, float value) {
return setProperty(key, String.valueOf(value));
}
/**
* double型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, double value) {
return setProperty(key, String.valueOf(value));
}
/**
* char型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, char value) {
return setProperty(key, String.valueOf(value));
}
/**
* boolean型のプロパティを設定
* @param key キー
* @param value keyに対応する変count
* @return プロパティリストの指定されたキーの前の値。それがない場合は null
*/
public synchronized Object setProperty(String key, boolean value) {
return setProperty(key, String.valueOf(value));
}
/**
* byte型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public byte getProperty(String key, byte defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
byte result;
try {
result = Byte.parseByte(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* short型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public short getProperty(String key, short defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
short result;
try {
result = Short.parseShort(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* int型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public int getProperty(String key, int defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
int result;
try {
result = Integer.parseInt(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* long型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public long getProperty(String key, long defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
long result;
try {
result = Long.parseLong(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* float型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public float getProperty(String key, float defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
float result;
try {
result = Float.parseFloat(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* double型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public double getProperty(String key, double defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
double result;
try {
result = Double.parseDouble(str);
} catch(NumberFormatException e) {
result = defaultValue;
}
return result;
}
/**
* char型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応する整count (見つからなかったらdefaultValue)
*/
public char getProperty(String key, char defaultValue) {
String str = getProperty(key, String.valueOf(defaultValue));
char result;
try {
result = str.charAt(0);
} catch(Exception e) {
result = defaultValue;
}
return result;
}
/**
* boolean型のプロパティを取得
* @param key キー
* @param defaultValue keyが見つからない場合に返す変count
* @return 指定されたキーに対応するboolean型変count (見つからなかったらdefaultValue)
*/
public boolean getProperty(String key, boolean defaultValue) {
String str = getProperty(key, Boolean.toString(defaultValue));
return Boolean.valueOf(str);
}
/**
* このプロパティセットを文字列に変換する(URLEncoderでエンコード)
* @param comments 識別コメント
* @return URLEncoderでエンコードされたプロパティセット文字列
*/
public String encode(String comments) {
String result = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
store(out, comments);
result = URLEncoder.encode(out.toString("UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error("UTF-8 not supported", e);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* encode(String)でエンコードしたStringからプロパティセットを復元
* @param source encode(String)でエンコードしたString
* @return 成功するとtrue
*/
public boolean decode(String source) {
try {
String decodedString = URLDecoder.decode(source, "UTF-8");
ByteArrayInputStream in = new ByteArrayInputStream(decodedString.getBytes("UTF-8"));
load(in);
} catch (UnsupportedEncodingException e) {
throw new Error("UTF-8 not supported", e);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
| 26.429487 | 87 | 0.722168 |
05dc3eaa8af39cae8e91024f21fa414b1e046e5d | 1,493 | package com.github.lzk90s.cbec.auth.dao.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import com.github.lzk90s.cbec.internal.api.auth.PlatformAccountDTO;
import com.google.common.base.Converter;
import lombok.Data;
import org.springframework.beans.BeanUtils;
@Data
@TableName("t_platform_account")
public class PlatformAccountEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String user;
private String platform;
private String platformUser;
private String platformPassword;
public static ConverterImpl getConverter() {
return new ConverterImpl();
}
public static class ConverterImpl extends Converter<PlatformAccountEntity, PlatformAccountDTO> {
@Override
public PlatformAccountDTO doForward(PlatformAccountEntity platformAccountEntity) {
PlatformAccountDTO platformAccountDTO = new PlatformAccountDTO();
BeanUtils.copyProperties(platformAccountEntity, platformAccountDTO);
return platformAccountDTO;
}
@Override
public PlatformAccountEntity doBackward(PlatformAccountDTO platformAccountDTO) {
PlatformAccountEntity platformAccountEntity = new PlatformAccountEntity();
BeanUtils.copyProperties(platformAccountDTO, platformAccountEntity);
return platformAccountEntity;
}
}
}
| 35.547619 | 100 | 0.750167 |
a23891d6f3df6ebe35662e22249296f8c47ab4d6 | 1,309 |
package org.onvif.ver10.schema;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SetDateTimeType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SetDateTimeType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Manual"/>
* <enumeration value="NTP"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SetDateTimeType")
@XmlEnum
public enum SetDateTimeType {
/**
* Indicates that the date and time are set manually.
*
*/
@XmlEnumValue("Manual")
MANUAL("Manual"),
/**
* Indicates that the date and time are set through NTP
*
*/
NTP("NTP");
private final String value;
SetDateTimeType(String v) {
value = v;
}
public String value() {
return value;
}
public static SetDateTimeType fromValue(String v) {
for (SetDateTimeType c: SetDateTimeType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 21.459016 | 95 | 0.614973 |
fb82e4f3b029333f8c3910a346a6885ecd64633b | 2,646 | /*
* 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.isis.core.internaltestsupport.jmocking;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.hamcrest.Description;
import org.jmock.api.Action;
import org.jmock.api.Invocation;
public final class JMockActions {
private JMockActions() {
}
@SafeVarargs
public static <T> Action returnEach(final T... values) {
return new ReturnEachAction<T>(values);
}
public static Action returnArgument(final int i) {
return new ReturnArgumentJMockAction(i);
}
private static class ReturnEachAction<T> implements Action {
private final Collection<T> collection;
private final Iterator<T> iterator;
ReturnEachAction(Collection<T> collection) {
this.collection = collection;
this.iterator = collection.iterator();
}
@SafeVarargs
private ReturnEachAction(T... array) {
this(Arrays.asList(array));
}
@Override
public T invoke(Invocation invocation) throws Throwable {
return iterator.next();
}
@Override
public void describeTo(Description description) {
description.appendValueList("return iterator.next() over ", ", ", "", collection);
}
}
private static final class ReturnArgumentJMockAction implements Action {
private final int i;
private ReturnArgumentJMockAction(final int i) {
this.i = i;
}
@Override
public void describeTo(final Description description) {
description.appendText("parameter #" + i + " ");
}
@Override
public Object invoke(final Invocation invocation) throws Throwable {
return invocation.getParameter(i);
}
}
}
| 30.413793 | 94 | 0.666667 |
cff952b26aae1dd1bbfb5f8741a9f9a010118567 | 2,283 | package org.rx.spring;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.rx.core.*;
import org.rx.util.Servlets;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.rx.core.App.as;
@ControllerAdvice
@Aspect
@Component
public class ControllerInterceptor extends BaseInterceptor {
private final List<String> skipMethods = new CopyOnWriteArrayList<>(Arrays.toList("setServletRequest", "setServletResponse", "isSignIn"));
public ControllerInterceptor() {
super.argShortSelector = (s, p) -> {
if (p instanceof MultipartFile) {
return "[MultipartFile]";
}
return p;
};
}
@Override
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = as(signature, MethodSignature.class);
if (methodSignature == null || skipMethods.contains(signature.getName())) {
return joinPoint.proceed();
}
IRequireSignIn requireSignIn = as(joinPoint.getTarget(), IRequireSignIn.class);
if (requireSignIn != null && !requireSignIn.isSignIn(methodSignature.getMethod(), joinPoint.getArgs())) {
throw new NotSignInException();
}
App.logMetric("url", Servlets.currentRequest().left.getRequestURL().toString());
return super.doAround(joinPoint);
}
@SneakyThrows
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object onException(Exception e, HttpServletRequest request) {
String msg = App.log(request.getRequestURL().toString(), e);
if (SpringContext.controllerExceptionHandler == null) {
return msg;
}
return SpringContext.controllerExceptionHandler.invoke(e, msg);
}
}
| 36.238095 | 142 | 0.711783 |
79d64222c2f5edc29f34fcf1477b6bd63f5548b9 | 302 | package com.softwareonpurpose.calibrator4test;
class Tally {
private long tally;
static Tally getInstance() {
return new Tally();
}
void increment() {
tally += 1;
}
long getTally() {
return tally;
}
void reset() {
tally = 0;
}
}
| 13.727273 | 46 | 0.533113 |
09edec2cce55882c1835c16db6284f96b3039fd3 | 1,297 | package models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "daily_recaps")
public class SalesRecap {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "outlet")
private Outlet outlet;
@Column(name = "for_date")
private Date forDate;
@Column(name = "note")
private String note = "";
@OneToMany(mappedBy = "salesRecap")
private List<RecapItem> recapItems = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Outlet getOutlet() {
return outlet;
}
public void setOutlet(Outlet outlet) {
this.outlet = outlet;
}
public Date getForDate() {
return forDate;
}
public void setForDate(Date forDate) {
this.forDate = forDate;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<RecapItem> getRecapItems() {
return recapItems;
}
public void setRecapItems(List<RecapItem> recapItems) {
this.recapItems = recapItems;
}
}
| 18.797101 | 59 | 0.615266 |
b492477e2b158579c826fb8097bbbff2ea5181fa | 3,105 | /*
철학자
status 생각하다, 밥먹다, 배가 고프다
밥을 먹을때는 양손에 포크를 들어야하며
총 5명의 사람과 5개의 포크가 있다
즉 세마포어로 2개의 스레드만 작동하도록
*/
package Task.Philosopher.Semaphore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Philosopher implements Runnable {
private String name;
private int number;
public static final Semaphore semaphore = new Semaphore(2);
public Philosopher(String name, int number) {
this.name = name;
this.number = number;
}
public void think() {
System.out.println(name + " thinking ...");
}
public void eat() {
System.out.println(name + " eating ... yum-yum-yum");
}
public void takeFork(int i) {
System.out.println(name + " attemp to take (" + i + ") fork ...");
Fork fork = Tableware.forks.get(i);
fork.useFork();
System.out.println(name + " take (" + i + ") fork now!");
}
public void putFork(int i) {
System.out.println(name + " put (" + i + ") fork down ...");
Fork fork = Tableware.forks.get(i);
fork.unUseFork();
}
public void run() {
long start = System.currentTimeMillis();
while (true) {
think();
try {
semaphore.acquire();
takeFork(this.number);
takeFork((this.number + 1) % 5);
eat();
putFork(this.number);
putFork((this.number + 1) % 5);
semaphore.release();
long end = System.currentTimeMillis(); //프로그램이 끝나는 시점 계산
System.out.println( "경과 시간 : " + ( end - start )/1000.0 +"초"); //실행 시간 계산 및 출력
} catch (Exception e) {
System.out.println("Exception occured!!");
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("컴퓨터소프트웨어공학과 20161213 최범휘");
System.out.println("뮤텍스와 세마포어를 이용한 식사하는 철학자 문제");
Thread.sleep(2000);
Philosopher a = new Philosopher("A", 0);
Philosopher b = new Philosopher("B", 1);
Philosopher c = new Philosopher("C", 2);
Philosopher d = new Philosopher("D", 3);
Philosopher e = new Philosopher("E", 4);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(a);
exec.execute(b);
exec.execute(c);
exec.execute(d);
exec.execute(e);
}
}
class Fork {
Lock lock = new ReentrantLock();
public void useFork() {
lock.lock();
}
public void unUseFork() {
lock.unlock();
}
}
class Tableware {
public static final List<Fork> forks = new ArrayList<Fork>(
Arrays.asList(new Fork(),new Fork(),new Fork(),new Fork(),new Fork()));
} | 27.236842 | 94 | 0.561997 |
eb7fa5d40e0c5e28508ba9312ed1e1b05bd9a22e | 363 | package com.ac.mylib.domain;
import lombok.Data;
import java.util.Date;
/**
* @author Echo
*/
@Data
public class Diary {
private int id = 0;// 日记ID号
private String title = "";// 日记标题
private String address = "";// 日记图片地址
private Date writeTime = null;// 写日记的时间
private int userid = 0;// 用户ID
private String username = "";// 用户名
}
| 15.782609 | 43 | 0.628099 |
0a1d7884aa9ffc2c6cad1535c7ad9fd0c24d08cd | 1,077 | /*
* Copyright(c) 2016 - 2020, Clouds Studio Holding Limited. All rights reserved.
* Project : components
* File : ProduceSkuException.java
* Date : 7/22/20, 12:51 AM
* Author : Hsi Chu
* Contact : hiylo@live.com
*/
package org.hiylo.components.exceptions;
import java.io.Serializable;
/**
* @author 朱玺
* @ClassName: ProduceSkuException
* @Description: 商品SKU异常
* @date 2016年12月7日 下午12:35:15
*/
public class ProduceSkuException extends BaseException implements Serializable {
private static final long serialVersionUID = 2560758391939000337L;
public ProduceSkuException(Integer code) {
this(code, Constants.ExceptionDescript.get(code));
}
public ProduceSkuException(Integer code, String message) {
super(code, message, ProduceSkuException.class);
}
public static <T extends BaseException> T buildException(Integer code) {
return BaseException.call(code);
}
public static <T extends BaseException> T buildException(Integer code, String message) {
return BaseException.call(code, message);
}
}
| 28.342105 | 92 | 0.718663 |
70643804d08a990db09aac669e55eb65c256cdd3 | 3,118 | package com.github.cloudgyb.m3u8downloader.viewcontroller;
import com.github.cloudgyb.m3u8downloader.ApplicationContext;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import java.io.IOException;
/**
* 主页面视图控制器
*
* @author cloudgyb
* 2021/5/16 10:47
*/
public class MainViewController {
@FXML
private TabPane tabPane;
@FXML
private Tab newDownloadTaskTab;
@FXML
private Tab downloadListTab;
@FXML
private Tab downloadHistoryTab;
@FXML
private Tab downloadSettingTab;
public void init() {
ApplicationContext.getInstance().set("tabs", tabPane);
}
public void newDownloadTaskTabSelected() throws IOException {
final Tab tab = tabPane.getSelectionModel().getSelectedItem();
final boolean selected = tab.isSelected();
if (selected) {
FXMLLoader loader = new FXMLLoader(MainViewController.
class.getResource("/fxml/new_download_task.fxml"));
final Pane pane = loader.load();
final NewDownloadTaskViewController controller = loader.getController();
controller.init();
tab.setContent(pane);
}
}
public void downloadListTabSelected() throws IOException {
final Tab tab = tabPane.getSelectionModel().getSelectedItem();
final boolean selected = tab.isSelected();
if (selected) {
FXMLLoader loader = new FXMLLoader(MainViewController.
class.getResource("/fxml/download_list.fxml"));
final StackPane pane = loader.load();
final DownloadListViewController controller = loader.getController();
controller.init();
pane.setAlignment(Pos.CENTER);
tab.setContent(pane);
}
}
public void downloadHistoryTabSelected() throws IOException {
final Tab tab = tabPane.getSelectionModel().getSelectedItem();
final boolean selected = tab.isSelected();
if (selected) {
FXMLLoader loader = new FXMLLoader(MainViewController.
class.getResource("/fxml/download_history.fxml"));
final StackPane pane = loader.load();
final DownloadHistoryViewController controller = loader.getController();
controller.init();
pane.setAlignment(Pos.CENTER);
tab.setContent(pane);
}
}
public void downloadSettingTabSelected() throws IOException {
final Tab tab = tabPane.getSelectionModel().getSelectedItem();
final boolean selected = tab.isSelected();
if (selected) {
FXMLLoader loader = new FXMLLoader(MainViewController.
class.getResource("/fxml/setting.fxml"));
final Pane pane = loader.load();
final DownloadSettingViewController controller = loader.getController();
controller.init();
tab.setContent(pane);
}
}
}
| 34.263736 | 84 | 0.650417 |
0bb7aa2ecd3c3aff6c00949d2cb2a3c19aaf5ea6 | 4,793 | /*******************************************************************************
* Copyright (c) 2002,2006 IBM 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.shrikeBT.shrikeCT.tools;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.invoke.CallSite;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import com.ibm.wala.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrikeBT.IInstruction;
import com.ibm.wala.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrikeCT.ClassReader;
import com.ibm.wala.shrikeCT.CodeReader;
import com.ibm.wala.shrikeCT.InvalidClassFileException;
public class BootstrapDumper {
final private PrintWriter w;
/**
* Get ready to print a class to the given output stream.
*/
public BootstrapDumper(PrintWriter w) {
this.w = w;
}
public static void main(String[] args) throws Exception {
OfflineInstrumenter oi = new OfflineInstrumenter(true);
String[] classpathEntries = oi.parseStandardArgs(args);
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BootstrapDumper p = new BootstrapDumper(w);
URL[] urls = new URL[ classpathEntries.length-1 ];
for(int i = 1; i < classpathEntries.length; i++) {
System.err.println(classpathEntries[i]);
File f = new File(classpathEntries[i]);
assert f.exists();
urls[i-1] = f.toURI().toURL();
}
URLClassLoader image = URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent());
System.err.println(image);
ClassInstrumenter ci;
oi.beginTraversal();
while ((ci = oi.nextClass()) != null) {
try {
p.doClass(image, ci.getReader());
} finally {
w.flush();
}
}
oi.close();
}
private void dumpAttributes(Class cl, ClassReader cr, int i, ClassReader.AttrIterator attrs) throws InvalidClassFileException,
InvalidBytecodeException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
for (; attrs.isValid(); attrs.advance()) {
String name = attrs.getName();
if (name.equals("Code")) {
CodeReader code = new CodeReader(attrs);
CTDecoder decoder = new CTDecoder(code);
decoder.decode();
IInstruction[] insts = decoder.getInstructions();
for(IInstruction inst : insts) {
if (inst instanceof InvokeDynamicInstruction) {
CallSite target = ((InvokeDynamicInstruction)inst).bootstrap(cl);
w.println(target.dynamicInvoker());
w.println(target.getTarget());
/*
* only in Java 8. Uncomment when we mandate Java 8.
try {
w.println(MethodHandles.reflectAs(Method.class, target.dynamicInvoker()));
} catch (Throwable e) {
System.out.println(e);
}
*/
}
}
}
}
}
/**
* Print a class.
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws ClassNotFoundException
*
* @throws IllegalArgumentException if cr is null
* @throws NoSuchFieldException
*/
public void doClass(ClassLoader image, final ClassReader cr) throws InvalidClassFileException, InvalidBytecodeException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
if (cr == null) {
throw new IllegalArgumentException("cr is null");
}
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
cr.initClassAttributeIterator(attrs);
int methodCount = cr.getMethodCount();
for (int i = 0; i < methodCount; i++) {
cr.initMethodAttributeIterator(i, attrs);
dumpAttributes(Class.forName(cr.getName().replace('/', '.'), false, image), cr, i, attrs);
}
}
} | 36.587786 | 301 | 0.676194 |
53d3058f921873ff1ee6327c819ec30b315b6d3f | 2,173 | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* 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.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
public class Cookie implements Cloneable {
public Cookie(String name, String value) {
}
public void setComment(String purpose) {
}
public String getComment() {
return null;
}
public void setDomain(String pattern) {
}
public String getDomain() {
return null;
}
public void setMaxAge(int expiry) {
}
public int getMaxAge() {
return -1;
}
public void setPath(String uri) {
}
public String getPath() {
return null;
}
public void setSecure(boolean flag) {
}
public boolean getSecure() {
return false;
}
public String getName() {
return null;
}
public void setValue(String newValue) {
}
public String getValue() {
return null;
}
public int getVersion() {
return -1;
}
public void setVersion(int v) {
}
public void setHttpOnly(boolean isHttpOnly) {
}
public boolean isHttpOnly() {
return false;
}
/**
* Convert the cookie to a string suitable for use as the value of the
* corresponding HTTP header.
*
* @return a stringified cookie.
*/
@Override
public String toString() {
return null;
}
}
| 25.564706 | 109 | 0.64243 |
ee0d7e698fdb00171ffc600d35a8b9fa4750ab89 | 1,356 | package com.thundersphun.foggingup.fogTypes;
import com.thundersphun.foggingup.util.IdType;
import net.minecraft.util.Identifier;
public class FogTypeBuilder {
private final IdType type;
private float start;
private float end;
private float density;
private Identifier id;
private boolean enabled;
public FogTypeBuilder(IdType type) {
this.type = type;
this.start = 1;
this.end = 1;
this.density = 1;
this.id = new Identifier("");
this.enabled = true;
}
public FogTypeBuilder() {
this(null);
}
public FogTypeBuilder setStart(float start) {
this.start = start;
return this;
}
public FogTypeBuilder setEnd(float end) {
this.end = end;
return this;
}
public FogTypeBuilder setDensity(float density) {
this.density = density;
return this;
}
public FogTypeBuilder setId(Identifier id) {
this.id = id;
return this;
}
public FogTypeBuilder setEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
public FogType build() {
if (this.type != null) {
switch (this.type) {
case BIOME:
return new BiomeFogType(this.start, this.end, this.density, this.id, this.enabled);
case DIMENSION:
return new DimensionFogType(this.start, this.end, this.density, this.id, this.enabled);
}
}
return new FogType(this.start, this.end, this.density, this.id, this.enabled);
}
}
| 21.1875 | 92 | 0.70649 |
5e3411983c2e807248564f86125c81a664cef20d | 418 | package com.easy.live.streaming.servants.protocol.output.user;
import lombok.Data;
/**
* @Description:用户出参
* @Author: zhangliangfu
* @Create on: 2019-07-10 19:05
*/
@Data
public class UserOutput {
private String password;
private String title;
private String avatar;
private Integer id;
private String name;
private String email;
private String phone;
private boolean useFlag;
}
| 19 | 62 | 0.705742 |
845a3c63451c82a35fa80ed29fcfc235f3b6d099 | 426 | package org.openntf.xrest.xsp.log;
import com.ibm.commons.log.Log;
import com.ibm.commons.log.LogMgr;
public class SmartNSFLoggerFactory extends Log{
public final static LogMgr XSP = load("org.openntf.xrest.xsp", "Logger used for Logging all events around the SmartNSF Server side");
public final static LogMgr DDE = load("org.openntf.xrest.designer", "Logger used for Logging all events about SmartNSF in the DDE");
}
| 35.5 | 134 | 0.774648 |
10994f07e85b275bd8375b8220413ffcd7dd9f49 | 3,176 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.ui.StringComboboxEditor;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author peter
*/
public class ComboEditorCompletionContributor extends CompletionContributor implements DumbAware {
public static final Key<Boolean> CONTINUE_RUN_COMPLETION = Key.create("CONTINUE_RUN_COMPLETION");
@Override
public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull final CompletionResultSet result) {
if (parameters.getInvocationCount() == 0) {
return;
}
final PsiFile file = parameters.getOriginalFile();
final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
if (document != null) {
JComboBox comboBox = document.getUserData(StringComboboxEditor.COMBO_BOX_KEY);
if (comboBox != null) {
String substring = document.getText().substring(0, parameters.getOffset());
boolean plainPrefixMatcher = Boolean.TRUE.equals(document.getUserData(StringComboboxEditor.USE_PLAIN_PREFIX_MATCHER));
final CompletionResultSet resultSet = plainPrefixMatcher ?
result.withPrefixMatcher(new PlainPrefixMatcher(substring)) :
result.withPrefixMatcher(substring);
final int count = comboBox.getItemCount();
for (int i = 0; i < count; i++) {
final Object o = comboBox.getItemAt(i);
if (o instanceof String) {
resultSet.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder.create((String)o).withInsertHandler(
new InsertHandler<LookupElement>() {
@Override
public void handleInsert(final InsertionContext context, final LookupElement item) {
final Document document = context.getEditor().getDocument();
document.deleteString(context.getEditor().getCaretModel().getOffset(), document.getTextLength());
}
}), count-i));
}
}
if (!Boolean.TRUE.equals(document.getUserData(CONTINUE_RUN_COMPLETION))) {
result.stopHere();
}
}
}
}
}
| 42.918919 | 129 | 0.700567 |
09b763fdae2983142d74ee1aca37bfb26b6e5ff1 | 465 | /*
* Copyright 2013, Andrew Lindesay
* Distributed under the terms of the MIT License.
*/
package org.haiku.haikudepotserver.dataobjects;
import org.haiku.haikudepotserver.dataobjects.auto._Captcha;
public class Captcha extends _Captcha {
private static Captcha instance;
private Captcha() {}
public static Captcha getInstance() {
if(instance == null) {
instance = new Captcha();
}
return instance;
}
}
| 19.375 | 60 | 0.670968 |
89e32cc05932be2339c47dbd065393367364e731 | 1,812 | package com.jfinal.weixin.sdk.api.shop.bean;
/**
* 商品其他属性
*
* @author Administrator
*
*/
public class ShopAttrExt {
private String isPostFree;// 是否包邮(0-否, 1-是), 如果包邮delivery_info字段可省略
private String isHasReceipt;// 是否提供发票(0-否, 1-是)
private String isUnderGuaranty;// 是否保修(0-否, 1-是)
private String isSupportReplace;// 是否支持退换货(0-否, 1-是)
private Location location;// 商品所在地地址
public String getIsPostFree() {
return isPostFree;
}
public void setIsPostFree(String isPostFree) {
this.isPostFree = isPostFree;
}
public String getIsHasReceipt() {
return isHasReceipt;
}
public void setIsHasReceipt(String isHasReceipt) {
this.isHasReceipt = isHasReceipt;
}
public String getIsUnderGuaranty() {
return isUnderGuaranty;
}
public void setIsUnderGuaranty(String isUnderGuaranty) {
this.isUnderGuaranty = isUnderGuaranty;
}
public String getIsSupportReplace() {
return isSupportReplace;
}
public void setIsSupportReplace(String isSupportReplace) {
this.isSupportReplace = isSupportReplace;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public static class Location {
private String country;
private String province;
private String city;
private String address;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
}
| 18.875 | 68 | 0.718543 |
8001574900b73595a72db2198a17fc8a37935be9 | 1,849 | package dev.darshit.urlshortener.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class StringUtils {
public static boolean isEmpty(String value) {
return (value == null || "".equals(value) || "null".equalsIgnoreCase(value));
}
public static List<String> split(String value, String delimiter) {
if (isEmpty(value) || isEmpty(delimiter)) {
return new ArrayList<>();
}
return Arrays.asList(value.split(delimiter));
}
public static String replace(final String value, final String target, final String replacement) {
if (isEmpty(value) || isEmpty(target) || replacement == null) {
return value;
}
int endIndex = value.indexOf(target);
if (endIndex == -1) {
return value;
}
StringBuilder builder = new StringBuilder(value.length());
int beginIndex = 0;
int targetLength = target.length();
while (endIndex >= 0) {
builder.append(substring(value, beginIndex, endIndex));
builder.append(replacement);
beginIndex = endIndex + targetLength;
endIndex = value.indexOf(target, beginIndex);
}
// characters from lastIndex as loop will break because of -1 endIndex value
builder.append(substring(value, beginIndex));
return builder.toString();
}
public static String delete(final String value, final String target) {
return replace(value, target, "");
}
private static String substring(final String value, final int beginIndex) {
return value.substring(beginIndex);
}
private static String substring(final String value, final int beginIndex, final int endIndex) {
return value.substring(beginIndex, endIndex);
}
} | 32.438596 | 101 | 0.63656 |
706694b8adac6220987038395e53f6803f575f8f | 2,926 | package org.apache.maven.plugin.internal;
/*
* 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.
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.Parameter;
import org.codehaus.plexus.component.configurator.ConfigurationListener;
/**
* A configuration listener to help validate the plugin configuration. For instance, check for required but missing
* parameters.
*
* @author Benjamin Bentmann
*/
class ValidatingConfigurationListener
implements ConfigurationListener
{
private final Object mojo;
private final ConfigurationListener delegate;
private final Map<String, Parameter> missingParameters;
public ValidatingConfigurationListener( Object mojo, MojoDescriptor mojoDescriptor, ConfigurationListener delegate )
{
this.mojo = mojo;
this.delegate = delegate;
this.missingParameters = new HashMap<String, Parameter>();
if ( mojoDescriptor.getParameters() != null )
{
for ( Parameter param : mojoDescriptor.getParameters() )
{
if ( param.isRequired() )
{
missingParameters.put( param.getName(), param );
}
}
}
}
public Collection<Parameter> getMissingParameters()
{
return missingParameters.values();
}
public void notifyFieldChangeUsingSetter( String fieldName, Object value, Object target )
{
delegate.notifyFieldChangeUsingSetter( fieldName, value, target );
if ( mojo == target )
{
notify( fieldName, value );
}
}
public void notifyFieldChangeUsingReflection( String fieldName, Object value, Object target )
{
delegate.notifyFieldChangeUsingReflection( fieldName, value, target );
if ( mojo == target )
{
notify( fieldName, value );
}
}
private void notify( String fieldName, Object value )
{
if ( value != null )
{
missingParameters.remove( fieldName );
}
}
}
| 29.857143 | 120 | 0.675666 |
6c2cb0ff42ff5c4f68ce562ddb2f4c2e0d36f693 | 2,104 | package hu.bme.mit.theta.solver.smtlib.impl.generic;
import hu.bme.mit.theta.core.decl.Decl;
import hu.bme.mit.theta.core.type.Expr;
import hu.bme.mit.theta.core.type.Type;
import hu.bme.mit.theta.solver.smtlib.solver.transformer.SmtLibDeclTransformer;
import hu.bme.mit.theta.solver.smtlib.solver.transformer.SmtLibExprTransformer;
import hu.bme.mit.theta.solver.smtlib.solver.transformer.SmtLibSymbolTable;
import hu.bme.mit.theta.solver.smtlib.solver.transformer.SmtLibTransformationManager;
import hu.bme.mit.theta.solver.smtlib.solver.transformer.SmtLibTypeTransformer;
public class GenericSmtLibTransformationManager implements SmtLibTransformationManager {
private final SmtLibTypeTransformer typeTransformer;
private final SmtLibDeclTransformer declTransformer;
private final SmtLibExprTransformer exprTransformer;
public GenericSmtLibTransformationManager(final SmtLibSymbolTable symbolTable) {
this.typeTransformer = instantiateTypeTransformer(this);
this.declTransformer = instantiateDeclTransformer(this, symbolTable);
this.exprTransformer = instantiateExprTransformer(this);
}
@Override
public final String toSort(final Type type) {
return typeTransformer.toSort(type);
}
@Override
public final String toSymbol(final Decl<?> decl) {
return declTransformer.toSymbol(decl);
}
@Override
public final String toTerm(final Expr<?> expr) {
return exprTransformer.toTerm(expr);
}
protected SmtLibTypeTransformer instantiateTypeTransformer(final SmtLibTransformationManager transformer) {
return new GenericSmtLibTypeTransformer(transformer);
}
protected SmtLibDeclTransformer instantiateDeclTransformer(
final SmtLibTransformationManager transformer, final SmtLibSymbolTable symbolTable
) {
return new GenericSmtLibDeclTransformer(transformer, symbolTable);
}
protected SmtLibExprTransformer instantiateExprTransformer(final SmtLibTransformationManager transformer) {
return new GenericSmtLibExprTransformer(transformer);
}
}
| 40.461538 | 111 | 0.786122 |
e89b2f30e6b607e8bd183b3283dcf7cc42996415 | 3,374 | package com.zup.cartao.proposta.solicitaCartao;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.HashMap;
import java.util.Optional;
@RestController
@RequestMapping(value = "/api/propostas")
public class NovaPropostaController {
@Value("${jasypt.password}")
private String password;
PropostaRepository propostaRepository;
AnaliseClient analiseClient;
SolicitaCartaoClient solicitaCartaoClient;
public NovaPropostaController(PropostaRepository propostaRepository,
AnaliseClient analiseClient,
SolicitaCartaoClient solicitaCartaoClient) {
this.propostaRepository = propostaRepository;
this.analiseClient = analiseClient;
this.solicitaCartaoClient = solicitaCartaoClient;
}
@PostMapping
public ResponseEntity<?> novaProposta(@RequestBody @Valid NovaPropostaRequest request,
UriComponentsBuilder uriBuilder){
System.out.println(password);
Optional<Proposta> possivelProposta = propostaRepository.findByDocumento(request.getDocumento());
if(possivelProposta.isPresent()){
HashMap<String, Object> resposta = new HashMap<>();
resposta.put("mensagem", "Já existe solicitação para esse cliente.");
return ResponseEntity.unprocessableEntity().body(resposta);
}
Proposta novaProposta = propostaRepository.save(request.paraProposta(password));
URI uri = uriBuilder.path("/api/propostas/{id}").buildAndExpand(novaProposta.getId()).toUri();
try{
// Proposta APROVADA
AnaliseClient.ConsultaStatusRequest requisicaoDaAnalise = new AnaliseClient.ConsultaStatusRequest(novaProposta);
AnaliseClient.ConsultaAnaliseResponse resposta = analiseClient.consultaStatus(requisicaoDaAnalise);
novaProposta.atualizaStatus(resposta.getResultadoSolicitacao());
propostaRepository.save(novaProposta);
//
// Solicita Cartão
try {
SolicitaCartaoClient.NovoCartaoRequest requisicaoDoCartao = new SolicitaCartaoClient.NovoCartaoRequest(novaProposta);
SolicitaCartaoClient.NovoCartaoResponse respostaCartao = solicitaCartaoClient.solicitaCartao(requisicaoDoCartao);
propostaRepository.save(novaProposta);
return ResponseEntity.created(uri).body(new NovaPropostaResponse(novaProposta));
}catch (FeignException.UnprocessableEntity e) {
return ResponseEntity.created(uri).build();
}
//
// Proposta NAO_APROVADA
}catch (FeignException.UnprocessableEntity e){
novaProposta.atualizaStatus("COM_RESTRICAO");
propostaRepository.save(novaProposta);
return ResponseEntity.created(uri).body(new NovaPropostaResponse(novaProposta));
}
//
}
}
| 43.25641 | 133 | 0.714582 |
8e5edf843c4b4e883ea49526de99d9b084542cc2 | 7,924 | package type.quantity;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import type.TypeEnv;
import compile.structure.Atom;
import compile.structure.Membrane;
import compile.structure.ProcessContext;
import compile.structure.Context;
import compile.structure.RuleContext;
import compile.structure.RuleStructure;
/**
* 量的解析(?)
* @author kudo
*
*/
public class QuantityInferer {
private final CountsSet countsset;
public Map<String, FixedCounts> getMemNameToFixedCountsSet(){
return countsset.getMemNameToFixedCountsSet();
}
private Membrane root;
public QuantityInferer(Membrane root){
this.countsset = new CountsSet();
this.root = root;
}
/**
* 量的解析を行う
*/
public void infer(){
// 個々の具体膜に対してStaticCountsを、
// 最外膜/継続膜に対してDynamicCountsを求める
// 全ての右辺膜に効果範囲を決める
// プロセスの混在膜があればプロセス独立性を失う
// ルール文脈の分散があればルールセット独立性を失う
inferRHSMembrane(root);
// 個々に解けるものは解く
countsset.solveIndividual();
// // 解いたものをマージする
// countsset.mergeFixeds();
// 解けないものはマージして解く
countsset.solveAll();
// if(Env.quantityInferenceLevel >= Env.COUNT_APPLYANDMERGE){
// // 個々の具体膜についてそれぞれに効果を適用する
// countsset.applyIndividual();
// }
// // 適用回数変数に[0,無限]を割り当てる
// countsset.assignInfinityToVar();
// if(Env.quantityInferenceLevel >= Env.COUNT_APPLYANDMERGE){
// // アトム個数の下限を0として適用回数を解く
// countsset.solveByCounts();
// }
// // 具体値を計算させる
// if(Env.quantityInferenceLevel >= Env.COUNT_APPLYANDMERGEDETAIL){
// countsset.solveIndividuals();
// }
//// countsset.solveDynamics();
// // 具体膜をマージする
// countsset.mergeFixeds();
// //プロセスの独立性の崩れた膜に効果を適用する
// countsset.applyCollapseds();
// 全下限を0に直し、[0,0]を0にする
countsset.assignZeroToMinimum();
}
public void printAll(){
countsset.printAll();
}
/**
* ルールについて量的解析を行う
* @param rule
*/
private void inferRule(RuleStructure rule){
// 左辺膜と右辺膜を、同じ膜として扱う
inferRuleRootMembrane(rule);
// 右辺子膜の走査
for(Membrane rhsmem : rule.rightMem.mems)
inferRHSMembrane(rhsmem);
// 右辺出現ルールの検査
for(RuleStructure rhsrule : rule.rightMem.rules)
inferRule(rhsrule);
}
/**
* 右辺の膜を再帰的に走査し、
* 1. プロセス文脈が出現しない膜
* 2. プロセス文脈が1個出現する膜
* 3. プロセス文脈が2個以上出現する膜
* にわける
* @param rhs
*/
private void inferRHSMembrane(Membrane rhs){
Set<Membrane> lhss = new HashSet<>();
/* プロセス文脈、型付きプロセス文脈について左辺出現膜の集合を得る */
for(ProcessContext rhsOcc : rhs.processContexts){
ProcessContext lhsOcc = (ProcessContext)rhsOcc.def.lhsOcc;
if(!lhss.contains(lhsOcc.mem))lhss.add(lhsOcc.mem);
}
for(ProcessContext rhsOcc : rhs.typedProcessContexts){
// データ型は無視
if(TypeEnv.dataTypeOfContextDef(rhsOcc.def)!=null)continue;
ProcessContext lhsOcc = (ProcessContext)rhsOcc.def.lhsOcc;
if(!lhss.contains(lhsOcc.mem))lhss.add(lhsOcc.mem);
}
// プロセス文脈が複数の膜から来ている場合、プロセスの独立性は絶たれる
if(lhss.size() > 1)
countsset.collapseProcessIndependency(TypeEnv.getMemName(rhs));
switch(lhss.size()){
case 0 : // プロセス文脈が出現しない膜
countsset.effectTarget.put(rhs,rhs);
inferGeneratedMembrane(rhs);
// 生成膜の効果対象は自身
break;
default: // 1個も2個も関係なく解析
countsset.effectTarget.put(rhs,countsset.effectTarget.get(rhs.parent));
inferMultiInheritedMembrane(lhss,rhs);
// case 1 : // プロセス文脈が1個出現する膜
// countsset.add(inferInheritedMembrane(((ProcessContext)rhs.processContexts.get(0)).def.lhsOcc.mem,rhs));
// break;
// default: // プロセス文脈が2個以上出現する膜
// Set<Membrane> lhss = new HashSet<Membrane>();
// for(ProcessContext rhsOcc : ((List<ProcessContext>)rhs.processContexts)){
// ProcessContext lhsOcc = (ProcessContext)rhsOcc.def.lhsOcc;
// if(!lhss.contains(lhsOcc.mem))lhss.add(lhsOcc.mem);
// }
// countsset.add(inferMultiInheritedMembrane(lhss,rhs));
}
/** プロセス文脈の分散が無いことを確認し、あればプロセス独立性を失う */
if(!checkIndependency(rhs.processContexts, rhs) ||
!checkIndependency(rhs.typedProcessContexts, rhs) )
countsset.collapseProcessUnderBounds(TypeEnv.getMemName(rhs));
/** ルール文脈の分散の有無を確認し、あればルールセット独立性を失う */
for(RuleContext rc : rhs.ruleContexts){
if(lhss.contains(rc.mem))continue;
else{
if(lhss.size() == 0) // 生成膜であればその膜のみ
countsset.collapseRuleIndependency(rhs);
else // 継続膜等であれば効果対象において。
if(countsset.effectTarget.get(rhs) == null){
countsset.collapseRulesIndependency(TypeEnv.getMemName(rhs));
}// 効果対象が全ての膜であれば膜名について。
else countsset.collapseRuleIndependency(countsset.effectTarget.get(rhs));
}
}
// 子膜の検査
for(Membrane child : rhs.mems)
inferRHSMembrane(child);
// ルールの検査
for(RuleStructure rule : rhs.rules)
inferRule(rule);
}
/**
* わたされた文脈列のいずれかがこの膜に出現することを確かめる
* いずれも出現していない場合、falseを返す
* todo ProcessContextをContextに変更したが問題ないか?
*/
public boolean checkOccurrence(List<Context> rhsOccs, Membrane rhs){
boolean okflg = false;
for(Context pcRhsOcc : rhsOccs){
if(pcRhsOcc.mem == rhs){
okflg = true;
break;
}
}
return okflg;
}
/**プロセス文脈の分散をチェックする
* 渡された文脈列のそれぞれの左辺出現膜のプロセスが全て輸送されていることを確認し、
* 確認できたらtrueを、確認できなければfalseを返す */
public boolean checkIndependency(List<ProcessContext> rhsOccs, Membrane rhs){
for(ProcessContext rhsOcc : rhsOccs){
// データ型の場合無視する
if(TypeEnv.dataTypeOfContextDef(rhsOcc.def)!=null)continue;
Membrane lhsmem = ((ProcessContext)rhsOcc.def.lhsOcc).mem;
if(lhsmem.processContexts.size() > 0){
boolean ok = checkOccurrence(lhsmem.processContexts.get(0).def.rhsOccs, rhs);
if(!ok)return false;
}
boolean okflg = true;
for(ProcessContext lhsOcc : lhsmem.typedProcessContexts){
boolean ok = checkOccurrence(lhsOcc.def.rhsOccs, rhs);
if(!ok){
okflg = false;
break;
}
}
if(!okflg)return false;
}
return true;
}
// /**
// * 左辺から右辺に受け継がれた「同じ膜」である、として解析する。
// * @param lhs
// * @param rhs
// */
// private DynamicCounts inferInheritedMembrane(Membrane lhs, Membrane rhs){
// VarCount vc = new VarCount();
// Count count = new Count(vc);
// //右辺から左辺を減算(解析結果を加算)
// StaticCounts rhsCounts = getCountsOfMem(1,rhs,count);
// StaticCounts lhsCounts = getCountsOfMem(-1,lhs,count);
// return new DynamicCounts(lhsCounts, 1, rhsCounts,vc);
// }
/**
* ルール右辺と左辺の本膜について受け継がれたものとして解析する。
* この効果はルール本膜に対してのみ有効(TODO ルール本膜の効果範囲にたいして有効)
* @param rule
* @param count
* @return
*/
private void inferRuleRootMembrane(RuleStructure rule){
//右辺から左辺を減算(解析結果を加算)
VarCount vc = new VarCount();
Count count = new Count(vc);
StaticCounts rhsCounts = getCountsOfMem(1,rule.rightMem,count);
StaticCounts lhsCounts = getCountsOfMem(-1,rule.leftMem,count);
rhsCounts.mem = rule.parent;
lhsCounts.mem = rule.parent;
countsset.add(new DynamicCounts(lhsCounts, 1, rhsCounts, vc), false);
}
/**
* 左辺複数の膜から右辺に受け継がれた「マージされた膜」として解析する。
* この効果は、同名の膜全てに共通。
* @param lhss
* @param rhs
*/
private void inferMultiInheritedMembrane(Set<Membrane> lhss, Membrane rhs){
VarCount vc = new VarCount();
Count count = new Count(vc);
StaticCounts rhsCounts = getCountsOfMem(1,rhs,count);
StaticCounts lhsCounts = new StaticCounts(rhs);
for(Membrane lhs : lhss)
lhsCounts.addAllCounts(getCountsOfMem(-1,lhs,count));
countsset.add(new DynamicCounts(lhsCounts, lhss.size(), rhsCounts, vc), true);
}
/**
* 単独で生成された膜として解析する。
* @param mem
*/
private void inferGeneratedMembrane(Membrane mem){
VarCount vc = new VarCount();
vc.bind(new IntervalCount(1,1));//NumCount(1));
Count count = new Count(vc);
countsset.add(getCountsOfMem(1,mem,count));
}
private StaticCounts getCountsOfMem(int sign, Membrane mem, Count count){
StaticCounts quantities = new StaticCounts(mem);
//アトムの解析結果
for(Atom atom : mem.atoms)
quantities.addAtomCount(atom,(Count.mul(sign, count)));
//子膜の解析結果
for(Membrane child : mem.mems)
quantities.addMemCount(child,(Count.mul(sign,count)));
return quantities;
}
// /**
// * ルール適用回数を全て無限として解析結果を解く
// *
// */
// private boolean solveRVAsInfinity(){
// return true;
// }
}
| 26.861017 | 108 | 0.709869 |
ddd44b95208456e4395a66a07089247d94ea6155 | 255 |
module io.toolisticon.compiletesting.integrationtest.java9 {
requires java.compiler;
requires java.logging;
requires transitive integration.test.java9.namedautomaticmodule;
exports io.toolisticon.compiletesting.integrationtest.java9;
}
| 25.5 | 68 | 0.8 |
067ed4f44c142aa0da37cc0fbdcb9aa300dc9d12 | 263 | package org.ljelic.instafram.observer.command;
import org.ljelic.instafram.view.adapter.dialog.DialogAdapter;
public class HelpOfflineAction extends Command {
@Override
void execute() {
DialogAdapter.info("Offline help should show up");
}
} | 23.909091 | 62 | 0.741445 |
fb6ceb8145383f0c444b4ffaace81a27abfc9574 | 859 | package de.adesso.anki.messages;
import java.nio.ByteBuffer;
/**
* Notifies the controller that the vehicle deviated from its desired driving lane.
*
* @author Yannick Eckey <yannick.eckey@adesso.de>
*/
public class OffsetFromRoadCenterUpdateMessage extends Message {
public static final int TYPE = 0x2d;
private float offsetFromRoadCenter; // float
private int laneChangeId; // unsigned byte
public OffsetFromRoadCenterUpdateMessage() {
this.type = TYPE;
}
@Override
protected void parsePayload(ByteBuffer buffer) {
this.offsetFromRoadCenter = buffer.getFloat();
this.laneChangeId = Byte.toUnsignedInt(buffer.get());
}
@Override
protected void preparePayload(ByteBuffer buffer) {
buffer.putFloat(this.offsetFromRoadCenter);
buffer.put((byte) this.laneChangeId);
}
}
| 26.84375 | 84 | 0.711292 |
90b18ddb97622f3938a338a1b0cccce7816acd87 | 6,011 | /*
* 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.ignite.internal.processors.query.h2.database.io;
import java.util.List;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.pagemem.PageUtils;
import org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusInnerIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.IOVersions;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO;
import org.apache.ignite.internal.processors.query.h2.database.H2Tree;
import org.apache.ignite.internal.processors.query.h2.database.InlineIndexHelper;
import org.apache.ignite.internal.processors.query.h2.opt.H2CacheRow;
import org.apache.ignite.internal.processors.query.h2.opt.H2Row;
/**
* Inner page for H2 row references.
*/
public abstract class AbstractH2ExtrasInnerIO extends BPlusInnerIO<H2Row> implements H2RowLinkIO {
/** Payload size. */
protected final int payloadSize;
/** */
public static void register() {
register(false);
register(true);
}
/**
* @param mvcc Mvcc flag.
*/
private static void register(boolean mvcc) {
short type = mvcc ? PageIO.T_H2_EX_REF_MVCC_INNER_START : PageIO.T_H2_EX_REF_INNER_START;
for (short payload = 1; payload <= PageIO.MAX_PAYLOAD_SIZE; payload++) {
IOVersions<? extends AbstractH2ExtrasInnerIO> io =
getVersions((short)(type + payload - 1), payload, mvcc);
PageIO.registerH2ExtraInner(io, mvcc);
}
}
/**
* @param payload Payload size.
* @param mvccEnabled Mvcc flag.
* @return IOVersions for given payload.
*/
@SuppressWarnings("unchecked")
public static IOVersions<? extends BPlusInnerIO<H2Row>> getVersions(int payload, boolean mvccEnabled) {
assert payload >= 0 && payload <= PageIO.MAX_PAYLOAD_SIZE;
if (payload == 0)
return mvccEnabled ? H2MvccInnerIO.VERSIONS : H2InnerIO.VERSIONS;
else
return (IOVersions<BPlusInnerIO<H2Row>>)PageIO.getInnerVersions((short)(payload - 1), mvccEnabled);
}
/**
* @param type Type.
* @param payload Payload size.
* @param mvcc Mvcc flag.
* @return Instance of IO versions.
*/
private static IOVersions<? extends AbstractH2ExtrasInnerIO> getVersions(short type, short payload, boolean mvcc) {
return new IOVersions<>(mvcc ? new H2MvccExtrasInnerIO(type, 1, payload) : new H2ExtrasInnerIO(type, 1, payload));
}
/**
* @param type Page type.
* @param ver Page format version.
* @param itemSize Item size.
* @param payloadSize Payload size.
*/
AbstractH2ExtrasInnerIO(short type, int ver, int itemSize, int payloadSize) {
super(type, ver, true, itemSize + payloadSize);
this.payloadSize = payloadSize;
}
/** {@inheritDoc} */
@SuppressWarnings("ForLoopReplaceableByForEach")
@Override public final void storeByOffset(long pageAddr, int off, H2Row row) {
H2CacheRow row0 = (H2CacheRow)row;
assert row0.link() != 0 : row0;
List<InlineIndexHelper> inlineIdxs = InlineIndexHelper.getCurrentInlineIndexes();
assert inlineIdxs != null : "no inline index helpers";
int fieldOff = 0;
for (int i = 0; i < inlineIdxs.size(); i++) {
InlineIndexHelper idx = inlineIdxs.get(i);
int size = idx.put(pageAddr, off + fieldOff, row.getValue(idx.columnIndex()), payloadSize - fieldOff);
if (size == 0)
break;
fieldOff += size;
}
H2IOUtils.storeRow(row0, pageAddr, off + payloadSize, storeMvccInfo());
}
/** {@inheritDoc} */
@Override public final H2Row getLookupRow(BPlusTree<H2Row, ?> tree, long pageAddr, int idx)
throws IgniteCheckedException {
long link = getLink(pageAddr, idx);
assert link != 0;
if (storeMvccInfo()) {
long mvccCrdVer = getMvccCoordinatorVersion(pageAddr, idx);
long mvccCntr = getMvccCounter(pageAddr, idx);
int mvccOpCntr = getMvccOperationCounter(pageAddr, idx);
return ((H2Tree)tree).createMvccRow(link, mvccCrdVer, mvccCntr, mvccOpCntr);
}
return ((H2Tree)tree).createRow(link);
}
/** {@inheritDoc} */
@Override public final void store(long dstPageAddr, int dstIdx, BPlusIO<H2Row> srcIo, long srcPageAddr, int srcIdx) {
int srcOff = srcIo.offset(srcIdx);
byte[] payload = PageUtils.getBytes(srcPageAddr, srcOff, payloadSize);
long link = PageUtils.getLong(srcPageAddr, srcOff + payloadSize);
assert link != 0;
int dstOff = offset(dstIdx);
PageUtils.putBytes(dstPageAddr, dstOff, payload);
H2IOUtils.store(dstPageAddr, dstOff + payloadSize, srcIo, srcPageAddr, srcIdx, storeMvccInfo());
}
/** {@inheritDoc} */
@Override public final long getLink(long pageAddr, int idx) {
return PageUtils.getLong(pageAddr, offset(idx) + payloadSize);
}
}
| 36.430303 | 122 | 0.680586 |
6bafc642f8e8677cad61f95689e282c16ddcc119 | 2,584 | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spring.autoconfigure.datastore;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Optional;
import com.google.cloud.datastore.Key;
import com.google.cloud.spring.data.datastore.core.mapping.DatastoreDataException;
import com.google.cloud.spring.data.datastore.core.mapping.DatastoreMappingContext;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.rest.webmvc.spi.BackendIdConverter;
/**
* A key converter that parses Key JSON from REST requests.
*
* @author Chengyuan Zhao
*
* @since 1.2
*/
public class DatastoreKeyIdConverter implements BackendIdConverter {
private final DatastoreMappingContext datastoreMappingContext;
/**
* Constructor.
*
* @param datastoreMappingContext the mapping context.
*/
public DatastoreKeyIdConverter(DatastoreMappingContext datastoreMappingContext) {
this.datastoreMappingContext = datastoreMappingContext;
}
@Override
public Serializable fromRequestId(String s, Class<?> aClass) {
try {
return Key.fromUrlSafe(URLDecoder.decode(s, Charset.defaultCharset().name()));
}
catch (UnsupportedEncodingException e) {
throw new DatastoreDataException("Could not decode URL key param: " + s);
}
}
@Override
public String toRequestId(Serializable serializable, Class<?> aClass) {
return ((Key) serializable).toUrlSafe();
}
@Override
public boolean supports(Class<?> entityType) {
// This ID converter only covers the Datastore key type. Returning false here causes the
// default converter from Spring Data to be used.
return Optional.ofNullable(this.datastoreMappingContext.getPersistentEntity(entityType))
.map(PersistentEntity::getIdProperty)
.map(PersistentProperty::getType)
.map(clz -> clz.equals(Key.class))
.orElse(false);
}
}
| 32.708861 | 90 | 0.771285 |
f6aad832070fad47ac62969846987331eb350b5c | 4,927 | package seedu.recruit.storage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static seedu.recruit.testutil.TypicalPersons.ALICE;
import static seedu.recruit.testutil.TypicalPersons.HOON;
import static seedu.recruit.testutil.TypicalPersons.IDA;
import static seedu.recruit.testutil.TypicalPersons.getTypicalAddressBook;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import seedu.recruit.commons.exceptions.DataConversionException;
import seedu.recruit.model.CandidateBook;
import seedu.recruit.model.ReadOnlyCandidateBook;
public class XmlCandidateBookStorageTest {
private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "XmlCandidateBookStorageTest");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void readAddressBook_nullFilePath_throwsNullPointerException() throws Exception {
thrown.expect(NullPointerException.class);
readAddressBook(null);
}
private java.util.Optional<ReadOnlyCandidateBook> readAddressBook(String filePath) throws Exception {
return new XmlCandidateBookStorage(Paths.get(filePath)).readCandidateBook(addToTestDataPathIfNotNull(filePath));
}
private Path addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
return prefsFileInTestDataFolder != null
? TEST_DATA_FOLDER.resolve(prefsFileInTestDataFolder)
: null;
}
@Test
public void read_missingFile_emptyResult() throws Exception {
assertFalse(readAddressBook("NonExistentFile.xml").isPresent());
}
@Test
public void read_notXmlFormat_exceptionThrown() throws Exception {
thrown.expect(DataConversionException.class);
readAddressBook("NotXmlFormatCandidateBook.xml");
/* IMPORTANT: Any code below an exception-throwing line (like the one above) will be ignored.
* That means you should not have more than one exception test in one method
*/
}
@Test
public void readAddressBook_invalidPersonAddressBook_throwDataConversionException() throws Exception {
thrown.expect(DataConversionException.class);
readAddressBook("invalidPersonCandidateBook.xml");
}
@Test
public void readAddressBook_invalidAndValidPersonAddressBook_throwDataConversionException() throws Exception {
thrown.expect(DataConversionException.class);
readAddressBook("invalidAndValidPersonCandidateBook.xml");
}
@Test
public void readAndSaveAddressBook_allInOrder_success() throws Exception {
Path filePath = testFolder.getRoot().toPath().resolve("TempAddressBook.xml");
CandidateBook original = getTypicalAddressBook();
XmlCandidateBookStorage xmlCandidateBookStorage = new XmlCandidateBookStorage(filePath);
//Save in new file and read back
xmlCandidateBookStorage.saveCandidateBook(original, filePath);
ReadOnlyCandidateBook readBack = xmlCandidateBookStorage.readCandidateBook(filePath).get();
assertEquals(original, new CandidateBook(readBack));
//Modify data, overwrite exiting file, and read back
original.addCandidate(HOON);
original.removeCandidate(ALICE);
xmlCandidateBookStorage.saveCandidateBook(original, filePath);
readBack = xmlCandidateBookStorage.readCandidateBook(filePath).get();
assertEquals(original, new CandidateBook(readBack));
//Save and read without specifying file path
original.addCandidate(IDA);
xmlCandidateBookStorage.saveCandidateBook(original); //file path not specified
readBack = xmlCandidateBookStorage.readCandidateBook().get(); //file path not specified
assertEquals(original, new CandidateBook(readBack));
}
@Test
public void saveAddressBook_nullAddressBook_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
saveAddressBook(null, "SomeFile.xml");
}
/**
* Saves {@code addressBook} at the specified {@code filePath}.
*/
private void saveAddressBook(ReadOnlyCandidateBook addressBook, String filePath) {
try {
new XmlCandidateBookStorage(Paths.get(filePath))
.saveCandidateBook(addressBook, addToTestDataPathIfNotNull(filePath));
} catch (IOException ioe) {
throw new AssertionError("There should not be an error writing to the file.", ioe);
}
}
@Test
public void saveAddressBook_nullFilePath_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
saveAddressBook(new CandidateBook(), null);
}
}
| 38.492188 | 120 | 0.739598 |
4efac2ae56260a19546b8d7db7fca6667e91d121 | 2,449 | package com.walmartlabs.concord.server.cfg;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2018 Walmart Inc.
* -----
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =====
*/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.walmartlabs.ollie.config.Config;
import org.eclipse.sisu.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
/**
* Default values for {@code configuration} object in processes.
*/
@Named
@Singleton
public class DefaultProcessConfiguration {
private static final Logger log = LoggerFactory.getLogger(DefaultProcessConfiguration.class);
private final Map<String, Object> cfg;
@Inject
@SuppressWarnings("unchecked")
public DefaultProcessConfiguration(@Config("process.defaultConfiguration") @Nullable String path) throws IOException {
if (path == null) {
log.warn("init -> no default process configuration");
this.cfg = Collections.emptyMap();
return;
}
log.info("init -> using external default process configuration: {}", path);
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try (InputStream in = Files.newInputStream(Paths.get(path))) {
this.cfg = Optional.ofNullable(mapper.readValue(in, Map.class)).orElse(Collections.emptyMap());
}
}
@SuppressWarnings(value = "unchecked")
public Map<String, Object> getCfg() {
if (cfg.get("configuration") == null) {
return Collections.emptyMap();
}
return (Map<String, Object>) cfg.get("configuration");
}
}
| 31.397436 | 122 | 0.701511 |
cca3b072ee7443fb2a1161ff7b81a2e63e3967b8 | 378 | package com.gnt.movies.utilities;
public class ApiClientRunnable implements Runnable {
private String urlApi;
private String result;
@Override
public void run() {
result = ApiClient.getResultFromTMDB(urlApi);
}
public ApiClientRunnable(String urlApi) {
super();
this.urlApi = urlApi;
}
public String getResult() {
return result;
}
}
| 17.181818 | 53 | 0.687831 |
335b2f1dd432fb7b76e9d0936131af01599d9925 | 74 | package com.gentics.diktyo.wrapper;
public interface WrappedElement {
}
| 12.333333 | 35 | 0.797297 |
198487575511d473e7bc0532678f87776e405ae8 | 1,685 | /*
* Copyright 2015 Steve Ash
*
* 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.steveash.jg2p.seqvow;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Steve Ash
*/
public class Current implements RetaggerPipe, Serializable {
private static final long serialVersionUID = -145933051168768617L;
@Override
public void pipe(int gramIndex, PartialTagging tagging) {
String g = "CG" + tagging.getGraphemeGrams().get(gramIndex);
tagging.addFeature(gramIndex, g);
String partialGram = tagging.getPartialPhoneGrams().get(gramIndex);
String partialGramOnly = PartialPhones.extractPartialPhoneGramFromGram(partialGram);
Preconditions.checkArgument(isNotBlank(partialGramOnly), "got no eligible from ", partialGram);
String p = "CP" + partialGramOnly;
tagging.addFeature(gramIndex, p);
String notPartialGramOnly = PartialPhones.extractNotPartialPhoneGramFromGram(partialGram);
if (isNotBlank(notPartialGramOnly)) {
String i = "CI" + notPartialGramOnly;
tagging.addFeature(gramIndex, i);
}
}
}
| 33.7 | 99 | 0.750148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.