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
|
|---|---|---|---|---|---|
876078c50a1dc894cd191894e4b14df6b0a5957b
| 376
|
package se.knowit.hackathon.restaurantsapi.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.With;
import se.knowit.hackathon.restaurantsapi.model.GoogleNearbyPlaces;
@Data
@With
@AllArgsConstructor
@NoArgsConstructor
public class FindPlaceResponse {
private int statusCode;
private GoogleNearbyPlaces body;
}
| 22.117647
| 67
| 0.829787
|
6bb6577493a2e80aae45191c09f6019bee2b7975
| 3,645
|
package com.tourcool.core.entity;
import android.text.TextUtils;
import java.io.Serializable;
import java.util.List;
/**
* @Author: JenkinsZhou on 2018/11/19 14:17
* @E-Mail: 971613168@qq.com
* @Function: 电影条目实体
* @Description:
*/
public class SubjectsEntity implements Serializable {
/**
* rating : {"max":10,"average":9.6,"stars":"50","min":0}
* genres : ["犯罪","剧情"]
* title : 肖申克的救赎
* casts : [{"alt":"https://movie.douban.com/celebrity/1054521/","avatars":{"small":"https://img3.doubanio.com/img/celebrity/small/17525.jpg","large":"https://img3.doubanio.com/img/celebrity/large/17525.jpg","medium":"https://img3.doubanio.com/img/celebrity/medium/17525.jpg"},"name":"蒂姆·罗宾斯","id":"1054521"},{"alt":"https://movie.douban.com/celebrity/1054534/","avatars":{"small":"https://img3.doubanio.com/img/celebrity/small/34642.jpg","large":"https://img3.doubanio.com/img/celebrity/large/34642.jpg","medium":"https://img3.doubanio.com/img/celebrity/medium/34642.jpg"},"name":"摩根·弗里曼","id":"1054534"},{"alt":"https://movie.douban.com/celebrity/1041179/","avatars":{"small":"https://img1.doubanio.com/img/celebrity/small/5837.jpg","large":"https://img1.doubanio.com/img/celebrity/large/5837.jpg","medium":"https://img1.doubanio.com/img/celebrity/medium/5837.jpg"},"name":"鲍勃·冈顿","id":"1041179"}]
* collect_count : 1078121
* original_title : The Shawshank Redemption
* subtype : movie
* directors : [{"alt":"https://movie.douban.com/celebrity/1047973/","avatars":{"small":"https://img3.doubanio.com/img/celebrity/small/230.jpg","large":"https://img3.doubanio.com/img/celebrity/large/230.jpg","medium":"https://img3.doubanio.com/img/celebrity/medium/230.jpg"},"name":"弗兰克·德拉邦特","id":"1047973"}]
* year : 1994
* images : {"small":"https://img3.doubanio.com/view/movie_poster_cover/ipst/public/p480747492.webp","large":"https://img3.doubanio.com/view/movie_poster_cover/lpst/public/p480747492.webp","medium":"https://img3.doubanio.com/view/movie_poster_cover/spst/public/p480747492.webp"}
* alt : https://movie.douban.com/subject/1292052/
* id : 1292052
*/
public RatingEntity rating;
public String title;
public int collect_count;
public String original_title;
public String subtype;
public String year;
public ImagesEntity images;
public String alt;
public String id;
public List<String> genres;
public List<CastsEntity> casts;
public List<DirectorsEntity> directors;
public String getGenres() {
String genre = "";
if (genres != null && genres.size() > 0) {
for (String item : genres) {
if (TextUtils.isEmpty(genre)) {
genre = item;
} else {
genre += "&" + item;
}
}
}
return genre;
}
public String getDirectors() {
String director = "";
if (directors != null && directors.size() > 0) {
for (DirectorsEntity item : directors) {
if (TextUtils.isEmpty(director)) {
director = item.name;
} else {
director += "&" + item.name;
}
}
}
return director;
}
public String getCasts() {
String cast = "";
if (casts != null && casts.size() > 0) {
for (CastsEntity item : casts) {
if (TextUtils.isEmpty(cast)) {
cast = item.name;
} else {
cast += "&" + item.name;
}
}
}
return cast;
}
}
| 42.882353
| 903
| 0.596433
|
988b4b9437f0c478b7bfdc528594dc3c31dd714d
| 7,735
|
package ch.uzh.ifi.seal.soprafs20.service;
import ch.uzh.ifi.seal.soprafs20.constant.PlayerStatus;
import ch.uzh.ifi.seal.soprafs20.constant.UserStatus;
import ch.uzh.ifi.seal.soprafs20.entity.Game;
import ch.uzh.ifi.seal.soprafs20.entity.Player;
import ch.uzh.ifi.seal.soprafs20.entity.Stone;
import ch.uzh.ifi.seal.soprafs20.entity.User;
import ch.uzh.ifi.seal.soprafs20.exceptions.ConflictException;
import ch.uzh.ifi.seal.soprafs20.exceptions.NotFoundException;
import ch.uzh.ifi.seal.soprafs20.exceptions.UnauthorizedException;
import ch.uzh.ifi.seal.soprafs20.repository.PlayerRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PlayerServiceTest {
@Mock
private PlayerRepository playerRepository;
@InjectMocks
private PlayerService playerService;
private User testUser;
private Player testPlayer;
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
// given
testUser = new User();
testPlayer = new Player();
// init testUser
testUser.setId(2L);
testUser.setToken("Hello there!");
testUser.setUsername("General Kenobi");
testUser.setStatus(UserStatus.ONLINE);
// init createdPlayer
testPlayer.setId(2L);
testPlayer.setUser(testUser);
testPlayer.setUsername("General Kenobi");
testPlayer.setStatus(PlayerStatus.NOT_READY);
testPlayer.initPlayer();
// mock the playerRepository
Mockito.when(playerRepository.save(Mockito.any())).thenReturn(testPlayer);
}
@Test
void getPlayer_validInput_playerFound() {
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
Player player = playerService.getPlayer(1);
assertEquals(2, player.getId());
assertEquals("General Kenobi", player.getUsername());
assertEquals(testUser, player.getUser());
assertEquals(PlayerStatus.NOT_READY, player.getStatus());
}
@Test
void getPlayer_validInput_noPlayerFound() {
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty());
// then -> attempt to fetch player from db -> check that an error is thrown
String exceptionMessage = "The player with the id 2 does not exist.";
NotFoundException exception = assertThrows(NotFoundException.class,
() -> playerService.getPlayer(2L), exceptionMessage);
assertEquals(exceptionMessage, exception.getMessage());
}
@Test
void getStones_validInput() {
// given
List<Stone> bag;
Game game = new Game();
game.setId(1L);
// add game to player
testPlayer.setGame(game);
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
bag = playerService.getStones(2, 1);
assertEquals(0, bag.size());
}
@Test
void getStones_invalidInput_wrongGame() {
// given
Game game = new Game();
game.setId(1L);
// add game to player
testPlayer.setGame(game);
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
// then -> attempt to create second player with same user -> check that an error is thrown
String exceptionMessage = "The player is playing in another game.";
ConflictException exception = assertThrows(ConflictException.class,
() -> playerService.getStones(2, 2), exceptionMessage);
assertEquals(exceptionMessage, exception.getMessage());
}
@Test
void createPlayer_validInput() {
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty());
// create player
testPlayer = playerService.createPlayer(testUser);
// then
Mockito.verify(playerRepository, Mockito.times(1)).save(Mockito.any());
assertEquals(testUser.getId(), testPlayer.getId());
assertEquals(testUser.getUsername(), testPlayer.getUsername());
assertEquals(testUser, testPlayer.getUser());
}
@Test
void createPlayer_invalidInput_alreadyExistingPlayer() {
// create first player
playerService.createPlayer(testUser);
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
// then -> attempt to create second player with same user -> check that an error is thrown
String exceptionMessage = "The user is already in another game.";
ConflictException exception = assertThrows(ConflictException.class,
() -> playerService.createPlayer(testUser), exceptionMessage);
assertEquals(exceptionMessage, exception.getMessage());
}
@Test
void readyPlayer_validInput() {
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
// call function to ready player
playerService.readyPlayer(2, "Hello there!");
// verify that player entity gets saved
Mockito.verify(playerRepository, Mockito.times(1)).save(Mockito.any());
// test that player is ready
assertEquals(PlayerStatus.READY, testPlayer.getStatus());
// call function again to unready player
playerService.readyPlayer(2, "Hello there!");
// verify that player entity gets saved
Mockito.verify(playerRepository, Mockito.times(2)).save(Mockito.any());
// test that player is ready
assertEquals(PlayerStatus.NOT_READY, testPlayer.getStatus());
}
@Test
void readyPlayer_invalidInput_playerNotAuthorized() {
// mock the playerRepository
Mockito.when(playerRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPlayer));
// then -> attempt to ready player with wrong token -> check that an error is thrown
String exceptionMessage = "The user is not authorized to ready this player.";
UnauthorizedException exception = assertThrows(UnauthorizedException.class,
() -> playerService.readyPlayer(2, "test"), exceptionMessage);
assertEquals(exceptionMessage, exception.getMessage());
}
@Test
void addGame_validInput() {
// given
Game testGame = new Game();
// call function
playerService.addGame(testPlayer, testGame);
// verify that player gets saved
Mockito.verify(playerRepository, Mockito.times(1)).save(Mockito.any());
// test conditions
assertEquals(testGame, testPlayer.getGame());
}
@Test
void savePlayer_validInput() {
// call function
playerService.savePlayer(testPlayer);
// verify that player gets saved
Mockito.verify(playerRepository, Mockito.times(1)).save(Mockito.any());
}
@Test
void deletePlayer_validInput() {
// call function
playerService.deletePlayer(testPlayer);
// verify that player gets saved
Mockito.verify(playerRepository, Mockito.times(1)).delete(Mockito.any());
}
}
| 34.686099
| 103
| 0.680802
|
64c852bbfc214cfdb49aa3a7e1bca3f83aa15850
| 5,801
|
package com.kanomiya.mcmod.enhancedbooks.block;
import com.kanomiya.mcmod.enhancedbooks.EnhancedBooks;
import com.kanomiya.mcmod.enhancedbooks.tileentity.TileEntityStorageShelf;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
// BlockChest
public class BlockStorageShelf extends BlockContainer {
/*
public static final PropertyBool[] HAS_BOOK = new PropertyBool[] {
PropertyBool.create("has_book_0"), PropertyBool.create("has_book_1"), PropertyBool.create("has_book_2"),
PropertyBool.create("has_book_3"), PropertyBool.create("has_book_4"), PropertyBool.create("has_book_5"),
PropertyBool.create("has_book_6"), PropertyBool.create("has_book_7"), PropertyBool.create("has_book_8"),
PropertyBool.create("has_book_9"), PropertyBool.create("has_book_10"), PropertyBool.create("has_book_11"),
PropertyBool.create("has_book_12"), PropertyBool.create("has_book_13"), PropertyBool.create("has_book_14"),
PropertyBool.create("has_book_15"),
};
*/
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public BlockStorageShelf() {
super(Material.wood);
setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
/*
.withProperty(HAS_BOOK[0], Boolean.valueOf(false))
.withProperty(HAS_BOOK[1], Boolean.valueOf(false))
.withProperty(HAS_BOOK[2], Boolean.valueOf(false))
.withProperty(HAS_BOOK[3], Boolean.valueOf(false))
.withProperty(HAS_BOOK[4], Boolean.valueOf(false))
.withProperty(HAS_BOOK[5], Boolean.valueOf(false))
.withProperty(HAS_BOOK[6], Boolean.valueOf(false))
.withProperty(HAS_BOOK[7], Boolean.valueOf(false))
.withProperty(HAS_BOOK[8], Boolean.valueOf(false))
.withProperty(HAS_BOOK[9], Boolean.valueOf(false))
.withProperty(HAS_BOOK[10], Boolean.valueOf(false))
.withProperty(HAS_BOOK[11], Boolean.valueOf(false))
.withProperty(HAS_BOOK[12], Boolean.valueOf(false))
.withProperty(HAS_BOOK[13], Boolean.valueOf(false))
.withProperty(HAS_BOOK[14], Boolean.valueOf(false))
.withProperty(HAS_BOOK[15], Boolean.valueOf(false))
);
*/
setCreativeTab(EnhancedBooks.tabEB);
setHardness(1.5F);
setStepSound(soundTypeWood);
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ) {
if (world.isRemote) { return false; }
player.openGui(EnhancedBooks.instance, EnhancedBooks.GUIID_STORAGESHELF, world, pos.getX(), pos.getY(), pos.getZ());
return true;
}
@Override
public void onNeighborBlockChange(World world, BlockPos pos, IBlockState state, Block neighborBlock) {
onBlockAdded(world, pos, state);
}
@Override
public void onBlockAdded(World world, BlockPos pos, IBlockState state) {
if (world.isRemote) { return ; }
TileEntityStorageShelf te = (TileEntityStorageShelf) world.getTileEntity(pos);
if (te == null) { return ; }
if (world.isBlockPowered(pos)) {
te.setPrevRSState(true);
} else {
te.setPrevRSState(false);
}
}
@Override
public int getRenderType()
{
return -1;
}
@Override
@SideOnly(Side.CLIENT)
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.CUTOUT;
}
@Override
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
return getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite());
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof IInventory) {
InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory)tileentity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override public float getEnchantPowerBonus(World world, BlockPos pos) {
TileEntityStorageShelf te = (TileEntityStorageShelf) world.getTileEntity(pos);
if (te == null) { return 0; }
return te.getEnchantPowerBonus();
}
@Override
public IBlockState getStateFromMeta(int meta)
{
EnumFacing enumfacing = EnumFacing.getFront(meta);
if (enumfacing.getAxis() == EnumFacing.Axis.Y)
{
enumfacing = EnumFacing.NORTH;
}
return getDefaultState().withProperty(FACING, enumfacing);
}
@Override
public int getMetaFromState(IBlockState state)
{
return ((EnumFacing)state.getValue(FACING)).getHorizontalIndex();
}
@Override
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {FACING }); //, HAS_BOOK[0], HAS_BOOK[1], HAS_BOOK[2]});
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new TileEntityStorageShelf();
}
@Override
public boolean isOpaqueCube() { return true; }
@Override
public boolean isFullCube() { return false; }
@Override
public boolean isFullBlock() { return false; }
@Override
public boolean getUseNeighborBrightness() { return true; }
}
| 29.596939
| 154
| 0.76142
|
ea9aff0892abcdf6e7e6609cff1d5efdb2ef10de
| 1,647
|
package app.grafica.twittertext;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Yaml {
static List<Entity> getExpectedEntities(Map testCase, String key, String listSlugKey) {
@SuppressWarnings("unchecked") final List<Map<String, Object>> expectedConfig =
(List<Map<String, Object>>) testCase.get("expected");
final List<Entity> expected = new LinkedList<>();
for (Map<String, Object> configEntry : expectedConfig) {
@SuppressWarnings("unchecked") final List<Integer> indices =
(List<Integer>) configEntry.get("indices");
final String listSlug = listSlugKey != null ? configEntry.get(listSlugKey).toString() : "";
Entity e = new Entity();
e.setStart(indices.get(0));
e.setEnd(indices.get(1));
e.setValue(configEntry.get(key).toString());
e.setListSlug(listSlug.isEmpty() ? null : listSlug);
expected.add(e);
}
return expected;
}
@SuppressWarnings("unchecked")
static List<Map> loadConformanceData(String yamlFile, String testType) throws IOException {
final InputStream stream = new FileInputStream(yamlFile);
final Reader reader = new BufferedReader(new InputStreamReader(stream));
final Map fullConfig = new YAMLMapper().readValue(reader, Map.class);
final Map testConfig = (Map) fullConfig.get("tests");
return (List<Map>) testConfig.get(testType);
}
}
| 39.214286
| 97
| 0.720097
|
f5235416056ae7a960e1a543f0bdd96315cefb52
| 133
|
package com.glitchtechscience.utility.async;
public interface OnProgressUpdated {
public void onProgressUpdated( int percent );
}
| 19
| 46
| 0.81203
|
ee68a892cadfe12266b8f307acdc2d76c2d8f229
| 290
|
package io.github.cepr0.demo.user.event;
import io.github.cepr0.crud.event.EntityEvent;
import io.github.cepr0.demo.model.User;
/**
* @author Sergei Poznanski
*/
public class CreateUserEvent extends EntityEvent<User> {
public CreateUserEvent(final User entity) {
super(entity);
}
}
| 20.714286
| 56
| 0.758621
|
3610f57035f598fe08d5f8f5d6b2f204d6fe7593
| 245
|
package com.rabbitmq.rabbittesttool.clients.publishers;
import com.rabbitmq.rabbittesttool.clients.MessagePayload;
import java.util.concurrent.ConcurrentMap;
public class PublishTracker {
ConcurrentMap<Long, MessagePayload> payloads;
}
| 20.416667
| 58
| 0.82449
|
830f16f2caedfc20348b55a298d0017df80e30a4
| 4,870
|
package com.yjcommon.useful;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* <P>
* 字符串处理的通用方法
* <P>
*
* @author Lien Li
* @version 1.00
*
* */
public class StringUtils {
/** 字符串编码 */
public static final String ENCODING_UTF8 = "utf-8";
/**
* 返回一个StringBuffer对象
*
* @return 返回StringBuffer对象,长度50
* */
public static StringBuffer getBuffer() {
return new StringBuffer(50);
}
/**
*
* 返回一个指定长度的StringBuffer对象
*
* @param length
* 指定长度
*
* @return 返回StringBuffer对象
* */
public static StringBuffer getBuffer(int length) {
return new StringBuffer(length);
}
/**
* 判断字符串是否为null或者为空
*
* @param str
* 传入的字符串
* @return boolean true or false
* */
public static boolean isEmpty(String str) {
if (str == null || str == "" || str.trim().equals(""))
return true;
return false;
}
/**
* 判断字符串是否为0或者为空
*
* @param str
* 传入的字符串
* @return boolean true or false
* */
public static boolean isNumEmpty(String str) {
if (str == null || str == "" || str.trim().equals("")
|| str.trim().equals("0"))
return true;
return false;
}
/**
* 将一个字符串进行UTF8编码后返回
*
* @param data
* 传入的字符串
* @return String
* */
public static String encode(String data) {
try {
return URLEncoder.encode(data, ENCODING_UTF8);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 将字符串转移成整数
*
* @param num
* 传入的字符串
* @return int
* */
public static int toInt(String num) {
try {
return Integer.parseInt(num);
} catch (Exception e) {
return 0;
}
}
/**
* 将字符串转移成长整数
*
* @param num
* 传入的字符串
* @return long
* */
public static long toLong(String num) {
try {
return Long.parseLong(num);
} catch (Exception e) {
return 0;
}
}
/**
* 将字符串转移成浮点数
*
* @param num
* 传入的字符串
* @return long
* */
public static float toFloat(String num) {
try {
return Float.parseFloat(num);
} catch (Exception e) {
return 0;
}
}
/**
* 将字符串转移成布尔数
*
* @param num
* 传入的字符串
* @return boolean
* */
public static boolean toBoolean(String num) {
if (isEmpty(num))
return false;
if (num.equals("true"))
return true;
return false;
}
/**
* sql特殊字符转义
*
* @param keyWord
* 关键字
*
* @return 转义后的字符串
* */
public static String sqliteEscape(String keyWord) {
keyWord = keyWord.replace("/", "//");
keyWord = keyWord.replace("'", "''");
keyWord = keyWord.replace("[", "/[");
keyWord = keyWord.replace("]", "/]");
keyWord = keyWord.replace("%", "/%");
keyWord = keyWord.replace("&", "/&");
keyWord = keyWord.replace("_", "/_");
keyWord = keyWord.replace("(", "/(");
keyWord = keyWord.replace(")", "/)");
return keyWord;
}
/**
* sql特殊字符反转义
*
* @param keyWord
* 关键字
*
* @return 反转义后的字符串
* */
public static String sqliteUnEscape(String keyWord) {
keyWord = keyWord.replace("//", "/");
keyWord = keyWord.replace("''", "'");
keyWord = keyWord.replace("/[", "[");
keyWord = keyWord.replace("/]", "]");
keyWord = keyWord.replace("/%", "%");
keyWord = keyWord.replace("/&", "&");
keyWord = keyWord.replace("/_", "_");
keyWord = keyWord.replace("/(", "(");
keyWord = keyWord.replace("/)", ")");
return keyWord;
}
/**
* 格式一个日期
*
* @param longDate
* 需要格式日期的长整数的字符串形式
* @param format
* 格式化参数
* @return 格式化后的日期
*/
public static String getStrDate(String longDate, String format) {
if (isEmpty(longDate))
return "";
long time = Long.parseLong(longDate);
Date date = new Date(time);
return getStrDate(date, format);
}
/**
* 格式一个日期
*
* @param time
* 需要格式日期的长整数
* @param format
* 格式化参数
* @return 格式化后的日期
*/
public static String getStrDate(long time, String format) {
Date date = new Date(time);
return getStrDate(date, format);
}
/**
* 返回当前日期的格式化表示
*
* @param date
* 指定格式化的日期
* @param formate
* 格式化参数
* @return 格式化后的日期
*/
public static String getStrDate(Date date, String formate) {
SimpleDateFormat dd = new SimpleDateFormat(formate);
return dd.format(date);
}
/**
*
* 返回当前日期的格式化(yyyy-MM-dd)表示
*
* @return 格式化的字符串
*
* */
public static String getStrDate() {
SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd");
return dd.format(new Date());
}
/**
* 返回指定个数的随机数字串
*
* @param num
* 随机数的位数
* @return String
*
* */
public static String getRandomStr(int num) {
StringBuffer temp = new StringBuffer();
Random rand = new Random();
for (int i = 0; i < num; i++) {
temp.append(rand.nextInt(10));
}
return temp.toString();
}
}
| 18.44697
| 66
| 0.576797
|
4986ceb5904dfdb6a537257372635e45f927fea5
| 873
|
package demo;
import org.junit.jupiter.api.Test;
import org.rapidpm.frp.reactive.CompletableFutureQueue;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class DemoCompletableFutureQueue {
@Test
void test001() {
Function<Integer, CompletableFuture<Integer>> f = CompletableFutureQueue
.<Integer, Integer>define((a) -> a + 10)
.thenCombineAsync((b) -> b + 20)
.thenCombineAsync((c) -> c + 30)
.resultFunction();
f.apply(1)
.thenAcceptAsync(System.out::println)
.join();
}
@Test
void test002() {
CompletableFutureQueue
.<Integer, Integer>define((a) -> a + 10)
.thenCombineAsync((b) -> b + 20)
.thenCombineAsync((c) -> c + 30)
.resultFunction()
.apply(1)
.thenAcceptAsync(System.out::println)
.join();
}
}
| 23.594595
| 76
| 0.628866
|
79b0e749f4673f74ded5cb8be42a46e0d190355e
| 1,392
|
package com.zhtkj.jt808.scheduler;
import java.util.Iterator;
import java.util.Map.Entry;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.zhtkj.jt808.mapper.CarRuntimeMapper;
import com.zhtkj.jt808.server.SessionManager;
import com.zhtkj.jt808.vo.Session;
import io.netty.channel.Channel;
@Component
public class TerminalScheduler {
@Autowired
private CarRuntimeMapper carRuntimeMapper;
/**
* @Description: 移除没有持续上报数据的终端session, 并更改车辆实时表的车辆状态为离线状态
* @return void
*/
@Scheduled(cron = "0 6/6 * * * ?")
public void removeIdleSession() {
Iterator<Entry<String, Session>> iterator =
SessionManager.getInstance().getSessionMap().entrySet().iterator();
DateTime idleTime = DateTime.now().minusMinutes(6);
while (iterator.hasNext()) {
Session session = iterator.next().getValue();
DateTime lastCommunicateTime = session.getLastCommunicateTime();
if (lastCommunicateTime == null || lastCommunicateTime.isBefore(idleTime)) {
Channel channel = session.getChannel();
if (channel.isOpen()) {
channel.close();
}
iterator.remove();
}
}
carRuntimeMapper.setCarOfflineState(idleTime.toString("yyyy-MM-dd HH:mm:ss"));
}
}
| 29.617021
| 81
| 0.721983
|
ae32c2ab164ac70cef0d0d06fe4aac0e4637339b
| 377
|
package com.huawei.classroom.student.h06;
/**
* @author super
*/
public class RifleSoldier extends Soldier {
public RifleSoldier(int x, int y) {
super(Param.SOLDIER_LV, Param.SOLDIER_RIFLE_AP, Param.SOLDIER_RIFLE_AR, x, y);
}
@Override
public int getAttackPower(GameObject obj) {
if(obj instanceof Dog) {
return 1000;
}
return -1;
}
}
| 17.952381
| 81
| 0.668435
|
f8dccac7514c6d0a2c474f529ac3363b6324d6ec
| 340
|
package on2020.on2020_Chapter1.The_3n_plus_1_problem;
import net.egork.chelper.tester.NewTester;
import org.junit.Assert;
import org.junit.Test;
public class Main {
@Test
public void test() throws Exception {
if (!NewTester.test("test/on2020/on2020_Chapter1/The_3n_plus_1_problem/The 3n plus 1 problem.json"))
Assert.fail();
}
}
| 22.666667
| 102
| 0.773529
|
61f14bb75c4b4095fceb4b43d1b2ff0373491e0f
| 264
|
package com.ryo.metadata.core.service;
import com.ryo.metadata.core.util.singleton.Singleton;
/**
*
* @author bbhou
* @date 2017/8/2
*/
public interface IdGenerator extends Singleton {
/**
* 生成ID
* @return 标识字符串
*/
String genId();
}
| 13.894737
| 54
| 0.632576
|
19393bb19bf4d7c64f8c19d9f277524a4203016f
| 3,742
|
/*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package gov.nasa.arc.spife.core.plan.rules.view;
import gov.nasa.ensemble.core.activityDictionary.ActivityDictionary;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.dictionary.ERule;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
public class PlanRulesContentProvider implements ITreeContentProvider {
private static final Object[] NO_CHILDREN = new Object[] {};
private EPlanElement currentPlanElement = null;
private final RuleGroup rootGroup = new RuleGroup("All Rules");
private final Object[] rootObjects = new Object[] { rootGroup };
private final Map<ERule, RuleGroup> ruleToGroup = new HashMap<ERule, RuleGroup>();
public PlanRulesContentProvider() {
List<ERule> rules = ActivityDictionary.getInstance().getDefinitions(ERule.class);
for (ERule rule : rules) {
List<String> categoryPath = rule.getPath();
RuleGroup group = rootGroup;
int i = categoryPath.size() - 1;
for (String category : categoryPath) {
if (i-- <= 0) {
break;
}
group = group.getGroupForLabel(category);
}
group.getRules().add(rule);
ruleToGroup.put(rule, group);
}
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof EPlanElement) {
currentPlanElement = (EPlanElement) newInput;
}
}
@Override
public void dispose() {
if (currentPlanElement != null) {
currentPlanElement = null;
}
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof RuleGroup) {
RuleGroup group = (RuleGroup)parentElement;
Collection<RuleGroup> groups = group.getGroups().values();
List<ERule> rules = group.getRules();
Object[] children = new Object[groups.size() + rules.size()];
int i = 0;
for (RuleGroup child : groups) {
children[i++] = child;
}
for (ERule child : rules) {
children[i++] = child;
}
return children;
}
return NO_CHILDREN;
}
@Override
public Object getParent(Object element) {
if (element instanceof RuleGroup) {
RuleGroup group = (RuleGroup)element;
return group.getParent();
}
if (element instanceof ERule) {
ERule rule = (ERule) element;
RuleGroup group = ruleToGroup.get(rule);
return group;
}
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof RuleGroup) {
RuleGroup group = (RuleGroup)element;
if (!group.getGroups().isEmpty()) {
return true;
}
if (!group.getRules().isEmpty()) {
return true;
}
}
return false;
}
@Override
public Object[] getElements(Object inputElement) {
if (inputElement == currentPlanElement) {
return rootObjects;
}
return NO_CHILDREN;
}
}
| 29.464567
| 83
| 0.686264
|
dba799a01f891003ba66de2d998534c48d8bc564
| 1,871
|
package org.cloudfoundry.identity.uaa.health;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
/**
* Simple controller that just returns "ok" in a request body for the purposes
* of monitoring health of the application. It also registers a shutdown hook
* and returns "stopping" and a 503 when the process is shutting down.
*/
@Controller
public class HealthzEndpoint {
private static Logger logger = LoggerFactory.getLogger(HealthzEndpoint.class);
private volatile boolean stopping = false;
public HealthzEndpoint(
@Value("${uaa.shutdown.sleep:10000}") final long sleepTime,
final Runtime runtime) {
Thread shutdownHook = new Thread(() -> {
stopping = true;
logger.warn("Shutdown hook received, future requests to this endpoint will return 503");
try {
if (sleepTime > 0) {
logger.debug("Healthz is sleeping shutdown thread for " + sleepTime + " ms.");
Thread.sleep(sleepTime);
}
} catch (InterruptedException e) {
logger.warn("Shutdown sleep interrupted.", e);
}
});
runtime.addShutdownHook(shutdownHook);
}
@GetMapping("/healthz")
@ResponseBody
public String getHealthz(HttpServletResponse response) {
if (stopping) {
logger.debug("Received /healthz request during shutdown. Returning 'stopping'");
response.setStatus(503);
return "stopping\n";
} else {
return "ok\n";
}
}
}
| 35.980769
| 100
| 0.652058
|
25270032f320a10e27641b43ecf8427468b73e15
| 428
|
package com.ssm.security.core.validate.code.sms;
import org.springframework.stereotype.Component;
/**
* 发送短信,默认实现
*
* @author 贾令强
* @since 2018/7/17 21:47
*/
@Component // 重构后必须在这里加注解声明bean,不能在类ValidateCodeConfigBean中new
public class DefaultSmsCodeSenderImpl implements SmsCodeSender {
@Override
public void send(String mobile, String code) {
System.out.println("向手机" + mobile + "发送验证码" + code);
}
}
| 23.777778
| 64
| 0.719626
|
86f78c860399425c656d9c23a52f6e39aca4d920
| 2,567
|
/*
* MIT License
*
* Copyright (c) 2020 SvenAugustus
*
* 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 xyz.flysium.photon.c050_gc;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 从数据库中读取信用数据,套用模型,并把结果进行记录和传输
*
* <li>
* -Xms200M -Xmx200M -XX:+PrintGC
* </li>
*
* @author Sven Augustus
*/
public class T02_FullGC_Problem01 {
private static class CardInfo {
BigDecimal price = new BigDecimal("0.0");
String name = "张三";
int age = 5;
Date birthdate = new Date();
public void m() {
}
}
private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(50,
new ThreadPoolExecutor.DiscardOldestPolicy());
public static void main(String[] args) throws Exception {
executor.setMaximumPoolSize(50);
for (; ; ) {
modelFit();
Thread.sleep(100);
}
}
private static void modelFit() {
List<CardInfo> taskList = getAllCardInfo();
taskList.forEach(info -> {
// do something
// do sth with info
executor.scheduleWithFixedDelay(info::m, 2, 3, TimeUnit.SECONDS);
});
}
private static List<CardInfo> getAllCardInfo() {
List<CardInfo> taskList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
CardInfo ci = new CardInfo();
taskList.add(ci);
}
return taskList;
}
}
| 28.842697
| 97
| 0.70783
|
825b12575342e277f2d940498b369859179db871
| 1,187
|
package org.getalp.dbnary.languages.spa;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.getalp.dbnary.languages.AbstractGlossFilter;
import org.getalp.dbnary.StructuredGloss;
public class GlossFilter extends AbstractGlossFilter {
public static final String senseNumRegExp = "\\d+(?:[abcdefghijklmn][iv]*)?";
public static final String simpleNumListFilter =
"^\\s*(" + senseNumRegExp + "(?:\\s*[\\,\\-–]\\s*" + senseNumRegExp + ")*)\\s*$";
public static final Pattern simpleNumListPattern = Pattern.compile(simpleNumListFilter);
public static final Matcher simpleNumListMatcher = simpleNumListPattern.matcher("");
public StructuredGloss extractGlossStructure(String rawGloss) {
if (null == rawGloss) {
return null;
}
// ? is frequently found in translation glosses in Spanish and should be ignored as it leads
// to incorrect enhancement
if ("?".equals(rawGloss.trim())) {
return null;
}
simpleNumListMatcher.reset(rawGloss);
if (simpleNumListMatcher.matches()) {
return new StructuredGloss(simpleNumListMatcher.group(1), null);
}
return new StructuredGloss(null, rawGloss);
}
}
| 35.969697
| 96
| 0.717776
|
f531588a9751c9c7dd3adf56eb1e31612049dc07
| 119
|
package jdbc;
import java.util.List;
public interface UserService {
void save(User user);
List<User> getUsers();
}
| 13.222222
| 30
| 0.731092
|
f7c15e3b0df1b1d3c620faecf06f2a05771f5555
| 31
|
module code.sample.java.ten {
}
| 15.5
| 29
| 0.741935
|
51ff1d03133fbbdf8eeaa96844e50bb911b238f6
| 3,464
|
package com.google.android.gms.internal.ads;
/* renamed from: com.google.android.gms.internal.ads.Xb */
final class C9227Xb {
/* renamed from: a */
private final Object f21913a;
/* renamed from: b */
private volatile int f21914b;
/* renamed from: c */
private volatile long f21915c;
private C9227Xb() {
this.f21913a = new Object();
this.f21914b = C9248Yb.f21937a;
this.f21915c = 0;
}
/* JADX WARNING: Code restructure failed: missing block: B:20:0x004e, code lost:
return;
*/
/* renamed from: a */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void mo28690a() {
/*
r7 = this;
com.google.android.gms.common.util.Clock r0 = com.google.android.gms.ads.internal.zzk.zzln()
long r0 = r0.mo27935b()
java.lang.Object r2 = r7.f21913a
monitor-enter(r2)
int r3 = r7.f21914b // Catch:{ all -> 0x0052 }
int r4 = com.google.android.gms.internal.ads.C9248Yb.f21939c // Catch:{ all -> 0x0052 }
if (r3 != r4) goto L_0x002f
long r3 = r7.f21915c // Catch:{ all -> 0x0052 }
com.google.android.gms.internal.ads.zzacj<java.lang.Long> r5 = com.google.android.gms.internal.ads.zzacu.f23943He // Catch:{ all -> 0x0052 }
com.google.android.gms.internal.ads.zzacr r6 = com.google.android.gms.internal.ads.zzyt.m31536e() // Catch:{ all -> 0x0052 }
java.lang.Object r5 = r6.mo29599a(r5) // Catch:{ all -> 0x0052 }
java.lang.Long r5 = (java.lang.Long) r5 // Catch:{ all -> 0x0052 }
long r5 = r5.longValue() // Catch:{ all -> 0x0052 }
long r3 = r3 + r5
int r5 = (r3 > r0 ? 1 : (r3 == r0 ? 0 : -1))
if (r5 > 0) goto L_0x002f
int r0 = com.google.android.gms.internal.ads.C9248Yb.f21937a // Catch:{ all -> 0x0052 }
r7.f21914b = r0 // Catch:{ all -> 0x0052 }
L_0x002f:
monitor-exit(r2) // Catch:{ all -> 0x0052 }
com.google.android.gms.common.util.Clock r0 = com.google.android.gms.ads.internal.zzk.zzln()
long r0 = r0.mo27935b()
java.lang.Object r3 = r7.f21913a
monitor-enter(r3)
int r2 = r7.f21914b // Catch:{ all -> 0x004f }
r4 = 2
if (r2 == r4) goto L_0x0042
monitor-exit(r3) // Catch:{ all -> 0x004f }
return
L_0x0042:
r2 = 3
r7.f21914b = r2 // Catch:{ all -> 0x004f }
int r2 = r7.f21914b // Catch:{ all -> 0x004f }
int r4 = com.google.android.gms.internal.ads.C9248Yb.f21939c // Catch:{ all -> 0x004f }
if (r2 != r4) goto L_0x004d
r7.f21915c = r0 // Catch:{ all -> 0x004f }
L_0x004d:
monitor-exit(r3) // Catch:{ all -> 0x004f }
return
L_0x004f:
r0 = move-exception
monitor-exit(r3) // Catch:{ all -> 0x004f }
throw r0
L_0x0052:
r0 = move-exception
monitor-exit(r2) // Catch:{ all -> 0x0052 }
throw r0
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.ads.C9227Xb.mo28690a():void");
}
/* synthetic */ C9227Xb(C9206Wb wb) {
this();
}
}
| 41.238095
| 156
| 0.535797
|
f818d9e2e20df583888bbabf337bebf4e03a70b8
| 2,593
|
// Copyright Eagle Legacy Modernization LLC, 2010-date
// Original author: Steven A. O'Hara, Oct 7, 2012
package com.eagle.programmar.COBOL.Statements;
import com.eagle.parsers.EagleFileReader;
import com.eagle.parsers.EagleLineReader;
import com.eagle.programmar.COBOL.COBOL_AbstractStatement;
import com.eagle.programmar.COBOL.Symbols.COBOL_Identifier_Reference;
import com.eagle.programmar.COBOL.Terminals.COBOL_Keyword;
import com.eagle.programmar.COBOL.Terminals.COBOL_Literal;
import com.eagle.tokens.TerminalToken;
import com.eagle.tokens.TokenChooser;
import com.eagle.tokens.TokenList;
import com.eagle.tokens.TokenSequence;
public class COBOL_CopyStatement extends COBOL_AbstractStatement
{
public COBOL_Keyword COPY = new COBOL_Keyword("COPY");
public COBOL_FileNameOrLiteral fileName;
public @OPT COBOL_CopyReplacing replacing;
public static class COBOL_CopyReplacing extends TokenSequence
{
public COBOL_Keyword REPLACING = new COBOL_Keyword("REPLACING");
public TokenList<COBOL_CopyReplace> replacements;
public static class COBOL_CopyReplace extends TokenSequence
{
public COBOL_Identifier_Reference from;
public COBOL_Keyword BY = new COBOL_Keyword("BY");
public COBOL_Identifier_Reference to;
}
}
public static class COBOL_FileNameOrLiteral extends TokenChooser
{
public @CHOICE COBOL_FileName fileNmae;
public @CHOICE COBOL_Literal literal;
}
public static class COBOL_FileName extends TerminalToken
{
private String id;
@Override
public boolean parse(EagleFileReader lines)
{
if (findStart(lines) == FOUND.EOF) return false;
EagleLineReader rec = lines.get(_currentLine);
int recLen = rec.length();
char ch = rec.charAt(_currentChar);
if (Character.isLetter(ch))
{
int endChar = _currentChar;
while (true)
{
endChar++;
if (endChar >= recLen) break;
ch = rec.charAt(endChar);
if (!Character.isLetterOrDigit(ch) && ch != '-' && ch != '.') break;
if (ch == '.' && (endChar+1 == recLen || !Character.isLetterOrDigit(rec.charAt(endChar+1)))) break;
}
id = rec.substring(_currentChar, endChar);
foundIt(_currentLine, endChar - 1);
return true;
}
return false;
}
@Override
public String toString()
{
return id;
}
@Override
public void setValue(String val)
{
id = val;
}
@Override
public String showString()
{
return "Filename";
}
@Override
public String description()
{
return "A filename.";
}
@Override
public String getDisplayStyleName()
{
return "identifier";
}
}
}
| 24.932692
| 104
| 0.725415
|
e058ad699dd380efde16f0ea834dce9f3ea4fd30
| 3,104
|
/*
assume that the first line of the file contain the names of the
attributes of the relation. each subsequent line represents 1
tuple of the relation. also assume that the fields of each line
is delimited by tabs ("\t")
*/
import qp.utils.Attribute;
import qp.utils.Schema;
import qp.utils.Tuple;
import java.io.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
public class ConvertTxtToTbl {
private static String propPath = "./src/resources/common.properties";
public static void main(String[] args) throws IOException {
// check the arguments
if (args.length != 1) {
System.out.println("usage: java ConvertTxtToTbl <tablename> \n creats <tablename>.tbl files");
System.exit(1);
}
String dir = getDBPath();
String tblname = args[0];
String txtfile = dir + args[0] + ".txt";
String mdfile = dir + tblname + ".md";
String tblfile = dir + tblname + ".tbl";
/** open the input and output streams **/
BufferedReader in = new BufferedReader(new FileReader(txtfile));
ObjectOutputStream outtbl = new ObjectOutputStream(new FileOutputStream(tblfile));
/** First Line is METADATA **/
int linenum = 0;
String line;
Schema schema = null;
try {
ObjectInputStream ins = new ObjectInputStream(new FileInputStream(mdfile));
schema = (Schema) ins.readObject();
} catch (ClassNotFoundException ce) {
System.out.println("class not found exception --- error in schema object file");
System.exit(1);
}
boolean flag = false;
StringTokenizer tokenizer;
while ((line = in.readLine()) != null) {
linenum++;
tokenizer = new StringTokenizer(line);
ArrayList<Object> data = new ArrayList<>();
int attrIndex = 0;
while (tokenizer.hasMoreElements()) {
String dataElement = tokenizer.nextToken();
int datatype = schema.typeOf(attrIndex);
if (datatype == Attribute.INT) {
data.add(Integer.valueOf(dataElement));
} else if (datatype == Attribute.REAL) {
data.add(Float.valueOf(dataElement));
} else if (datatype == Attribute.STRING) {
data.add(dataElement);
} else {
System.err.println("Invalid data type");
System.exit(1);
}
attrIndex++;
}
Tuple tuple = new Tuple(data);
outtbl.writeObject(tuple);
}
outtbl.close();
in.close();
}
public static String getDBPath() {
try (InputStream input = new FileInputStream(propPath)) {
Properties prop = new Properties();
prop.load(input);
return prop.getProperty("db.path");
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
}
| 33.376344
| 106
| 0.569588
|
84b6e6212b51809341fb7de2943a2227d9c106aa
| 2,768
|
/*
* Copyright 2021 The University of Manchester
*
* 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.acuity.visualisations.model.output.entities;
import com.acuity.visualisations.model.acuityfield.AcuityField;
import com.acuity.visualisations.model.acuityfield.AcuityFieldTransformation;
import com.acuity.visualisations.data.util.Util;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.time.LocalDateTime;
@Getter
@Setter
public class MedDosDisc extends TimestampedEntity {
private String patientGuid;
private Integer ipDisc;
@AcuityField(transform = AcuityFieldTransformation.TERMINATING_EVENT_23_59_59)
private LocalDateTime ipdcDate;
private String ipdcReas;
private String ipdcSpec;
private String drugName;
private String subject;
private String part;
private String subjectDecisionSpec;
private String subjectDecisionSpecOther;
public MedDosDisc() {
initId();
}
@Override
public String uniqueFieldsToString() {
return new ToStringBuilder(this, Util.getToStringStyle()).
append("subject", subject).
append("part", part).
append("drugName", drugName).
append("ipdcDate", ipdcDate).
toString();
}
@Override
public String allFieldsToString() {
return new ToStringBuilder(this, Util.getToStringStyle()).
append("subject", subject).
append("part", part).
append("drugName", drugName).
append("ipdcDate", ipdcDate).
append("ipdcReas", ipdcReas).
append("ipdcSpec", ipdcSpec).
append("ipDisc", ipDisc).
append("subjectDecisionSpec", subjectDecisionSpec).
append("subjectDecisionSpecOther", subjectDecisionSpecOther).
toString();
}
/**
* RCT-4146: Dose data standardisation should happen in one place
* DISCARD EVENTS WITHOUT TIMINGS
* Discard all discontinuation events where the dateTime is null.
*
* @return
*/
@Override
public boolean isValid() {
return ipdcDate != null;
}
}
| 31.816092
| 82
| 0.672327
|
b3f9a609b40287a1ff1e01a3cc9aecb8888b31ae
| 1,015
|
package thredds.crawlabledataset.s3;
import java.util.Date;
import java.util.Objects;
/**
* Summary metadata for the "virtual directory" at the specified Amazon S3 URI
*
* @author jonescc
* @since 2016/09/12
*/
public class ThreddsS3Directory extends AbstractThreddsS3Metadata {
public ThreddsS3Directory(S3URI s3uri) {
super(s3uri);
}
//////////////////////////////////////// Object ////////////////////////////////////////
@Override
public String toString() {
return String.format("ThreddsS3Directory{'%s'}", getS3uri());
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other == null || getClass() != other.getClass()) {
return false;
}
ThreddsS3Directory that = (ThreddsS3Directory) other;
return Objects.equals(this.getS3uri(), that.getS3uri());
}
@Override
public int hashCode() {
return getS3uri().hashCode();
}
}
| 24.756098
| 92
| 0.575369
|
92668aab29d7d156fe14618abe1345cc9cfebedb
| 1,163
|
package com.zihler.wiki.adapters.presentation.rest.presenters.outputs;
import com.zihler.wiki.adapters.presentation.rest.viewmodels.WikiPageViewModel;
import com.zihler.wiki.application.outbound_ports.documents.WikiPageDocument;
import com.zihler.wiki.domain.values.ReferenceTag;
import com.zihler.wiki.domain.values.ReferencedWikiPages;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
public class WikiPageOutput {
private WikiPageDocument document;
public WikiPageOutput(WikiPageDocument document) {
this.document = document;
}
public WikiPageViewModel dto() {
return new WikiPageViewModel(
document.referenceTag().toString(),
document.title().toString(),
document.body().toString(),
toReferenceTagStrings(document.referencedWikiPages())
);
}
private Set<String> toReferenceTagStrings(ReferencedWikiPages referencedWikiPages) {
return referencedWikiPages
.getReferencedWikiPages()
.stream()
.map(ReferenceTag::toString)
.collect(toSet());
}
}
| 32.305556
| 88
| 0.690456
|
87bf6a1022c31ac687fd301b7ce527b5c4725c91
| 7,286
|
/*
* Copyright 2014-2020 Lukas Krejci
* and other contributors as indicated by the @author tags.
*
* 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.revapi.reporter.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.Deque;
import javax.annotation.Nonnull;
import org.revapi.AnalysisContext;
import org.revapi.Difference;
import org.revapi.DifferenceSeverity;
import org.revapi.Element;
import org.revapi.Report;
import org.revapi.Reporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class can be used as a base class for reporters that want to write the reports into the files. It provides
* some basic features like difference filtering based on severity, the ability to specify the file to write to
* (including "out" and "err" as special file names for standard output and standard error) and whether to
* overwrite or append to an existing file.
*/
public abstract class AbstractFileReporter implements Reporter {
private static final Logger LOG = LoggerFactory.getLogger(AbstractFileReporter.class);
protected DifferenceSeverity minLevel;
protected PrintWriter output;
protected boolean shouldClose;
protected AnalysisContext analysis;
/**
* For testing.
*
* @param wrt the output writer
*/
protected void setOutput(PrintWriter wrt) {
this.output = wrt;
this.shouldClose = true;
}
/**
* Subclasses should write the reports to the {@link #output} in this method. This method MUST NOT close the
* output though.
*/
protected abstract void flushReports() throws IOException;
@Override
public void initialize(@Nonnull AnalysisContext analysis) {
if (this.analysis != null) {
try {
flushReports();
} catch (IOException e) {
throw new IllegalStateException("Failed to output previous analysis report.");
}
}
this.analysis = analysis;
String minLevel = analysis.getConfiguration().get("minSeverity").asString();
String output = analysis.getConfiguration().get("output").asString();
output = "undefined".equals(output) ? "out" : output;
boolean append = analysis.getConfiguration().get("append").asBoolean(false);
this.minLevel = "undefined".equals(minLevel) ? DifferenceSeverity.POTENTIALLY_BREAKING :
DifferenceSeverity.valueOf(minLevel);
OutputStream out;
switch (output) {
case "out":
out = System.out;
break;
case "err":
out = System.err;
break;
default:
File f = new File(output);
if (f.exists() && !f.canWrite()) {
LOG.warn(
"The configured file, '" + f.getAbsolutePath() + "' is not a writable." +
" Defaulting the output to standard output.");
out = System.out;
} else {
File parent = f.getParentFile();
if (!parent.exists()) {
if (!parent.mkdirs()) {
LOG.warn("Failed to create directory structure to write to the configured output file '" +
f.getAbsolutePath() + "'. Defaulting the output to standard output.");
out = System.out;
break;
}
}
try {
out = new FileOutputStream(output, append);
} catch (FileNotFoundException e) {
LOG.warn("Failed to create the configured output file '" + f.getAbsolutePath() + "'." +
" Defaulting the output to standard output.", e);
out = System.out;
}
}
}
shouldClose = out != System.out && out != System.err;
this.output = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
}
/**
* This is the default implementation of the report method that does the initial filtering based on the configured
* minimum severity and then delegates to {@link #doReport(Report)} if the reporting should really be performed.
* @param report the report with the differences
*/
@Override
public void report(@Nonnull Report report) {
LOG.trace("Received report {}", report);
if (report.getDifferences().isEmpty()) {
return;
}
DifferenceSeverity maxReportedSeverity = DifferenceSeverity.NON_BREAKING;
for (Difference d : report.getDifferences()) {
for (DifferenceSeverity c : d.classification.values()) {
if (c.compareTo(maxReportedSeverity) > 0) {
maxReportedSeverity = c;
}
}
}
if (maxReportedSeverity.compareTo(minLevel) < 0) {
return;
}
doReport(report);
}
/**
* The report contains differences of at least the configured severity. This method is called from
* {@link #report(Report)} by default.
*/
protected abstract void doReport(Report report);
@Override
public void close() throws IOException {
flushReports();
if (shouldClose) {
output.close();
}
}
/**
* @return a comparator that can be used to sort the reports in the order of the compared elements.
*/
protected Comparator<Report> getReportsByElementOrderComparator() {
return (r1, r2) -> {
Element r1El = r1.getOldElement() == null ? r1.getNewElement() : r1.getOldElement();
Element r2El = r2.getOldElement() == null ? r2.getNewElement() : r2.getOldElement();
Deque<Element> r1Ancestry = new ArrayDeque<>();
Deque<Element> r2Ancestry = new ArrayDeque<>();
while (r1El != null) {
r1Ancestry.push(r1El);
r1El = r1El.getParent();
}
while (r2El != null) {
r2Ancestry.push(r2El);
r2El = r2El.getParent();
}
while (!r1Ancestry.isEmpty() && !r2Ancestry.isEmpty()) {
int order = r1Ancestry.pop().compareTo(r2Ancestry.pop());
if (order != 0) {
return order;
}
}
return r1Ancestry.size() - r2Ancestry.size();
};
}
}
| 34.367925
| 118
| 0.601839
|
72dc2e2551bb8eb0bc389adaa2e358565b1b6d6b
| 11,815
|
package io.swagger.parser;
import io.swagger.models.ModelImpl;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.parser.util.RemoteUrl;
import io.swagger.parser.util.SwaggerDeserializationResult;
import io.swagger.util.Json;
import mockit.Expectations;
import mockit.Mocked;
import org.junit.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class NetworkReferenceTest {
@Mocked
public RemoteUrl remoteUrl = new RemoteUrl();
private static String issue_323_yaml, issue_323_events_yaml, issue_323_paging_yaml, issue_323_bar_yaml;
private static String issue_328_yaml, issue_328_events_yaml, issue_328_paging_yaml, issue_328_bar_yaml;
private static String issue_330_yaml, issue_330_users_yaml, issue_330_paging_yaml, issue_330_entities_yaml;
private static String issue_335_json, issue_335_bar_json;
private static String issue_407_json;
private static String issue_411_server, issue_411_components;
static {
try {
issue_323_yaml = readFile("src/test/resources/nested-file-references/issue-323.yaml");
issue_323_events_yaml = readFile("src/test/resources/nested-file-references/eventsCase9.yaml");
issue_323_paging_yaml = readFile("src/test/resources/nested-file-references/common/pagingWithFolderRef.yaml");
issue_323_bar_yaml = readFile("src/test/resources/nested-file-references/common/common2/bar.yaml");
issue_328_yaml = readFile("src/test/resources/nested-file-references/issue-328.yaml");
issue_328_events_yaml = readFile("src/test/resources/nested-file-references/issue-328-events.yaml");
issue_328_paging_yaml = readFile("src/test/resources/nested-file-references/common/issue-328-paging.yaml");
issue_328_bar_yaml = readFile("src/test/resources/nested-file-references/common/common2/issue-328-bar.yaml");
issue_330_yaml = readFile("src/test/resources/nested-network-references/issue-330.yaml");
issue_330_paging_yaml = readFile("src/test/resources/nested-network-references/common/issue-330-paging.yaml");
issue_330_users_yaml = readFile("src/test/resources/nested-network-references/common/issue-330-users.yaml");
issue_330_entities_yaml = readFile("src/test/resources/nested-network-references/common/issue-330-entities.yaml");
issue_335_json = readFile("src/test/resources/nested-file-references/issue-335.json");
issue_335_bar_json = readFile("src/test/resources/nested-file-references/issue-335-bar.json");
issue_407_json = readFile("src/test/resources/petstore.json");
issue_411_server = readFile("src/test/resources/nested-network-references/issue-411-server.yaml");
issue_411_components = readFile("src/test/resources/nested-network-references/issue-411-remote2.yaml");
}
catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void testIssue323() throws Exception {
new Expectations() {{
remoteUrl.urlToString("http://localhost:8080/nested-file-references/issue-323.yaml", new ArrayList<AuthorizationValue>());
result = issue_323_yaml;
remoteUrl.urlToString("http://localhost:8080/nested-file-references/eventsCase9.yaml", new ArrayList<AuthorizationValue>());
result = issue_323_events_yaml;
remoteUrl.urlToString("http://localhost:8080/nested-file-references/common/pagingWithFolderRef.yaml", new ArrayList<AuthorizationValue>());
result = issue_323_paging_yaml;
remoteUrl.urlToString("http://localhost:8080/nested-file-references/common/common2/bar.yaml", new ArrayList<AuthorizationValue>());
result = issue_323_bar_yaml;
}};
SwaggerDeserializationResult result = new SwaggerParser().readWithInfo("http://localhost:8080/nested-file-references/issue-323.yaml", null, true);
assertNotNull(result.getSwagger());
Swagger swagger = result.getSwagger();
assertNotNull(swagger.getPath("/events"));
assertNotNull(swagger.getDefinitions().get("StatusResponse"));
assertNotNull(swagger.getDefinitions().get("Paging"));
assertNotNull(swagger.getDefinitions().get("Foobar"));
}
@Test
public void testIssue328() throws Exception {
new Expectations() {{
remoteUrl.urlToString("http://localhost:8080/resources/swagger/issue-328.yaml", new ArrayList<AuthorizationValue>());
result = issue_328_yaml;
remoteUrl.urlToString("http://localhost:8080/resources/swagger/issue-328-events.yaml", new ArrayList<AuthorizationValue>());
result = issue_328_events_yaml;
remoteUrl.urlToString("http://localhost:8080/resources/swagger/common/issue-328-paging.yaml", new ArrayList<AuthorizationValue>());
result = issue_328_paging_yaml;
remoteUrl.urlToString("http://localhost:8080/resources/swagger/common/common2/issue-328-bar.yaml", new ArrayList<AuthorizationValue>());
result = issue_328_bar_yaml;
}};
SwaggerDeserializationResult result = new SwaggerParser().readWithInfo("http://localhost:8080/resources/swagger/issue-328.yaml", null, true);
assertNotNull(result.getSwagger());
Swagger swagger = result.getSwagger();
assertNotNull(swagger.getPath("/events"));
assertNotNull(swagger.getDefinitions().get("StatusResponse"));
assertNotNull(swagger.getDefinitions().get("Paging"));
assertNotNull(swagger.getDefinitions().get("Foobar"));
}
@Test
public void testIssue330() throws Exception {
new Expectations() {{
remoteUrl.urlToString("http://server1/resources/swagger.yaml", new ArrayList<AuthorizationValue>());
result = issue_330_yaml;
remoteUrl.urlToString("http://server1/resources/common/paging.yaml", new ArrayList<AuthorizationValue>());
result = issue_330_paging_yaml;
remoteUrl.urlToString("http://server1/resources/common/users.yaml", new ArrayList<AuthorizationValue>());
result = issue_330_users_yaml;
remoteUrl.urlToString("http://server2/resources/common/entities.yaml", new ArrayList<AuthorizationValue>());
result = issue_330_entities_yaml;
}};
SwaggerDeserializationResult result = new SwaggerParser().readWithInfo("http://server1/resources/swagger.yaml", null, true);
assertNotNull(result.getSwagger());
Swagger swagger = result.getSwagger();
assertNotNull(swagger.getPath("/events"));
assertNotNull(swagger.getDefinitions().get("Address"));
assertNotNull(swagger.getDefinitions().get("Paging"));
assertNotNull(swagger.getDefinitions().get("users"));
assertNotNull(swagger.getDefinitions().get("Phone"));
}
@Test
public void testIssue335() throws Exception {
new Expectations() {{
remoteUrl.urlToString("http://server1/resources/swagger.json", new ArrayList<AuthorizationValue>());
result = issue_335_json;
remoteUrl.urlToString("http://server1/resources/Bar.json", new ArrayList<AuthorizationValue>());
result = issue_335_bar_json;
}};
SwaggerDeserializationResult result = new SwaggerParser().readWithInfo("http://server1/resources/swagger.json", null, true);
Swagger swagger = result.getSwagger();
assertNotNull(swagger);
assertNotNull(swagger.getDefinitions());
assertNotNull(swagger.getDefinitions().get("BarData"));
assertNotNull(swagger.getDefinitions().get("BarSettingsRequest"));
}
@Test
public void testPathReference() throws Exception {
new Expectations() {{
remoteUrl.urlToString("http://petstore.swagger.io/v2/swagger.json", new ArrayList<AuthorizationValue>());
result = issue_407_json;
}};
SwaggerParser parser = new SwaggerParser();
String yaml =
"swagger: '2.0'\n" +
"info:\n" +
" description: |\n" +
" version: 1.0.0\n" +
" title: testing\n" +
"paths:\n" +
" /foo:\n" +
" $ref: 'http://petstore.swagger.io/v2/swagger.json#/paths/~1pet'\n" +
" /bar:\n" +
" $ref: 'http://petstore.swagger.io/v2/swagger.json#/paths/~1pet'\n" +
"schemes:\n" +
" - https\n" +
" - http";
final SwaggerDeserializationResult result = parser.readWithInfo(yaml);
Assert.assertNotNull(result.getSwagger());
assertTrue(result.getMessages().size() == 0);
assertTrue(result.getSwagger().getDefinitions().size() == 3);
}
@Test
public void testIssue411() throws Exception {
final List< AuthorizationValue > auths = new ArrayList<>();
AuthorizationValue auth = new AuthorizationValue("Authorization", "OMG_SO_SEKR3T", "header");
auths.add(auth);
new Expectations() {{
remoteUrl.urlToString("http://remote1/resources/swagger.json", auths);
result = issue_411_server;
remoteUrl.urlToString("http://remote2/resources/foo", auths);
result = issue_411_components;
}};
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult result = parser.readWithInfo("http://remote1/resources/swagger.json", auths, true);
Json.prettyPrint(result);
Swagger swagger = result.getSwagger();
assertNotNull(swagger.getPath("/health"));
Path health = swagger.getPath("/health");
assertTrue(health.getGet().getParameters().size() == 0);
Object responseRef = health.getGet().getResponses().get("200").getSchema();
assertTrue(responseRef instanceof RefProperty);
RefProperty refProperty = (RefProperty) responseRef;
assertEquals(refProperty.get$ref(), "#/definitions/Success");
assertNotNull(swagger.getDefinitions().get("Success"));
Parameter param = swagger.getPath("/stuff").getGet().getParameters().get(0);
assertEquals(param.getIn(), "query");
assertEquals(param.getName(), "skip");
Response response = swagger.getPath("/stuff").getGet().getResponses().get("200");
assertNotNull(response);
assertTrue(response.getSchema() instanceof StringProperty);
Response error = swagger.getPath("/stuff").getGet().getResponses().get("400");
assertNotNull(error);
Property errorProp = error.getSchema();
assertNotNull(errorProp);
assertTrue(errorProp instanceof RefProperty);
RefProperty errorProperty = (RefProperty) errorProp;
assertEquals(errorProperty.get$ref(), "#/definitions/Error");
assertTrue(swagger.getDefinitions().get("Error") instanceof ModelImpl);
}
static String readFile(String name) throws Exception {
return new String(Files.readAllBytes(new File(name).toPath()), Charset.forName("UTF-8"));
}
}
| 46.884921
| 154
| 0.677105
|
04e54bac8546312134de03980442f00bea72b7cb
| 14,233
|
package com.jcommerce.gwt.client.panels.order;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.jcommerce.gwt.client.ContentWidget;
import com.jcommerce.gwt.client.ModelNames;
import com.jcommerce.gwt.client.PageState;
import com.jcommerce.gwt.client.form.BeanObject;
import com.jcommerce.gwt.client.model.IOrderInfo;
import com.jcommerce.gwt.client.model.IShipping;
import com.jcommerce.gwt.client.model.IShippingArea;
import com.jcommerce.gwt.client.panels.system.Success;
import com.jcommerce.gwt.client.resources.Resources;
import com.jcommerce.gwt.client.service.Condition;
import com.jcommerce.gwt.client.service.Criteria;
import com.jcommerce.gwt.client.service.PagingListService;
import com.jcommerce.gwt.client.service.ReadService;
import com.jcommerce.gwt.client.service.RemoteService;
import com.jcommerce.gwt.client.service.UpdateService;
import com.jcommerce.gwt.client.service.WaitService;
import com.jcommerce.gwt.client.widgets.RadioCellRenderer;
public class OrderShippingPanel extends ContentWidget{
public static interface Constants {
public String OrderShipping_title();
public String OrderShipping_ok();
public String OrderShipping_cancel();
public String OrderShipping_next();
public String OrderShipping_pre();
public String OrderShipping_shippingName();
public String OrderShipping_shippingDesc();
public String OrderShipping_shippingFee();
public String OrderShipping_freeMoney();
public String OrderShipping_insurance();
public String OrderShipping_selectShipping();
}
private static OrderShippingPanel instance = null;
protected State getCurState() {
return (State)curState;
}
@Override
public String getDescription() {
return "cwBasicTextDescription";
}
@Override
public String getName() {
if(getCurState().getIsEdit())
return Resources.constants.OrderShipping_title();
else
return Resources.constants.OrderUser_title();
}
public OrderShippingPanel() {
curState = new State();
}
public static OrderShippingPanel getInstance(){
if (instance == null) {
instance = new OrderShippingPanel();
}
return instance;
}
public static class State extends PageState {
public static final String PKID = "pkId";
public static final String USERID = "userId";
public static final String ISEDIT = "isEdit";
public void setId(String id){
setValue(PKID, id);
}
public String getPkId(){
return (String)getValue(PKID);
}
public void setUserId(String id){
setValue(USERID, id);
}
public String getUserId(){
return (String)getValue(USERID);
}
public void setIsEdit(boolean isEdit){
setValue(ISEDIT, String.valueOf(isEdit));
}
public boolean getIsEdit(){
return Boolean.valueOf((String)getValue(ISEDIT)).booleanValue();
}
@Override
public String getPageClassName() {
return OrderShippingPanel.class.getName();
}
}
BeanObject order;
PagingToolBar toolBar;
RadioGroup rgShipping = new RadioGroup();
ColumnConfig select;
ColumnConfig colShippingFee;
ColumnConfig colFreeMoney;
ColumnModel cm;
Grid<BeanObject> grid;
Button btnNext;
Button btnOk;
Button btnPre;
// List<Double> freeMoneyList = new ArrayList<Double>();
// List<Double> shippingFeeList = new ArrayList<Double>();
// int isReady;
// int size;
@Override
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
Criteria c = new Criteria();
c.addCondition(new Condition(IShipping.ENABLED, Condition.EQUALS, "true"));
BasePagingLoader loader = new PagingListService().getLoader(ModelNames.SHIPPING, c);
final ListStore<BeanObject> store = new ListStore<BeanObject>(loader);
store.addStoreListener(new StoreListener<BeanObject>() {
public void storeDataChanged(StoreEvent<BeanObject> se) {
List<BeanObject> storeData = (List<BeanObject>)se.getStore().getModels();
// freeMoneyList.clear();
// shippingFeeList.clear();
// isReady = 0;
// size = storeData.size() * 2;
for (BeanObject object : storeData) {
RadioCellRenderer rcr = new RadioCellRenderer(rgShipping);
select.setRenderer(rcr);
// RemoteService.getSpecialService().getShippingConfig((String) object.get(IShipping.ID), new AsyncCallback<Map<String, String>>(){
// public void onFailure(Throwable caught) {
// caught.printStackTrace();
// Window.alert("ERROR: "+caught.getMessage());
// }
// public void onSuccess(Map<String, String> result) {
// double freeMoney = Double.parseDouble(result.get("freeMoney"));
// freeMoneyList.add(freeMoney);
// isReady++;
// }
// });
//
// RemoteService.getSpecialService().getOrderFee(getCurState().getPkId(), (String) object.get(IShipping.ID), null, new AsyncCallback<Map<String, Object>>(){
// public void onFailure(Throwable caught) {
// caught.printStackTrace();
// Window.alert("ERROR: "+caught.getMessage());
// }
// @Override
// public void onSuccess(Map<String, Object> result) {
// double shippingFee = (Double)result.get("shippingFee");
// shippingFeeList.add(shippingFee);
// isReady++;
// }
// });
}
// new WaitService(new Job() {
//
// @Override
// public boolean isReady() {
// if(isReady < size)
// return false;
// else
// return true;
// }
//
// @Override
// public void run() {
// isReady = 0;
// ShippingFeeCellRenderer money = new ShippingFeeCellRenderer("freeMoney");
// ShippingFeeCellRenderer fee = new ShippingFeeCellRenderer("shippingFee");
// money.setFreeMoney(freeMoneyList);
// colFreeMoney.setRenderer(money);
// fee.setShippingFee(shippingFeeList);
// colShippingFee.setRenderer(fee);
// grid.reconfigure(store, cm);
// }
//
// });
}
});
toolBar = new PagingToolBar(50);
toolBar.bind(loader);
List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
select = new ColumnConfig(IShipping.ID, "", 50);
columns.add(select);
ColumnConfig colShippingName = new ColumnConfig(IShipping.NAME, Resources.constants.OrderShipping_shippingName(), 100);
columns.add(colShippingName);
ColumnConfig colShippingDesc = new ColumnConfig(IShipping.DESCRIPTION, Resources.constants.OrderShipping_shippingDesc(), 100);
columns.add(colShippingDesc);
colShippingFee = new ColumnConfig("shippingFee", Resources.constants.OrderShipping_shippingFee(), 100);
columns.add(colShippingFee);
colFreeMoney = new ColumnConfig("freeMoney", Resources.constants.OrderShipping_freeMoney(), 100);
columns.add(colFreeMoney);
ColumnConfig colInsuranceFee = new ColumnConfig(IShipping.INSURE, Resources.constants.OrderShipping_insurance(), 100);
columns.add(colInsuranceFee);
cm = new ColumnModel(columns);
grid = new Grid<BeanObject>(store, cm);
grid.setLoadMask(true);
grid.setBorders(true);
grid.setAutoExpandColumn(IShipping.DESCRIPTION);
ContentPanel panel = new ContentPanel();
panel.setFrame(true);
panel.setCollapsible(true);
panel.setAnimCollapse(false);
panel.setLayout(new FitLayout());
panel.add(grid);
panel.setHeight(350);
//panel.setBottomComponent(toolBar);
panel.setButtonAlign(HorizontalAlignment.CENTER);
btnPre = new Button(Resources.constants.OrderShipping_pre());
btnPre.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
OrderGoodsPanel.State newState = new OrderGoodsPanel.State();
newState.setIsEdit(false);
newState.setId(getCurState().getPkId());
newState.setUserId(getCurState().getUserId());
newState.execute();
}
});
panel.addButton(btnPre);
btnNext = new Button(Resources.constants.OrderShipping_next());
panel.addButton(btnNext);
btnNext.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if(rgShipping.getValue() == null) {
Window.alert(Resources.constants.OrderShipping_selectShipping());
}
else {
updateOrder();
OrderPayPanel.State newState = new OrderPayPanel.State();
newState.setId(getCurState().getPkId());
newState.setUserId(getCurState().getUserId());
newState.setIsEdit(false);
newState.execute();
}
}
});
btnOk = new Button(Resources.constants.OrderShipping_ok());
panel.addButton(btnOk);
btnOk.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if(rgShipping.getValue() == null) {
Window.alert(Resources.constants.OrderShipping_selectShipping());
}
else {
updateOrder();
new WaitService(new WaitService.Job() {
public boolean isReady() {
if(!updateIsReady) {
return false;
}
else {
return true;
}
}
public void run() {
if(!isChange) {
OrderDetailPanel.State newState = new OrderDetailPanel.State();
newState.setId(getCurState().getPkId());
newState.execute();
}
else if(isIncrease) {
Success.State newState = new Success.State();
newState.setMessage(Resources.constants.OrderDetail_orderAmountIncrease());
OrderDetailPanel.State choice1 = new OrderDetailPanel.State();
choice1.setId(getCurState().getPkId());
newState.addChoice(OrderDetailPanel.getInstance().getName(), choice1);
newState.execute();
}
else {
Success.State newState = new Success.State();
newState.setMessage(Resources.constants.OrderDetail_orderAmountDecrease());
OrderDetailPanel.State choice1 = new OrderDetailPanel.State();
choice1.setId(getCurState().getPkId());
newState.addChoice(OrderDetailPanel.getInstance().getName(), choice1);
newState.execute();
}
}
});
}
}
});
panel.addButton(new Button(Resources.constants.OrderShipping_cancel(), new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
cancel();
}
}));
add(panel);
}
@Override
public void refresh() {
toolBar.refresh();
btnOk.setVisible(false);
btnPre.setVisible(false);
btnNext.setVisible(false);
if(getCurState().getIsEdit()) {
btnOk.setVisible(true);
}
else {
btnPre.setVisible(true);
btnNext.setVisible(true);
}
isChange = false;
}
boolean updateIsReady;
boolean isChange = false;
boolean isIncrease = false;
private void updateOrder() {
updateIsReady = false;
final String shippingId = rgShipping.getValue().getValueAttribute();
final String orderId = getCurState().getPkId();
new ReadService().getBean(ModelNames.ORDER, orderId, new ReadService.Listener() {
public void onSuccess(final BeanObject bean) {
new RemoteService().getSpecialService().getOrderFee(getCurState().getPkId(), shippingId, null, new AsyncCallback<Map<String, String>>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
Window.alert("ERROR: "+caught.getMessage());
}
public void onSuccess(Map<String, String> result) {
if(getCurState().getIsEdit()) {
if(bean.getInt(IOrderInfo.PAY_STATUS) == IOrderInfo.PS_PAYED && (Double)bean.get(IOrderInfo.ORDER_AMOUNT) != new Double(result.get("amount"))) {
isChange = true;
if((Double)bean.get(IOrderInfo.ORDER_AMOUNT) > new Double(result.get("amount")))
isIncrease = false;
else {
isIncrease = true;
bean.set(IOrderInfo.PAY_STATUS, IOrderInfo.PS_UNPAYED);
}
}
}
bean.set(IOrderInfo.ORDER_AMOUNT, result.get("amount"));
bean.set(IOrderInfo.SHIPPING_ID, shippingId);
bean.set(IOrderInfo.SHIPPING_FEE, result.get("shippingFee"));
bean.set(IOrderInfo.SHIPPING_NAME, result.get("shippingName"));
new UpdateService().updateBean(orderId, bean, new UpdateService.Listener() {
public void onSuccess(Boolean success) {
updateIsReady = true;
}
});
}
});
}
});
}
private void cancel() {
if(getCurState().getIsEdit()) {
OrderDetailPanel.State newState = new OrderDetailPanel.State();
newState.setId(getCurState().getPkId());
newState.execute();
}
else {
//删除订单及订单商品
new RemoteService().getSpecialService().deleteOrder(getCurState().getPkId(), new AsyncCallback<Boolean>(){
public void onFailure(Throwable caught) {
}
public void onSuccess(Boolean result) {
}
});
OrderListPanel.State newState = new OrderListPanel.State();
newState.execute();
}
}
}
| 33.888095
| 161
| 0.676105
|
08df9682088791dab50f9fa8afe1e306d4c822d8
| 1,824
|
/*
*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* /
*/
package org.wso2.carbon.apimgt.api.dto;
import java.io.Serializable;
/**
* This DTO used to represent a specific condition inside a Condition Group. This is analogous to {@code Condition}
* object.
*/
public class ConditionDTO implements Serializable{
private String conditionType;
private String conditionName;
private String conditionValue;
private boolean isInverted;
public String getConditionType() {
return conditionType;
}
public String getConditionName() {
return conditionName;
}
public void setConditionName(String conditionName) {
this.conditionName = conditionName;
}
public String getConditionValue() {
return conditionValue;
}
public void setConditionValue(String conditionValue) {
this.conditionValue = conditionValue;
}
public boolean isInverted() {
return isInverted;
}
public void setConditionType(String conditionType) {
this.conditionType = conditionType;
}
public void isInverted(boolean invertCondition) {
this.isInverted = invertCondition;
}
}
| 27.223881
| 115
| 0.69682
|
fddce6fed15b53fde810f80ded521fc51c56fb6e
| 244
|
module juery.basic {
requires static lombok;
requires juery.api;
requires java.desktop; // Need for lombok.anyConstructor.addConstructorProperties
exports fr.ght1pc9kc.juery.basic;
exports fr.ght1pc9kc.juery.basic.filter;
}
| 30.5
| 85
| 0.754098
|
330faa1e25185ebbfee590adbdbfd8e14d5cfc82
| 293
|
/**
*
*/
package top.qianxinyao.performance;
/**
* @author qianxinyao
* @email tomqianmaple@gmail.com
* @github https://github.com/bluemapleman
* @date 2016年12月2日
* 用以评估推荐效果的类
* 1、准确率(precision) 2、召回率(recall)
*/
public class Judge
{
public double getPrecision(){
return 0;
}
}
| 13.952381
| 42
| 0.675768
|
1a9c93d8c3ff4ea57ebc64f71d3da8dc52ec3f4f
| 5,163
|
package com.noober.backgroudlibrary;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.noober.background.BackgroundLibrary;
import com.noober.background.drawable.DrawableCreator;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.fl_content, new BlankFragment()).commitAllowingStateLoss();
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ListActivity.class));
}
});
View vAnim = findViewById(R.id.v_anim);
// AnimationDrawable animationDrawable = (AnimationDrawable) vAnim.getBackground();
// animationDrawable.start();
Drawable drawable = new DrawableCreator.Builder().setCornersRadius(30)
.setSolidColor(Color.parseColor("#FFFFFF"))
.setStrokeColor(Color.parseColor("#FFFFFF"))
.setStrokeWidth(10)
.build();
TextView tvTest1 = findViewById(R.id.tvTest1);
tvTest1.setClickable(true);
ColorStateList colors = new DrawableCreator.Builder().setPressedTextColor(Color.RED).setUnPressedTextColor(Color.BLUE).buildTextColor();
tvTest1.setTextColor(colors);
Button btnTest2 = findViewById(R.id.btnTest2);
Drawable drawable2 = new DrawableCreator.Builder().setCornersRadius(dip2px(20))
.setGradientAngle(0).setGradientColor(Color.parseColor("#63B8FF"), Color.parseColor("#4F94CD")).build();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
btnTest2.setBackground(drawable2);
}else {
btnTest2.setBackgroundDrawable(drawable2);
}
Button btnTest3 = findViewById(R.id.btnTest3);
Drawable drawable3 = new DrawableCreator.Builder().setCornersRadius(dip2px(20))
.setRipple(true, Color.parseColor("#71C671"))
.setSolidColor(Color.parseColor("#7CFC00"))
.setStrokeColor(Color.parseColor("#8c6822"))
.setStrokeWidth(dip2px(2))
.build();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
btnTest3.setBackground(drawable3);
}else {
btnTest3.setBackgroundDrawable(drawable3);
}
TextView tvTest4 = findViewById(R.id.tvTest4);
Drawable drawable4 = new DrawableCreator.Builder().setCornersRadius(dip2px(20))
.setPressedDrawable(ContextCompat.getDrawable(this, R.drawable.circle_like_pressed))
.setUnPressedDrawable(ContextCompat.getDrawable(this, R.drawable.circle_like_normal))
.build();
tvTest4.setClickable(true);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
tvTest4.setBackground(drawable4);
}else {
tvTest4.setBackgroundDrawable(drawable4);
}
final Button btnLike = findViewById(R.id.btn_like);
btnLike.setOnClickListener(new View.OnClickListener() {
int i = 1;
@Override
public void onClick(View v) {
btnLike.setText(String.format("点赞+%d", i++));
}
});
final Button btnLike2 = findViewById(R.id.btn_like2);
btnLike2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(btnLike2.isSelected()){
btnLike2.setText("未点赞");
}else {
btnLike2.setText("已点赞");
}
btnLike2.setSelected(!btnLike2.isSelected());
}
});
final Button btnEnable = findViewById(R.id.btn_setEnable);
final TextView tvMulti = findViewById(R.id.tv_multi);
btnEnable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tvMulti.isEnabled()){
tvMulti.setEnabled(false);
tvMulti.setText("textView一条属性多个状态:enable=false");
}else {
tvMulti.setEnabled(true);
tvMulti.setText("textView一条属性多个状态:enable=true");
}
}
});
}
public int dip2px(float dipValue) {
float scale = getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5F);
}
}
| 39.113636
| 144
| 0.633934
|
2f3cef8cdba64b3f2f4f82aafb8dd5877006b6f7
| 5,154
|
/*******************************************************************************
* Copyright (c) 2009-2015 The Last Check, LLC, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.thelastcheck.io.x9.parser;
import com.thelastcheck.io.x937.records.X937AccountTotalsDetailRecord;
import com.thelastcheck.io.x937.records.X937BoxSummaryRecord;
import com.thelastcheck.io.x937.records.X937BundleControlRecord;
import com.thelastcheck.io.x937.records.X937BundleHeaderRecord;
import com.thelastcheck.io.x937.records.X937CashLetterControlRecord;
import com.thelastcheck.io.x937.records.X937CashLetterHeaderRecord;
import com.thelastcheck.io.x937.records.X937CheckDetailAddendumARecord;
import com.thelastcheck.io.x937.records.X937CheckDetailAddendumBRecord;
import com.thelastcheck.io.x937.records.X937CheckDetailAddendumCRecord;
import com.thelastcheck.io.x937.records.X937CheckDetailRecord;
import com.thelastcheck.io.x937.records.X937FileControlRecord;
import com.thelastcheck.io.x937.records.X937FileHeaderRecord;
import com.thelastcheck.io.x937.records.X937ImageViewAnalysisRecord;
import com.thelastcheck.io.x937.records.X937ImageViewDataRecord;
import com.thelastcheck.io.x937.records.X937ImageViewDetailRecord;
import com.thelastcheck.io.x937.records.X937NonHitTotalsDetailRecord;
import com.thelastcheck.io.x937.records.X937ReturnAddendumARecord;
import com.thelastcheck.io.x937.records.X937ReturnAddendumBRecord;
import com.thelastcheck.io.x937.records.X937ReturnAddendumCRecord;
import com.thelastcheck.io.x937.records.X937ReturnAddendumDRecord;
import com.thelastcheck.io.x937.records.X937ReturnRecord;
import com.thelastcheck.io.x937.records.X937RoutingNumberSummaryRecord;
public class X937DefaultRecordHandler implements
X937FileHeaderHandler,
X937FileControlHandler,
X937CashLetterHeaderHandler,
X937CashLetterControlHandler,
X937BundleHeaderHandler,
X937BundleControlHandler,
X937CheckDetailHandler,
X937CheckDetailAddendumAHandler,
X937CheckDetailAddendumBHandler,
X937CheckDetailAddendumCHandler,
X937ImageViewDetailHandler,
X937ImageViewDataHandler,
X937ImageViewAnalysisHandler,
X937ReturnHandler,
X937ReturnAddendumAHandler,
X937ReturnAddendumBHandler,
X937ReturnAddendumCHandler,
X937ReturnAddendumDHandler,
X937NonHitTotalsDetailHandler,
X937AccountTotalsDetailHandler,
X937BoxSummaryHandler,
X937RoutingNumberSummaryHandler {
public void handle(X937CashLetterGraph graph, X937RoutingNumberSummaryRecord record) {
}
public void handle(X937CashLetterGraph graph, X937BoxSummaryRecord record) {
}
public void handle(X937CashLetterGraph graph, X937AccountTotalsDetailRecord record) {
}
public void handle(X937CashLetterGraph graph, X937NonHitTotalsDetailRecord record) {
}
public void handle(X937ReturnGraph graph, X937ReturnAddendumDRecord record) {
}
public void handle(X937ReturnGraph graph, X937ReturnAddendumCRecord record) {
}
public void handle(X937ReturnGraph graph, X937ReturnAddendumBRecord record) {
}
public void handle(X937ReturnGraph graph, X937ReturnAddendumARecord record) {
}
public void handle(X937ReturnGraph graph, X937ReturnRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937ImageViewAnalysisRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937ImageViewDataRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937ImageViewDetailRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937CheckDetailAddendumCRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937CheckDetailAddendumBRecord record) {
}
public void handle(X937CheckDetailGraph graph, X937CheckDetailAddendumARecord record) {
}
public void handle(X937CheckDetailGraph graph, X937CheckDetailRecord record) {
}
public void handle(X937BundleGraph graph, X937BundleControlRecord record) {
}
public void handle(X937BundleGraph graph, X937BundleHeaderRecord record) {
}
public void handle(X937CashLetterGraph graph, X937CashLetterControlRecord record) {
}
public void handle(X937CashLetterGraph graph, X937CashLetterHeaderRecord record) {
}
public void handle(X937FileGraph graph, X937FileControlRecord record) {
}
public void handle(X937FileGraph graph, X937FileHeaderRecord record) {
}
}
| 39.343511
| 91
| 0.763679
|
188ac6f11fe05391237c1440707557b21d22111a
| 1,496
|
package com.ciel.scaproducer2.controller;
import com.ciel.scaapi.crud.IScaUserService;
import com.ciel.scaapi.exception.AlertException;
import com.ciel.scaapi.retu.Result;
import com.ciel.scaentity.entity.ScaUser;
import io.seata.core.context.RootContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@RestController
@Slf4j
@AllArgsConstructor
public class SeataTransactionController {
protected IScaUserService userService;
@Transactional(rollbackFor = Exception.class)
@GetMapping("/seata")
public Result seata(@RequestParam("price") BigDecimal price,
@RequestParam("sendId") Long sendUserId,
@RequestParam("receiveId") Long receiveUserId) throws AlertException {
String xid = RootContext.getXID();//分支事务id
System.out.println("事务id" + xid);
ScaUser user = userService.getById(receiveUserId);
user.setPrice(user.getPrice().add(price));
userService.updateById(user); //更新余额
if (price.compareTo(BigDecimal.ONE) == 0) {
throw new AlertException("1 元主动异常 测试回滚");
}
return Result.ok("账户加钱完成");
}
}
| 30.530612
| 94
| 0.731283
|
184dae4a88ad058b17ff9b87017e6c7b8e84df0a
| 2,023
|
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.exec.planner.logical;
import java.util.List;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexLiteral;
import com.dremio.exec.planner.common.WindowRelBase;
public class WindowRel extends WindowRelBase implements Rel {
/**
* Creates a window relational expression.
*
* @param cluster Cluster
* @param traits
* @param child Input relational expression
* @param rowType Output row type
* @param groups Windows
*/
private WindowRel(
RelOptCluster cluster,
RelTraitSet traits,
RelNode child,
List<RexLiteral> constants,
RelDataType rowType,
List<Group> groups) {
super(cluster, traits, child, constants, rowType, groups);
}
public static WindowRel create(RelOptCluster cluster,
RelTraitSet traitSet,
RelNode child,
List<RexLiteral> constants,
RelDataType rowType,
List<Group> groups) {
RelTraitSet traits = adjustTraits(cluster, child, groups, traitSet);
return new WindowRel(cluster, traits, child, constants, rowType, groups);
}
@Override
public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
return new WindowRel(getCluster(), traitSet, sole(inputs), constants, getRowType(), groups);
}
}
| 30.651515
| 96
| 0.727138
|
1c0debff5d899d8a3f76da21fb7c2d77cd7ee31e
| 8,529
|
/*******************************************************************************
* Copyright (c) Contributors to the Eclipse 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.
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
/*
* REVISION HISTORY:
*
* Date Author(s)
* CR Headline
* ============ ==============================================================
* Feb 25, 2005 Andre Assad
* 11 Implement DMT Use Cases
* ============ ==============================================================
*/
package org.osgi.test.cases.dmt.tc3.tbc.MetaNode.MetaData;
import java.util.Date;
import org.osgi.service.dmt.DmtData;
import org.osgi.service.dmt.DmtException;
import org.osgi.service.dmt.DmtSession;
import org.osgi.service.dmt.MetaNode;
import org.osgi.service.dmt.spi.DataPlugin;
import org.osgi.service.dmt.spi.ExecPlugin;
import org.osgi.service.dmt.spi.ReadWriteDataSession;
import org.osgi.service.dmt.spi.ReadableDataSession;
import org.osgi.service.dmt.spi.TransactionalDataSession;
import org.osgi.test.cases.dmt.tc3.tbc.DmtConstants;
import org.osgi.test.cases.dmt.tc3.tbc.DmtTestControl;
/**
* @author Andre Assad
*
* A test implementation of TestPluginMetaData. This implementation validates the
* DmtSession calls to a subtree handled by a TestPluginMetaData.
*
*/
public class TestPluginMetaData implements DataPlugin, ExecPlugin, ReadWriteDataSession {
public static final String CLOSE = "TestPluginMetaData.close";
public static final String GETCHILDNODENAMES = "TestPluginMetaData.getChildNodeNames";
public static final String GETMETANODE = "TestPluginMetaData.getMetaNode";
public static final String GETNODESIZE = "TestPluginMetaData.getNodeSize";
public static final String GETNODETIMESTAMP = "TestPluginMetaData.getNodeTimeStamp";
public static final String GETNODETITLE = "TestPluginMetaData.getNodeTitle";
public static final String GETNODETYPE = "TestPluginMetaData.getNodeType";
public static final String GETNODEVALUE = "TestPluginMetaData.getNodeValue";
public static final String GETNODEVERSION = "TestPluginMetaData.getNodeVersion";
public static final String ISLEAFNODE = "TestPluginMetaData.isLeafNode";
public static final String ISNODEURI = "TestPluginMetaData.isNodeUri";
//Values (when a string is expected, the return is the same as the gets above)
public static final int GETNODESIZE_VALUE = 1001;
public static final int GETNODEVERSION_VALUE = 199;
public static final DmtData GETNODEVALUE_VALUE = new DmtData(9);
public static final Date GETNODETIMESTAMP_VALUE = new Date(System.currentTimeMillis());
public static final String COMMIT = "TestPluginMetaData.commit";
public static final String COPY = "TestPluginMetaData.copy";
public static final String CREATEINTERIORNODE_1 = "TestPluginMetaData.createInteriorNode";
public static final String CREATEINTERIORNODE_2 = "TestPluginMetaData.createInteriorNode(,)";
public static final String CREATELEAFNODE_1 = "TestPluginMetaData.createLeafNode";
public static final String CREATELEAFNODE_2 = "TestPluginMetaData.createLeafNode(,)";
public static final String CREATELEAFNODE_3 = "TestPluginMetaData.createLeafNode(,,)";
public static final String DELETENODE = "TestPluginMetaData.deleteNode";
public static final String RENAMENODE = "TestPluginMetaData.renameNode";
public static final String ROLLBACK = "TestPluginMetaData.rollback";
public static final String SETDEFAULTNODEVALUE = "TestPluginMetaData.setDefaultNodeValue";
public static final String SETNODETITLE = "TestPluginMetaData.setNodeTitle";
public static final String SETNODETYPE = "TestPluginMetaData.setNodeType";
public static final String SETNODEVALUE = "TestPluginMetaData.setNodeValue";
private DmtTestControl tbc;
public TestPluginMetaData(DmtTestControl tbc) {
this.tbc = tbc;
}
@Override
public ReadableDataSession openReadOnlySession(String[] sessionRoot, DmtSession session) throws DmtException {
return null;
}
@Override
public ReadWriteDataSession openReadWriteSession(String[] sessionRoot, DmtSession session) throws DmtException {
return this;
}
@Override
public TransactionalDataSession openAtomicSession(String[] sessionRoot, DmtSession session) throws DmtException {
return null;
}
@Override
public void execute(DmtSession session, String[] nodePath, String correlator, String data) throws DmtException {
}
@Override
public void setNodeTitle(String[] nodeUri, String title) throws DmtException {
DmtConstants.TEMPORARY = SETNODETITLE;
}
@Override
public void setNodeValue(String[] nodeUri, DmtData data) throws DmtException {
DmtConstants.TEMPORARY = SETNODEVALUE;
}
public void setDefaultNodeValue(String[] nodeUri) throws DmtException {
DmtConstants.TEMPORARY = SETDEFAULTNODEVALUE;
}
@Override
public void setNodeType(String[] nodeUri, String type) throws DmtException {
DmtConstants.TEMPORARY = SETNODETYPE;
}
@Override
public void deleteNode(String[] nodeUri) throws DmtException {
DmtConstants.TEMPORARY = DELETENODE;
}
public void createInteriorNode(String[] nodeUri) throws DmtException {
DmtConstants.TEMPORARY = CREATEINTERIORNODE_1;
}
@Override
public void createInteriorNode(String[] nodeUri, String type)
throws DmtException {
DmtConstants.TEMPORARY = CREATEINTERIORNODE_2;
}
public void createLeafNode(String[] nodeUri) throws DmtException {
DmtConstants.TEMPORARY = CREATELEAFNODE_1;
}
public void createLeafNode(String[] nodeUri, DmtData value) throws DmtException {
DmtConstants.TEMPORARY = CREATELEAFNODE_2;
}
@Override
public void createLeafNode(String[] nodeUri, DmtData value, String mimeType)
throws DmtException {
DmtConstants.TEMPORARY = CREATELEAFNODE_3;
}
@Override
public void copy(String[] nodeUri, String[] newNodeUri, boolean recursive)
throws DmtException {
DmtConstants.TEMPORARY = COPY;
}
@Override
public void renameNode(String[] nodeUri, String newName) throws DmtException {
DmtConstants.TEMPORARY = RENAMENODE;
}
@Override
public void close() throws DmtException {
}
@Override
public boolean isNodeUri(String[] nodeUri) {
String nodeName = tbc.mangleUri(nodeUri);
if (nodeName.equals(TestPluginMetaDataActivator.INEXISTENT_NODE)
|| nodeName.equals(TestPluginMetaDataActivator.INEXISTENT_LEAF_NODE)
|| nodeName.equals(TestPluginMetaDataActivator.INEXISTENT_LEAF_NODE_INVALID_NAME)
|| nodeName.equals(TestPluginMetaDataActivator.INEXISTENT_NODE_INVALID_NAME)) {
return false;
} else {
return true;
}
}
@Override
public DmtData getNodeValue(String[] nodeUri) throws DmtException {
return null;
}
@Override
public String getNodeTitle(String[] nodeUri) throws DmtException {
return GETNODETITLE;
}
@Override
public String getNodeType(String[] nodeUri) throws DmtException {
return GETNODETYPE;
}
@Override
public int getNodeVersion(String[] nodeUri) throws DmtException {
return GETNODEVERSION_VALUE;
}
@Override
public Date getNodeTimestamp(String[] nodeUri) throws DmtException {
return GETNODETIMESTAMP_VALUE;
}
@Override
public int getNodeSize(String[] nodeUri) throws DmtException {
return GETNODESIZE_VALUE;
}
@Override
public String[] getChildNodeNames(String[] nodeUri) throws DmtException {
return new String[] { GETCHILDNODENAMES, "newNode" };
}
@Override
public MetaNode getMetaNode(String[] nodeUri) throws DmtException {
return TestPluginMetaDataActivator.metaNodeDefault;
}
@Override
public boolean isLeafNode(String[] nodeUri) throws DmtException {
String nodeName = tbc.mangleUri(nodeUri);
if (nodeName.equals(TestPluginMetaDataActivator.LEAF_NODE) ||
nodeName.equals(TestPluginMetaDataActivator.INEXISTENT_LEAF_NODE_INVALID_NAME)) {
return true;
}
else {
return false;
}
}
@Override
public void nodeChanged(String[] nodeUri) throws DmtException {
}
}
| 33.316406
| 114
| 0.748271
|
f628cc01baf8ed6e7602ef0e25f9d4b6d2e269e7
| 668
|
package designpattern.prototype;
/**
* @author initial.y
* @className Client
* @description
* @date 2021/8/8
*/
public class Client {
public static void main(String[] args) {
ConcretePrototype1 concretePrototype1 = new ConcretePrototype1();
System.out.println(concretePrototype1);
ConcretePrototype2 concretePrototype2 = new ConcretePrototype2();
System.out.println(concretePrototype2);
for (int i = 0; i < 2; i++) {
System.out.println("concretePrototype1.clone:" + concretePrototype1.clone());
System.out.println("concretePrototype2.clone:" + concretePrototype2.clone());
}
}
}
| 27.833333
| 89
| 0.663174
|
c711e9334ee37c7470dadeff60d57fbca097e54e
| 5,883
|
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* 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 me.lucko.luckperms.common.commands.abstraction;
import lombok.Getter;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.locale.LocalizedSpec;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
/**
* An abstract command class
*
* @param <T> the type required by the {@link #execute(LuckPermsPlugin, Sender, Object, List, String)} method of this command
* @param <S> the type of any child commands
*/
public abstract class Command<T, S> {
@Getter
private final LocalizedSpec spec;
/**
* The name of the command. Should be properly capitalised.
*/
@Getter
private final String name;
/**
* The permission required to use this command. Nullable.
*/
private final Permission permission;
/**
* A predicate used for testing the size of the arguments list passed to this command
*/
@Getter
private final Predicate<Integer> argumentCheck;
/**
* Child commands. Nullable.
*/
private final List<Command<S, ?>> children;
public Command(LocalizedSpec spec, String name, Permission permission, Predicate<Integer> argumentCheck, List<Command<S, ?>> children) {
this.spec = spec;
this.name = name;
this.permission = permission;
this.argumentCheck = argumentCheck;
this.children = children == null ? null : ImmutableList.copyOf(children);
}
public Command(LocalizedSpec spec, String name, Permission permission, Predicate<Integer> argumentCheck) {
this(spec, name, permission, argumentCheck, null);
}
public Command(LocalizedSpec spec, String name, Predicate<Integer> argumentCheck) {
this(spec, name, null, argumentCheck, null);
}
public abstract CommandResult execute(LuckPermsPlugin plugin, Sender sender, T t, List<String> args, String label) throws CommandException;
public List<String> tabComplete(LuckPermsPlugin plugin, Sender sender, List<String> args) {
return Collections.emptyList();
}
/**
* Sends a brief command usage message to the Sender.
* If this command has child commands, the children are listed. Otherwise, a basic usage message is sent.
*
* @param sender the sender to send the usage to
* @param label the label used when executing the command
*/
public abstract void sendUsage(Sender sender, String label);
/**
* Sends a detailed command usage message to the Sender.
* If this command has child commands, nothing is sent. Otherwise, a detailed messaging containing a description
* and argument usage is sent.
*
* @param sender the sender to send the usage to
* @param label the label used when executing the command
*/
public abstract void sendDetailedUsage(Sender sender, String label);
/**
* Returns true if the sender is authorised to use this command
*
* Commands with children are likely to override this method to check for permissions based upon whether
* a sender has access to any sub commands.
*
* @param sender the sender
* @return true if the sender has permission to use this command
*/
public boolean isAuthorized(Sender sender) {
return permission == null || permission.isAuthorized(sender);
}
/**
* Returns if this command should be displayed in command listings, or "hidden"
*
* @return if this command should be displayed in command listings, or "hidden"
*/
public boolean shouldDisplay() {
return true;
}
public String getDescription() {
return spec.description();
}
/**
* Returns the usage of this command. Will only return a non empty result for main commands.
*
* @return the usage of this command.
*/
public String getUsage() {
String usage = spec.usage();
return usage == null ? "" : usage;
}
public Optional<Permission> getPermission() {
return Optional.ofNullable(permission);
}
public Optional<List<Arg>> getArgs() {
return Optional.ofNullable(spec.args());
}
public Optional<List<Command<S, ?>>> getChildren() {
return Optional.ofNullable(children);
}
}
| 35.017857
| 143
| 0.699813
|
72f7fd9f8be9c841123a75094a56298b39b7587d
| 816
|
package io.github.tunacan427.electroarmor.integration;
import io.github.prospector.modmenu.api.ModMenuApi;
import io.github.tunacan427.electroarmor.ElectroArmor;
import io.github.tunacan427.electroarmor.ElectroArmorConfig;
import me.sargunvohra.mcmods.autoconfig1u.AutoConfig;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.screen.Screen;
import java.util.Optional;
import java.util.function.Supplier;
@Environment(EnvType.CLIENT)
public class ModMenuIntegration implements ModMenuApi {
@Override
public String getModId() {
return ElectroArmor.MOD_ID;
}
@Override
public Optional<Supplier<Screen>> getConfigScreen(Screen screen) {
return Optional.of(AutoConfig.getConfigScreen(ElectroArmorConfig.class, screen));
}
}
| 31.384615
| 89
| 0.794118
|
c7df2c75697f4399c9ae34e931f032814cd64287
| 5,636
|
package at.tuwien.ldlab.statspace.metadata;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import at.tuwien.ldlab.statspace.util.SpecialEndpointList;
import at.tuwien.ldlab.statspace.widgetgeneration.Endpoint;
import at.tuwien.ldlab.statspace.widgetgeneration.Request;
import be.ugent.mmlab.rml.core.RMLEngine;
import be.ugent.mmlab.rml.model.Parameters;
public class GenerateMetaData extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Log log = LogFactory.getLog(GenerateMetaData.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sRMLSource=null, sEndpoint=null;
Parameters parameters = new Parameters();
//read parameters
Enumeration<String> arrNames = request.getParameterNames();
while(arrNames.hasMoreElements()){
String sName = arrNames.nextElement();
if(sName.equalsIgnoreCase("sparql")){
sEndpoint = request.getParameter("sparql").trim();
}else{
if(sName.equalsIgnoreCase("rmlsource")){
sRMLSource = request.getParameter("rmlsource").trim();
}else{
String sValue = request.getParameter(sName);
parameters.addParameterValue(sName, sValue);
}
}
}
//case 1: create metadata for an endpoint
if(sEndpoint!=null && !sEndpoint.isEmpty()){
log.info("Create metadata for " + sEndpoint);
SpecialEndpointList specialList = new SpecialEndpointList(getServletContext().getRealPath("/") + File.separator + "template" + File.separator + "list.xml");
HttpSession session = request.getSession( );
session.setMaxInactiveInterval(60*60);
//check special endpoint list
int k;
boolean bHTTP, bRemove, bFindOther;
String sUseDistinct;
sEndpoint=sEndpoint.trim();
if(!sEndpoint.toLowerCase().startsWith("http"))
sEndpoint="http://"+sEndpoint;
k=specialList.getEndpointIndex(sEndpoint);
if(k!=-1){
if(!specialList.getEndpointForQuery(k).equals(""))
sEndpoint = specialList.getEndpointForQuery(k);
bHTTP = specialList.getHTTPRequest(k);
bRemove = specialList.getRemoveDuplicate(k);
sUseDistinct = specialList.getUseDistinct(k);
bFindOther = specialList.getFindOtherValue(k);
}else{
bHTTP = false;
bRemove = false;
sUseDistinct = "";
bFindOther = true;
}
//query sparql endpoint
Endpoint endpoint = new Endpoint(sEndpoint, "", bHTTP, bRemove, sUseDistinct, bFindOther);
endpoint.queryDataSet();
int errorCode = endpoint.getErrorCode();
if(endpoint.getDataSet().size()!=0)
errorCode =-1;
if(errorCode!= -1){
response.addHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("Sorry. No dataset is detected");
}else{
//set Id for this request
Random random = new Random();
int idRequest = random.nextInt();
//add new request
Request req = new Request();
req.setMetaDataPurpose(true);
req.setEndpoint(endpoint);
request.setAttribute("idRequest", idRequest);
request.getServletContext().setAttribute(Integer.toString(idRequest), req);
RequestDispatcher view = request.getRequestDispatcher("/generation/dataset.jsp");
view.forward(request, response);
}
}
//case 2: create metadata for a non-RDF dataset
else if(sRMLSource!=null && !sRMLSource.isEmpty()){
log.info("Create metadata for " + sRMLSource);
String sPath = getServletContext().getRealPath("/");
String sSeparator = File.separator;
if(RMLEngine.isLocalFile(sRMLSource)){
sRMLSource = sPath + sRMLSource;
}
MetaDataForRML md = new MetaDataForRML();
md.runRMLProcessor(sRMLSource, sPath, sSeparator, parameters);
boolean bStatus = md.getStatus();
if(!bStatus){
response.addHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("There was an error with your mapping");
}else{
File file = new File(md.getOutputFile());
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/octet-stream");
String s = file.getName();
s = s.substring(s.indexOf("_")+1);
response.setHeader("Content-Disposition", "attachment; filename=" + s);
int length=0;
ServletOutputStream outStream = response.getOutputStream();
byte[] byteBuffer = new byte[4096];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
}else{
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
response.addHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("Sorry, we cannot recognize parameters in your request");
}
}
}
| 38.340136
| 160
| 0.6989
|
b805e2401114e60f01721643315a76a151f7a6c2
| 3,480
|
package com.skylerdache.spacepong.game_elements;
import com.skylerdache.spacepong.enums.PlayerPosition;
import com.skylerdache.spacepong.exceptions.PlayerScoreException;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Ball {
private final double radius;
private final SpaceBounds bounds;
private double x = 0;
private double y = 0;
private double z = 0;
private double vx = 0;
private double vy = 0;
private double vz = 0;
public Ball(double radius, SpaceBounds spaceBounds) {
this.radius = radius;
this.bounds = spaceBounds;
this.resetPositionAndVelocity();
}
/**
* simulates the motion of the ball
* @param dt number of seconds
* @param p1Paddle p1 paddle
* @param p2Paddle p2 paddle
* @throws PlayerScoreException if the ball goes out of bounds in a way that a player scores a point
*/
public void tick(double dt, Paddle p1Paddle, Paddle p2Paddle) throws PlayerScoreException {
// bounce logic:
// X axis (positive X is p1's right, p2's left) :
if (x + dt*vx + radius > bounds.XMax()) { //above max, bounce down:
x = 2*bounds.XMax() - x - vx*dt;
vx = -vx;
}
else if (x + dt*vx - radius < bounds.XMin()) { //below min, bounce up:
x = 2*bounds.XMin() - x - vx*dt;
vx = -vx;
} else { //within range:
x += dt * vx;
}
// System.out.println("ball ticking: x from "+prevX+" to "+x);
// Y axis (positive Y is up, negative Y is down):
if (y + dt*vy + radius > bounds.YMax()) { //above max, bounce down:
y = 2 * bounds.YMax() - y - vy*dt;
vy = -vy;
} else if (y + dt*vy - radius < bounds.YMin()) { //below min, bounce up:
y = 2 * bounds.YMin() - y - vy*dt;
vy = -vy;
} else { //within range:
y += dt * vy;
}
// Z axis (positive Z is towards P1, negative Z is towards P2):
if (z + dt*vz + radius > bounds.ZMax()) { //above max
throw new PlayerScoreException(PlayerPosition.P2);
} else
if (z + dt*vz - radius < bounds.ZMin()) { //below min
throw new PlayerScoreException(PlayerPosition.P1);
} else { //within range:
if (p1Paddle.ballInRange(this)) {
z = 2*p1Paddle.zMin() - z - vz*dt;
vz *= -1;
} else if (p2Paddle.ballInRange(this)) {
z = 2*p2Paddle.zMax() - z - vz*dt;
vz *= -1;
} else {
z += dt * vz;
}
}
}
public void resetPositionAndVelocity() {
resetPosition();
resetVelocity();
}
public void resetPosition() {
this.x = bounds.centerX();
this.y = bounds.centerY();
this.z = bounds.centerZ();
}
/**
* The ball will have a random horizontal and vertical direction, but its direction toward
* either paddle/score zone will be either +1 or -1; so one player or the other will score
*/
public void resetVelocity() {
this.vx = 2*Math.random()-1;
this.vy = 2*Math.random()-1;
//noinspection MagicNumber
if (Math.random() > 0.5) {
this.vz = 1;
} else {
this.vz = -1;
}
}
public String getPosition() {
return String.format("x: %1f, y: %1f, z: %1f",x, y, z);
}
}
| 34.117647
| 104
| 0.541954
|
585ca4327a159c4d9b200f088ad62dc4e8f7cdd1
| 994
|
package com.darkender.plugins.okbomber.custom.addons;
import com.darkender.plugins.okbomber.TNTData;
import com.darkender.plugins.okbomber.custom.TNTAddon;
import org.bukkit.Particle;
import org.bukkit.entity.TNTPrimed;
public class FloatingAddon extends TNTAddon
{
public FloatingAddon()
{
super("addon-floating");
}
@Override
public boolean conflictsWith(TNTAddon other)
{
return other.equals(STICKY);
}
@Override
public String getName()
{
return "Floating";
}
@Override
public String getDescription()
{
return "Causes the TNT to float upwards";
}
@Override
public void onIgnite(TNTPrimed tnt, TNTData data)
{
tnt.setGravity(false);
}
@Override
public void entityTick(TNTPrimed tnt, TNTData data)
{
tnt.getWorld().spawnParticle(Particle.CLOUD, tnt.getLocation(), 0);
tnt.setVelocity(tnt.getVelocity().setY(0.4));
}
}
| 21.608696
| 75
| 0.646881
|
ebbcb3a95b915596a0aa3d35aa633c1ea6f3c422
| 509
|
package udacity.pokemon;
public class Pokemon {
private String name;
private int id;
private String candy;
private String image;
public Pokemon(String name, int id, String candy, String image) {
this.name = name;
this.id = id;
this.candy = candy;
this.image = image;
}
public String getName() { return name; }
public int getId() { return id; }
public String getCandy() { return candy; }
public String getImage() { return image; }
}
| 22.130435
| 69
| 0.618861
|
1f85998069f1fc8a590cd38af4e86b50bf23ed0c
| 1,162
|
package com.bazl.dna.lims.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bazl.dna.lims.dao.XckyAddressInfoMapper;
import com.bazl.dna.lims.model.po.XckyAddressInfo;
import com.bazl.dna.lims.service.XckyAddressInfoService;
/**
* Created by Administrator on 2019/1/27.
*/
@Service
public class XckyAddressInfoServiceImpl extends BaseService implements XckyAddressInfoService {
@Autowired
XckyAddressInfoMapper xckyAddressInfoMapper;
/**
* 根据单位id获取现勘地址信息
* @param orgId
* @return
*/
public XckyAddressInfo selectByOrgId(String orgId) {
try {
return xckyAddressInfoMapper.selectByOrgId(orgId);
} catch (Exception ex) {
logger.error("根据单位id获取现勘地址信息错误!", ex);
return null;
}
}
/**
* 获取默认的现勘地址信息
* @return
*/
public XckyAddressInfo selectDefault(){
try {
return xckyAddressInfoMapper.selectDefault();
} catch (Exception ex) {
logger.error("根据单位id获取现勘地址信息错误!", ex);
return null;
}
}
}
| 24.208333
| 95
| 0.659208
|
4c844e961b95af36717af4b421065c4dbf91e610
| 609
|
package cn.debug.aop2.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
@Component
@Aspect
@EnableAspectJAutoProxy
public class AspectAdvice {
@Around("execution(* cn.debug.aop2.service.UserService.test(..))")
public Object test(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("切面前...");
Object result = pjp.proceed();
System.out.println("切面后...");
return result;
}
}
| 22.555556
| 69
| 0.778325
|
614777d3a4eeca0c38bddd077323bb83201d575b
| 22,906
|
package com.zkryle.jeg.common.golem;
import com.zkryle.jeg.common.ICoreOwner;
import com.zkryle.jeg.common.customgoals.*;
import com.zkryle.jeg.core.Init;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.attributes.AttributeModifierMap;
import net.minecraft.entity.ai.attributes.Attributes;
import net.minecraft.entity.ai.goal.*;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.monster.ZombifiedPiglinEntity;
import net.minecraft.entity.passive.TameableEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.particles.BlockParticleData;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
import java.util.Random;
public class EnragedMagmaticGolemEntity extends TameableEntity implements ICoreOwner, IEntityAdditionalSpawnData{
private float fallingSpeed = 0.0f;
private short coreDischargeCounter = 1200;
public float headInclination;
public float bodyInclination;
public float altBodyInclination;
private ItemStack core = ItemStack.EMPTY;
private boolean isOn = false;
private int attackAnimationTick;
private int rangedAttackAnimationTick;
private byte coreDelay = 80;
private boolean soundFlag;
public EnragedMagmaticGolemEntity( EntityType <? extends TameableEntity> p_i48574_1_ , World p_i48574_2_ ){
super( p_i48574_1_ , p_i48574_2_ );
}
public static AttributeModifierMap.MutableAttribute createAttributes(){
return MobEntity.createMobAttributes().add(Attributes.FOLLOW_RANGE, 35.0D).add( Attributes.MAX_HEALTH , 300.0D ).add(Attributes.MOVEMENT_SPEED, 0.30D)
.add(Attributes.KNOCKBACK_RESISTANCE, 1.0D).add(Attributes.ATTACK_DAMAGE, 30.0D);
}
@Override
protected void registerGoals(){
this.goalSelector.addGoal( 1, new SpikeAttackGoal(this, 11.0F) );
this.goalSelector.addGoal(2, new CoreOwnerMeleeAttackGoal(this, 1.0D, true));
this.goalSelector.addGoal(3, new CoreOwnerFollowOwnerGoal( this , 1.0D , 7.5F , 2.0F , false ) );
this.goalSelector.addGoal( 4, new CoreOwnerWaterAvoidingRandomWalkingGoal( this, 0.9D ) );
this.goalSelector.addGoal( 5, new CoreOwnerLookAtGoal( this, LivingEntity.class, 4.0F ) );
this.goalSelector.addGoal( 6, new CoreOwnerLookRandomlyGoal( this) );
this.targetSelector.addGoal(1, new OwnerHurtByTargetGoal(this));
this.targetSelector.addGoal(2, new OwnerHurtTargetGoal(this));
this.targetSelector.addGoal(3, (new HurtByTargetGoal(this)).setAlertOthers());
this.targetSelector.addGoal(4, new NearestAttackableTargetGoal <>(this, MobEntity.class, 5, false, false,
( p_234199_0_) -> p_234199_0_ instanceof IMob && !(p_234199_0_ instanceof ZombifiedPiglinEntity) ));
}
@Nullable
@Override
public AgeableEntity getBreedOffspring( ServerWorld p_241840_1_ , AgeableEntity p_241840_2_ ){
return null;
}
@Override
public boolean hasCore(){
return !this.core.isEmpty();
}
@Override
public void setCore( ItemStack core){
this.core = core;
}
@Override
public ItemStack getCore(){
return this.core;
}
@Override
public boolean isDelayElapsed(){
return this.coreDelay <= 0;
}
@Override
public void tick(){
if(this.getCorePercentage() <= 2 && this.isOn()){
this.setOn( false );
} else if(this.getCorePercentage() > 2 && !this.isOn()){
this.setOn( true );
}
if(!this.isOn()){
if(bodyInclination < 1.055f) fallingSpeed += 0.0025f;
if(headInclination > -0.5f){
headInclination -= 0.05f;
}
if(bodyInclination < 1.055f && headInclination < -0.25f){
bodyInclination += fallingSpeed;
}
} else {
if(headInclination < 0.0f && bodyInclination <= 0.0f){
headInclination += 0.05f;
}
if(bodyInclination > 0.0f ){
bodyInclination -= 0.05f;
}
if(this.rangedAttackAnimationTick > 10 && altBodyInclination < 0.85F){
altBodyInclination += 0.3f;
}
fallingSpeed = 0.0001f;
}
if(this.rangedAttackAnimationTick <= 10 && altBodyInclination > 0.0F){
altBodyInclination -= 0.15f;
}
if(Math.floor(bodyInclination * 10) == 9 && !this.hasCore()){
this.spawnHitParticles(30);
this.soundFlag = true;
if(!this.level.isClientSide()){
this.level.playSound(null, this.blockPosition(), Init.GROUND_PUNCH.get() , SoundCategory.NEUTRAL , 1.0F , 1.0F);
}
}
if(Math.floor(bodyInclination * 10) == 1 && !this.hasCore() && this.soundFlag){
if(!this.level.isClientSide()){
this.soundFlag = false;
this.level.playSound(null, this.blockPosition(), Init.GOLEM_EXTRACTING_CORE.get() , SoundCategory.NEUTRAL , 1.0F , 1.0F);
}
}
if(this.isOn()){
this.coreDischargeCounter--;
if(coreDischargeCounter <= 0){
coreDischargeCounter = 1200;
if(!this.level.isClientSide()){
this.core.hurt( 5 , new Random() , null );
}
}
}
this.coreDelay = (byte) Math.max( 0, --coreDelay );
super.tick();
}
public void spawnHitParticles(int amountOfParticles){
Vector3d particlePos = this.position().add( this.getLookAngle() );
if (this.level instanceof ServerWorld) {
((ServerWorld)this.level).sendParticles(new BlockParticleData(ParticleTypes.BLOCK, this.level.getBlockState( new BlockPos(particlePos).below() )), particlePos.x(), particlePos.y(), particlePos.z(), amountOfParticles, this.getBbWidth() / 4.0F , this.getBbHeight() / 4.0F , this.getBbWidth() / 4.0F , 0.1D);
}
}
@Override
public ActionResultType mobInteract( PlayerEntity pPlayer , Hand pHand ){
if(pPlayer.getItemInHand( pHand ).getItem() == Init.NETHER_CORE_ITEM.get() && !this.hasCore() && bodyInclination >= 1.055f){
this.coreDelay = 80;
this.setCore( pPlayer.getItemInHand( pHand ).copy() );
pPlayer.setItemInHand( pHand, ItemStack.EMPTY );
if(getCorePercentage() > 2) this.core.hurt( 20, new Random(), null );
if(!pPlayer.isShiftKeyDown()) this.setTamed( pPlayer );
this.level.playSound( pPlayer, this.blockPosition().above(), Init.INSERTING_CORE_GOLEM.get(), SoundCategory.NEUTRAL, 0.5F, 1.0F );
return ActionResultType.SUCCESS;
} else if (pPlayer.getItemInHand( pHand ).isEmpty() && this.hasCore() && (bodyInclination <= 0.0f || this.getCorePercentage() <= 2)
&& ( this.getOwnerUUID() == null || this.getOwnerUUID().equals( pPlayer.getUUID() ) )) {
pPlayer.setItemInHand( pHand, this.core.copy() );
this.setCore( ItemStack.EMPTY );
if(this.isTame() && this.getOwnerUUID().equals( pPlayer.getUUID() )) this.setUnTamed();
this.soundFlag = true;
return ActionResultType.SUCCESS;
}else if(pPlayer.getItemInHand( pHand ).getItem() == Init.MAGMATIC_OBSIDIAN_ITEM.get()
&& this.getHealth() < this.getMaxHealth()){
if(!pPlayer.abilities.instabuild){
pPlayer.getItemInHand( pHand ).shrink( 1 );
}
this.playSound( SoundEvents.IRON_GOLEM_REPAIR , 1.0f , 1.0f );
this.heal( 16.0f );
return ActionResultType.SUCCESS;
}
return ActionResultType.PASS;
}
public boolean isOn(){
return this.isOn;
}
public void setOn( boolean on ){
isOn = on;
}
@Override
public boolean save( CompoundNBT pCompound ){
CompoundNBT core = new CompoundNBT();
this.core.save( core );
pCompound.put("CORE", core);
return super.save( pCompound );
}
@Override
public void load( CompoundNBT pCompound ){
this.setCore( ItemStack.of( (CompoundNBT) pCompound.get( "CORE" ) ).copy() );
super.load( pCompound );
}
@Override
protected void dropEquipment(){
this.level.addFreshEntity( new ItemEntity( this.level, this.getX(), this.getY(), this.getZ(), this.core.copy() ) );
}
@Override
public void writeSpawnData( PacketBuffer buffer ){
buffer.writeItem(this.core.copy());
}
@Override
public void readSpawnData( PacketBuffer additionalData ){
this.setCore( additionalData.readItem().copy() );
}
@Override
public IPacket <?> getAddEntityPacket(){
return NetworkHooks.getEntitySpawningPacket(this);
}
@Nullable
@Override
protected SoundEvent getHurtSound( DamageSource p_184601_1_ ){ return Init.ENRAGED_MAGMATIC_GOLEM_HURT.get(); }
@Nullable
@Override
protected SoundEvent getDeathSound(){ return Init.ENRAGED_MAGMATIC_GOLEM_DIES.get(); }
public boolean doHurtTarget( Entity pEntity) {
this.attackAnimationTick = 10;
this.level.broadcastEntityEvent(this, (byte)4);
float f = this.getAttackDamage();
float f1 = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f;
boolean flag = pEntity.hurt( DamageSource.mobAttack(this), f1);
if (flag) {
boolean flag1 = new Random().nextInt(20) == 5;
pEntity.setDeltaMovement(pEntity.getDeltaMovement().add(this.getLookAngle().x() * 1.7F * (flag1 ? 2.0F : 1.0F), 0.7F , this.getLookAngle().z() * 1.7F * (flag1 ? 2.0F : 1.0F)));
this.doEnchantDamageEffects(this, pEntity);
for (Entity entity : pEntity.level.getEntities(pEntity, new AxisAlignedBB( pEntity.blockPosition().east(2).south(2).below(), pEntity.blockPosition().north(2).west(2).above() ) )){
if(!(entity instanceof EnragedMagmaticGolemEntity)){
boolean flag2 = !(entity instanceof ItemEntity);
if(flag2) entity.hurt( DamageSource.mobAttack(this), f1/8.0F);
float v = 1.2F * (flag1 ? 2.0F : 1.0F);
entity.setDeltaMovement( pEntity.getDeltaMovement().add( this.getLookAngle().x() * v , 0.7F , this.getLookAngle().z() * v ) );
}
}
}
boolean fireFlag = new Random().nextInt(100) < 10;
if (fireFlag) pEntity.setSecondsOnFire( 10 );
this.playSound( Init.ENRAGED_MAGMATIC_GOLEM_ATTACK.get(), 0.7F, 1.0F);
return flag;
}
private float getAttackDamage() {
return (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE) * (this.getCorePercentage() / 100.0F);
}
@Override
public void aiStep(){
super.aiStep();
if (this.attackAnimationTick > 0) {
--this.attackAnimationTick;
}
if (this.rangedAttackAnimationTick > 0) {
--this.rangedAttackAnimationTick;
}
}
@OnlyIn(Dist.CLIENT)
public void handleEntityEvent(byte pId) {
if (pId == 4) {
this.attackAnimationTick = 10;
this.playSound(SoundEvents.IRON_GOLEM_ATTACK, 1.0F, 1.0F);
} else if(pId == 5){
this.rangedAttackAnimationTick = 20;
}else{
super.handleEntityEvent(pId);
}
}
@OnlyIn(Dist.CLIENT)
public int getAttackAnimationTick(){
return this.attackAnimationTick;
}
public void performPreRangedAttackAnimation(){
this.rangedAttackAnimationTick = 20;
this.level.broadcastEntityEvent( this, (byte) 5 );
}
@OnlyIn(Dist.CLIENT)
public int getRangedAttackAnimationTick(){
return this.rangedAttackAnimationTick;
}
/**
* Deprecated call, overriding/implementing is fine.
*/
@Deprecated
public void setTamed( PlayerEntity pPlayer ){
this.tame( pPlayer );
this.navigation.stop();
this.setTarget( null );
this.level.broadcastEntityEvent( this , (byte) 7 );
}
/**
* Deprecated call, overriding/implementing is fine.
*/
@Deprecated
public void setUnTamed(){
this.setTame( false );
this.setOwnerUUID(null);
}
@Override
public boolean fireImmune(){
return true;
}
@Override
protected void playStepSound( BlockPos p_180429_1_ , BlockState p_180429_2_ ){
this.playSound( Init.ENRAGED_MAGMATIC_GOLEM_STEP.get(), 0.4F , 1.0F);
super.playStepSound( p_180429_1_ , p_180429_2_ );
}
@Override
public void checkDespawn(){
}
// Custom Ranged Attack Goal
public class SpikeAttackGoal extends Goal{
private final EnragedMagmaticGolemEntity golem;
private final float distanceToActivate;
private long lastCanUseCheck = 0L;
private int animationDelay;
public SpikeAttackGoal(EnragedMagmaticGolemEntity pEntity, float pDistance){
this.golem = pEntity;
this.distanceToActivate = pDistance;
}
@Override
public boolean canUse(){
LivingEntity target = golem.getTarget();
if(this.golem.isDelayElapsed() && this.golem.getCorePercentage() >= 50){
if((this.golem.level.getGameTime() - this.lastCanUseCheck) > 100L){
if(target == null){
return false;
}else if(!target.isAlive()){
return false;
}else if(golem.distanceTo( target ) >= this.distanceToActivate && isReachable( target )){
this.lastCanUseCheck = this.golem.level.getGameTime();
return true;
}
}
}
return false;
}
@Override
public boolean canContinueToUse(){
LivingEntity target = golem.getTarget();
return this.animationDelay > 0 || (target != null && !target.isAlive() && golem.distanceTo( target ) >= this.distanceToActivate && isReachable( target ) && this.golem.getCorePercentage() >= 50);
}
@Override
public void start(){
this.golem.setAggressive( true );
this.animationDelay = 10;
golem.performPreRangedAttackAnimation();
if(!this.golem.level.isClientSide()) this.golem.level.playSound(null, this.golem.blockPosition(), Init.GROUND_PUNCH.get() , SoundCategory.NEUTRAL , 1.0F , 1.0F);
}
@Override
public void stop(){
if(animationDelay <= 0){
LivingEntity livingentity = this.golem.getTarget();
if(!EntityPredicates.NO_CREATIVE_OR_SPECTATOR.test( livingentity )){
this.golem.setTarget( null );
}
this.golem.setAggressive( false );
this.golem.getNavigation().stop();
}
}
@Override
public void tick(){
this.animationDelay = Math.max(0, --animationDelay);
this.golem.navigation.stop();
if(this.animationDelay == 0){
if( this.golem.getTarget() != null){
performAttack( this.golem.getTarget() , this.golem.distanceTo( this.golem.getTarget() ) );
this.golem.spawnHitParticles( 100 );
}
}
}
private void performAttack( LivingEntity target, double distanceToTarget ){
this.golem.getCore().hurt( 3, new Random(), null );
float f = (float)MathHelper.atan2(target.getZ() - this.golem.getZ(), target.getX() - this.golem.getX());
for(int l = 0; l < distanceToTarget; ++l) {
double d2 = 1.25D * (l - 3.0D);
int j = 1 * l;
if(!this.golem.level.isClientSide()){
BlockPos pos = new BlockPos( this.golem.getX() + (double)MathHelper.cos(f) * d2, target.getY() - 1.0D,this.golem.getZ() + (double)MathHelper.sin(f) * d2 );
if(this.golem.level.getBlockState(pos).isFaceSturdy(target.level, pos, Direction.UP)){
((ServerWorld) this.golem.level).sendParticles( new BlockParticleData( ParticleTypes.BLOCK ,
target.level.getBlockState( pos ) ) ,
this.golem.getX() + (double) MathHelper.cos( f ) * d2 , target.getY() - 0.25D , this.golem.getZ() + (double) MathHelper.sin( f ) * d2
, (int) (distanceToTarget - l) , 0 , 0 , 0 , (distanceToTarget - l) * 2 );
if(target.level.getBlockState( pos ).getBlock() != Blocks.AIR){
((ServerWorld) this.golem.level).sendParticles( ParticleTypes.REVERSE_PORTAL ,
this.golem.getX() + (double) MathHelper.cos( f ) * d2 , target.getY() - 0.25D , this.golem.getZ() + (double) MathHelper.sin( f ) * d2
, (int) distanceToTarget , 0 , 0 , 0 , 0.5F );
}
target.level.playSound( null, pos, Init.ENRAGED_GOLEM_SPIKE_ATTACK.get(), SoundCategory.BLOCKS, 0.7F, 1.0F );
} else if(this.golem.level.getBlockState(pos.below()).isFaceSturdy(target.level, pos.below(), Direction.UP)){
((ServerWorld) this.golem.level).sendParticles( new BlockParticleData( ParticleTypes.BLOCK ,
target.level.getBlockState( pos.below() ) ) ,
this.golem.getX() + (double) MathHelper.cos( f ) * d2 , target.getY() - 1.25D , this.golem.getZ() + (double) MathHelper.sin( f ) * d2
, (int) (distanceToTarget - l) , 0 , 0 , 0 , (distanceToTarget - l) * 2 );
if(target.level.getBlockState( pos.below() ).getBlock() != Blocks.AIR){
((ServerWorld) this.golem.level).sendParticles( ParticleTypes.REVERSE_PORTAL ,
this.golem.getX() + (double) MathHelper.cos( f ) * d2 , target.getY() - 1.25D , this.golem.getZ() + (double) MathHelper.sin( f ) * d2
, (int) distanceToTarget , 0 , 0 , 0 , 0.5F );
}
target.level.playSound( null, pos.below(), Init.ENRAGED_GOLEM_SPIKE_ATTACK.get(), SoundCategory.BLOCKS, 0.7F, 1.0F );
}
}
}
for(int i = 0; i < 5; ++i) {
float f1 = f + (float)i * (float)Math.PI * 0.4F;
BlockPos pos = new BlockPos( this.golem.getX() + (double)MathHelper.cos(f) * 1.25D * (int)(distanceToTarget - 2.0D) + (double)MathHelper.cos(f1) * 1.9D,
target.blockPosition().getY() ,this.golem.getZ() + (double)MathHelper.sin(f) * (int)(distanceToTarget - 2.0D) + (double)MathHelper.sin(f1) * 1.9D );
if(target.level.getBlockState(pos.below()).isFaceSturdy(target.level, pos, Direction.UP)){
target.level.addFreshEntity( EnragedGolemSpikeEntity.createEnragedGolemSpikeEntity( target.level ,
this.golem.getX() + (double) MathHelper.cos( f ) * 1.25D * (int) (distanceToTarget - 2.0D) + (double) MathHelper.cos( f1 ) * 1.9D ,
target.blockPosition().getY() , this.golem.getZ() + (double) MathHelper.sin( f ) * (int) (distanceToTarget - 2.0D) + (double) MathHelper.sin( f1 ) * 1.9D , f ) );
} else if(target.level.getBlockState(pos.below(2)).isFaceSturdy(target.level, pos.below(), Direction.UP)){
target.level.addFreshEntity( EnragedGolemSpikeEntity.createEnragedGolemSpikeEntity( target.level ,
this.golem.getX() + (double) MathHelper.cos( f ) * 1.25D * (int) (distanceToTarget - 2.0D) + (double) MathHelper.cos( f1 ) * 1.9D ,
target.blockPosition().below().getY() , this.golem.getZ() + (double) MathHelper.sin( f ) * (int) (distanceToTarget - 2.0D) + (double) MathHelper.sin( f1 ) * 1.9D , f ) );
}
}
BlockPos pos = new BlockPos( this.golem.getX() + (double)MathHelper.cos(f) * 1.25D * (int)(distanceToTarget - 2.0D),
target.blockPosition().getY() ,this.golem.getZ() + (double)MathHelper.sin(f) * (int)(distanceToTarget - 2.0D) );
if(target.level.getBlockState(pos.below()).isFaceSturdy(target.level, pos, Direction.UP)){
target.level.addFreshEntity( EnragedGolemSpikeEntity.createEnragedGolemSpikeEntity( target.level ,
this.golem.getX() + (double) MathHelper.cos( f ) * 1.25D * (int) (distanceToTarget - 2.0D) ,
target.blockPosition().getY() , this.golem.getZ() + (double) MathHelper.sin( f ) * (int) (distanceToTarget - 2.0D) , f ) );
} else if(target.level.getBlockState(pos.below(2)).isFaceSturdy(target.level, pos.below(), Direction.UP)){
target.level.addFreshEntity( EnragedGolemSpikeEntity.createEnragedGolemSpikeEntity( target.level ,
this.golem.getX() + (double) MathHelper.cos( f ) * 1.25D * (int) (distanceToTarget - 2.0D) ,
target.blockPosition().below().getY() , this.golem.getZ() + (double) MathHelper.sin( f ) * (int) (distanceToTarget - 2.0D) , f ) );
}
}
private boolean isReachable(LivingEntity pTarget) {
return golem.blockPosition().getY() == pTarget.blockPosition().getY() || golem.blockPosition().below().getY() == pTarget.blockPosition().getY()
|| golem.blockPosition().below(2).getY() == pTarget.blockPosition().getY() || golem.blockPosition().below(3).getY() == pTarget.blockPosition().getY();
}
@Override
public boolean isInterruptable(){
return false;
}
}
}
| 46.274747
| 317
| 0.603292
|
2fa4e3287eb63dee73efab9f2e6071bd5dcf4d25
| 3,979
|
/*
* Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product may include a number of subcomponents with separate copyright notices
* and license terms. Your use of these subcomponents is subject to the terms and
* conditions of the subcomponent's license, as noted in the LICENSE file.
*/
package com.vmware.mangle.agent.tests;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.jboss.byteman.agent.submit.Submit;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.vmware.mangle.java.agent.utils.ThreadUtils;
/**
* @author hkilari
*
*/
public class AgentRemediateFaultTest {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream standard = System.out;
String userDir = null;
@BeforeClass
public void installAgent() {
AgentTestUtils.installAgent(baos);
}
@AfterClass(alwaysRun = true)
public void clearAgent() {
AgentTestUtils.forceExit(baos, standard);
}
@Test
public void bytemanFaultRemediationTest() {
Submit.main(new String[] { "-if", "__timeoutVariance", "2000", "__gap", "20000", "__gapVariance", "5000",
"__loadVariance", "30", "__longLasting", "true", "__faultName", "cpuFault", "__timeOutInMilliSeconds",
"10000", "__load", "30" });
Assert.assertTrue(baos.toString().contains("Created Fault Successfully"), baos.toString());
String faultId =
RegularExpressionUtils.extractField(baos.toString(), "[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}");
Assert.assertTrue(faultId != null && !faultId.trim().equals(""));
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Submit.main(new String[] { "-llf" });
Assert.assertTrue(baos.toString().contains("{\"" + faultId + "\":\"cpuFault\"}"), baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
ThreadUtils.delayInSeconds(2);
Submit.main(new String[] { "-rf", faultId });
Assert.assertTrue(baos.toString().contains("Received Remediation Request Successfully"), baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Submit.main(new String[] { "-rf", faultId });
Assert.assertTrue(baos.toString().contains("Requested Fault is already Remediated."), baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Submit.main(new String[] { "-rf", "bcdadaa0-33ea-4ef5-b19e-d25a66a6bd70" });
Assert.assertTrue(
baos.toString().contains("No fault found with provided ID: bcdadaa0-33ea-4ef5-b19e-d25a66a6bd70"),
baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Submit.main(new String[] { "-rf", "" });
Assert.assertTrue(baos.toString().contains("No fault found with provided ID:"), baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Submit.main(new String[] { "-rf", " " });
Assert.assertTrue(baos.toString().contains("No fault found with provided ID:"), baos.toString());
try {
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 35.212389
| 119
| 0.589847
|
1f3038333a301a64695f59e7c328099f3382b6b5
| 643
|
package twitter4jads.models.ads;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* @author niketkhandelwal
*/
public class PollEntity implements Serializable {
@SerializedName("options")
private List<PollOption> options;
@SerializedName("end_datetime")
private String endDateTime;
@SerializedName("duration_minutes")
private String durationMinutes;
public static class PollOption implements Serializable {
@SerializedName("position")
private Integer position;
@SerializedName("text")
private String text;
}
}
| 20.741935
| 60
| 0.720062
|
fc9b4d9541335ce923b6ad0f4ce88bbb03bca355
| 11,803
|
// Generated from C:/Users/mayn/Downloads/antlr4/app/src/main/java/com/jsdroid/antlr4/lua\Lua.g4 by ANTLR 4.7.2
package com.jsdroid.antlr4.lua;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link LuaListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class LuaBaseListener implements LuaListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterChunk(LuaParser.ChunkContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitChunk(LuaParser.ChunkContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterBlock(LuaParser.BlockContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitBlock(LuaParser.BlockContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterStat(LuaParser.StatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitStat(LuaParser.StatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterRetstat(LuaParser.RetstatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitRetstat(LuaParser.RetstatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLabel(LuaParser.LabelContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLabel(LuaParser.LabelContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFuncname(LuaParser.FuncnameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFuncname(LuaParser.FuncnameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVarlist(LuaParser.VarlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVarlist(LuaParser.VarlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNamelist(LuaParser.NamelistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNamelist(LuaParser.NamelistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExplist(LuaParser.ExplistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExplist(LuaParser.ExplistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterExp(LuaParser.ExpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitExp(LuaParser.ExpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVar(LuaParser.VarContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVar(LuaParser.VarContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterPrefixexp(LuaParser.PrefixexpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitPrefixexp(LuaParser.PrefixexpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunctioncall(LuaParser.FunctioncallContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunctioncall(LuaParser.FunctioncallContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVarOrExp(LuaParser.VarOrExpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVarOrExp(LuaParser.VarOrExpContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNameAndArgs(LuaParser.NameAndArgsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNameAndArgs(LuaParser.NameAndArgsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVarSuffix(LuaParser.VarSuffixContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVarSuffix(LuaParser.VarSuffixContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArgs(LuaParser.ArgsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArgs(LuaParser.ArgsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunctiondef(LuaParser.FunctiondefContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunctiondef(LuaParser.FunctiondefContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFuncbody(LuaParser.FuncbodyContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFuncbody(LuaParser.FuncbodyContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterParlist(LuaParser.ParlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitParlist(LuaParser.ParlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTableconstructor(LuaParser.TableconstructorContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTableconstructor(LuaParser.TableconstructorContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFieldlist(LuaParser.FieldlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFieldlist(LuaParser.FieldlistContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterField(LuaParser.FieldContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitField(LuaParser.FieldContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFieldsep(LuaParser.FieldsepContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFieldsep(LuaParser.FieldsepContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorOr(LuaParser.OperatorOrContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorOr(LuaParser.OperatorOrContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorAnd(LuaParser.OperatorAndContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorAnd(LuaParser.OperatorAndContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorComparison(LuaParser.OperatorComparisonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorComparison(LuaParser.OperatorComparisonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorStrcat(LuaParser.OperatorStrcatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorStrcat(LuaParser.OperatorStrcatContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorAddSub(LuaParser.OperatorAddSubContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorAddSub(LuaParser.OperatorAddSubContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorMulDivMod(LuaParser.OperatorMulDivModContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorMulDivMod(LuaParser.OperatorMulDivModContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorUnary(LuaParser.OperatorUnaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorUnary(LuaParser.OperatorUnaryContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperatorPower(LuaParser.OperatorPowerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperatorPower(LuaParser.OperatorPowerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNumber(LuaParser.NumberContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNumber(LuaParser.NumberContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterString(LuaParser.StringContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitString(LuaParser.StringContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
}
| 26.404922
| 111
| 0.679404
|
2d9190d3cb011090880c256e774fbfc9ab312a8b
| 3,334
|
/*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*/
package de.uripura.Command;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
public class CommandTeleport implements CommandExecutor {
FileConfiguration conf;
public CommandTeleport(FileConfiguration config) {
this.conf = config;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + conf.getString(
"msg.generic.error-player-only"));
return true;
}
Player player = (Player) sender;
Location location;
PlayerList list = new PlayerList(sender.getServer());
if (!player.hasPermission("command.tp")) {
player.sendMessage(ChatColor.RED + conf.getString(
"msg.generic.error-permission"));
return true;
}
if (args.length == 0) {
player.sendMessage(ChatColor.RED + conf.getString(
"msg.generic.error-to-few-arguments"));
return true;
}
if (args.length == 1) {
if (args[0].contains(",")) {
// Split argument and extract coordinates
String[] strCoords = args[0].split(",");
if (strCoords.length != 3) {
player.sendMessage(ChatColor.YELLOW + conf.getString(
"msg.teleport.num-coords"));
return true;
}
try {
location = new Location(player.getWorld(),
Double.parseDouble(strCoords[0]),
Double.parseDouble(strCoords[1]),
Double.parseDouble(strCoords[2]));
player.teleport(location);
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + conf.getString(
"msg.teleport.not-num"));
return true;
}
return true;
} else {
Player tmpPlay = list.getPlayerFromName(args[0]);
// Check if we want to the player,
// or the player wants to us
if (label.equalsIgnoreCase("tphere")) {
tmpPlay.teleport(player.getLocation());
} else {
player.teleport(tmpPlay.getLocation());
}
return true;
}
}
if (args.length == 2)
{
Player p1, p2;
p1 = list.getPlayerFromName(args[0]);
p2 = list.getPlayerFromName(args[1]);
if (p1 != null && p2 != null) {
p1.teleport(p2);
} else {
sender.sendMessage(ChatColor.RED + conf.getString(
"msg.generic.error-player-not-found"));
}
return true;
}
if (args.length == 3)
{
try {
location = new Location(player.getWorld(),
Double.parseDouble(args[0]),
Double.parseDouble(args[1]),
Double.parseDouble(args[2]));
player.teleport(location);
return true;
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED + conf.getString(
"msg.teleport.error-not-num"));
return true;
}
}
return false;
}
}
| 26.460317
| 75
| 0.643671
|
b9a9e08b3aa0056ecf01dc3734e1b5d62b8d9d15
| 3,270
|
/** Generated Assertion Class - DO NOT CHANGE */
package au.org.greekwelfaresa.idempiere.test.assertj.ad_pinstance_log;
import au.org.greekwelfaresa.idempiere.test.assertj.po.AbstractPOAssert;
import java.util.Objects;
import javax.annotation.Generated;
import org.compiere.model.X_AD_PInstance_Log;
/** Generated assertion class for AD_PInstance_Log
* @author idempiere-test (generated)
* @version Release 6.2 - $Id: b9a9e08b3aa0056ecf01dc3734e1b5d62b8d9d15 $ */
@Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator")
public abstract class AbstractAD_PInstance_LogAssert<SELF extends AbstractAD_PInstance_LogAssert<SELF, ACTUAL>, ACTUAL extends X_AD_PInstance_Log>
extends AbstractPOAssert<SELF, ACTUAL>
{
/** Standard Constructor */
public AbstractAD_PInstance_LogAssert (ACTUAL actual, Class<SELF> selfType)
{
super (actual, selfType);
}
public SELF hasAD_PInstance_ID(int expected)
{
isNotNull();
int actualField = actual.getAD_PInstance_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have AD_PInstance_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasAD_PInstance_Log_UU(String expected)
{
isNotNull();
String actualField = actual.getAD_PInstance_Log_UU();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have AD_PInstance_Log_UU: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasAD_Table_ID(int expected)
{
isNotNull();
int actualField = actual.getAD_Table_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have AD_Table_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasLog_ID(int expected)
{
isNotNull();
int actualField = actual.getLog_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Log_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasP_Date(Object expected)
{
isNotNull();
dateAssert("P_Date", actual.getP_Date(), expected);
return myself;
}
public SELF hasP_ID(int expected)
{
isNotNull();
int actualField = actual.getP_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have P_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasP_Msg(String expected)
{
isNotNull();
String actualField = actual.getP_Msg();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have P_Msg: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasP_Number(Object expected)
{
isNotNull();
bdAssert("P_Number", actual.getP_Number(), expected);
return myself;
}
}
| 31.142857
| 146
| 0.725688
|
2d1e0dbaf817cb6bdbebefce861f3fe758256a8a
| 459
|
package com.mdimension.jchronic.handlers;
import java.util.List;
import com.mdimension.jchronic.Options;
import com.mdimension.jchronic.utils.Span;
import com.mdimension.jchronic.utils.Token;
public class SRPAHandler extends SRPHandler {
@Override
public Span handle(List<Token> tokens, Options options) {
Span anchorSpan = Handler.getAnchor(tokens.subList(3, tokens.size()), options);
return super.handle(tokens, anchorSpan, options);
}
}
| 25.5
| 83
| 0.771242
|
3d9b69fe5537bd3b1ad57df4e6cb97e465c69f7e
| 5,123
|
/*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.spi.discovery;
import org.apache.ignite.Ignite;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.managers.discovery.DiscoCache;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap;
import org.apache.ignite.internal.util.GridConcurrentHashSet;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests discovery cache reuse between topology events.
*/
@RunWith(JUnit4.class)
public class IgniteDiscoveryCacheReuseSelfTest extends GridCommonAbstractTest {
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
stopAllGrids();
super.afterTest();
}
/**
* Tests correct reuse of discovery cache.
*
* @throws Exception If failed.
*/
@Test
public void testDiscoCacheReuseOnNodeJoin() throws Exception {
startGridsMultiThreaded(2);
// The final topology version after 2 node joins and one CacheAffinityChange message.
AffinityTopologyVersion waited = new AffinityTopologyVersion(2, 1);
// Wait for this topology version on all grids.
GridTestUtils.waitForCondition(() -> {
boolean verChanged = true;
for (Ignite ignite : G.allGrids())
verChanged &= ((IgniteEx) ignite).context().discovery().topologyVersionEx().equals(waited);
return verChanged;
}, 5000);
assertDiscoCacheReuse(new AffinityTopologyVersion(2, 0), new AffinityTopologyVersion(2, 1));
}
/**
* Assert disco cache reuse.
*
* @param v1 First version.
* @param v2 Next version.
*/
private void assertDiscoCacheReuse(AffinityTopologyVersion v1, AffinityTopologyVersion v2) {
for (Ignite ignite : G.allGrids()) {
GridBoundedConcurrentLinkedHashMap<AffinityTopologyVersion, DiscoCache> discoCacheHist =
U.field(((IgniteEx) ignite).context().discovery(), "discoCacheHist");
DiscoCache discoCache1 = discoCacheHist.get(v1);
DiscoCache discoCache2 = discoCacheHist.get(v2);
assertEquals(v1, discoCache1.version());
assertEquals(v2, discoCache2.version());
String[] props = new String[] {
"state", "loc", "rmtNodes", "allNodes", "srvNodes", "daemonNodes", "rmtNodesWithCaches",
"allCacheNodes", "allCacheNodes", "cacheGrpAffNodes", "nodeMap", "minNodeVer"
};
for (String prop : props)
assertSame(U.field(discoCache1, prop), U.field(discoCache2, prop));
assertNotSame(U.field(discoCache1, "alives"), U.field(discoCache2, "alives"));
GridConcurrentHashSet alives1 = U.field(discoCache1, "alives");
GridConcurrentHashSet alives2 = U.field(discoCache2, "alives");
assertEquals("Discovery caches are not equal", alives1, alives2);
}
}
}
| 43.05042
| 107
| 0.707203
|
6f80b2a4fa5dbba099456960348fc353ceb4d005
| 271
|
package com.orange1988.photoselector.base;
import android.view.View;
import butterknife.ButterKnife;
/**
* Created by Mr. Orange on 15/11/26.
*/
public abstract class PSViewHolder {
public PSViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
| 16.9375
| 42
| 0.704797
|
89101bd95d39dc935fb9aeb3241b8ef49cb45108
| 4,952
|
/*
* Copyright 2018 Dmitry Ustalov
*
* 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.nlpub.watset.cli;
import com.beust.jcommander.JCommander;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
/**
* Watset command-line interface.
*/
public final class Application implements Runnable {
/**
* Status of command-line argument parsing.
*/
public enum ParseStatus {
/**
* A command has been parsed successfully.
*/
COMMAND,
/**
* No command has been found.
*/
EMPTY,
/**
* No command has been found, but the version has been requested.
*/
EMPTY_BUT_VERSION
}
/**
* The command-line argument parser.
*/
private final JCommander jc;
/**
* The parsing status.
*/
private ParseStatus status = ParseStatus.EMPTY;
/**
* Watset command-line interface entry point.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
final var app = new Application();
switch (app.parse(args)) {
case COMMAND:
case EMPTY_BUT_VERSION:
app.run();
break;
default:
app.jc.usage();
System.exit(1);
break;
}
}
/**
* Create an instance of the Watset command-line interface.
*/
public Application() {
final var parameters = new Command.MainParameters();
// TODO: Use the main argument for --input instead of the named one.
jc = JCommander.newBuilder()
.addObject(parameters)
.addCommand("empty", new ProvidedClusteringCommand(parameters, "empty"))
.addCommand("singleton", new ProvidedClusteringCommand(parameters, "singleton"))
.addCommand("together", new ProvidedClusteringCommand(parameters, "together"))
.addCommand("components", new ProvidedClusteringCommand(parameters, "components"))
.addCommand("gn", new ProvidedClusteringFixedKCommand(parameters, "gn"))
.addCommand("kst", new ProvidedClusteringFixedKCommand(parameters, "kst"))
.addCommand("spectral", new SpectralClusteringCommand(parameters))
.addCommand("cw", new ChineseWhispersCommand(parameters))
.addCommand("mcl", new MarkovClusteringCommand(parameters))
.addCommand("mcl-bin", new MarkovClusteringExternalCommand(parameters))
.addCommand("embed", new EmbeddingCommand(parameters))
.addCommand("senses", new SensesCommand(parameters))
.addCommand("graph", new GraphCommand(parameters))
.addCommand("embedsenses", new SenseEmbeddingCommand(parameters))
.addCommand("watset", new WatsetCommand(parameters))
.addCommand("maxmax", new ProvidedClusteringCommand(parameters, "maxmax"))
.addCommand("pairwise", new PairwiseCommand(parameters))
.addCommand("purity", new PurityCommand(parameters))
.addCommand("version", new VersionCommand(parameters))
.build();
}
/**
* Parse the command-line arguments.
*
* @param args the command-line arguments
* @return the status
*/
public ParseStatus parse(String... args) {
status = ParseStatus.EMPTY;
jc.parse(args);
final var parameters = (Command.MainParameters) jc.getObjects().get(0);
if (nonNull(jc.getParsedCommand())) {
status = ParseStatus.COMMAND;
} else if (parameters.version) {
status = ParseStatus.EMPTY_BUT_VERSION;
}
return status;
}
/**
* Run the parsed command.
*/
@Override
public void run() {
final var command = status == ParseStatus.EMPTY_BUT_VERSION ?
"version" :
requireNonNull(jc.getParsedCommand(), "command should not be null");
run(command);
}
/**
* Run the specified command.
*
* @param command the command
*/
public void run(String command) {
final var objects = jc.getCommands().get(command).getObjects();
final var runnable = (Command) objects.get(0);
runnable.run();
}
}
| 31.948387
| 98
| 0.605816
|
13b2bc65a15f3ba1be9e614a54bc2a477fb3b05e
| 6,106
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.localization;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.MecanumDriveOdometry;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.drive.DriveSubsystem;
import frc.robot.imu.ImuSubsystem;
import frc.robot.misc.util.LoggingUtil;
import frc.robot.vision_cargo.CargoVisionSubsystem;
import frc.robot.vision_cargo.UpperHubVisionTarget;
import frc.robot.vision_upper.TimestampedPose2d;
import java.util.Optional;
import lib.wpilib.MecanumDrivePoseEstimator;
import org.ejml.data.SingularMatrixException;
import org.littletonrobotics.junction.Logger;
/** Used for combining sensor data to localize the robot on the field. */
public class Localization extends SubsystemBase {
/** Returns whether a translation is within the bounds of the field. */
public static boolean translationIsValid(Translation2d translation) {
final var x = translation.getX();
final var y = translation.getY();
return x >= 0 && y >= 0 && x <= Constants.FIELD_WIDTH && y <= Constants.FIELD_HEIGHT;
}
/** Returns whether a pose is within the bounds of the field. */
public static boolean poseIsValid(Pose2d pose) {
return translationIsValid(pose.getTranslation());
}
private final DriveSubsystem driveSubsystem;
private final CargoVisionSubsystem visionSubsystem;
private final ImuSubsystem imuSubsystem;
private final MecanumDrivePoseEstimator poseEstimator;
private final MecanumDriveOdometry odometry;
int odometryErrorCount = 0;
int visionErrorCount = 0;
public Localization(
DriveSubsystem driveSubsystem,
CargoVisionSubsystem visionSubsystem,
ImuSubsystem imuSubsystem,
Pose2d initialRobotPose) {
this.driveSubsystem = driveSubsystem;
this.visionSubsystem = visionSubsystem;
this.imuSubsystem = imuSubsystem;
final var initialHeading = imuSubsystem.getRotation();
poseEstimator =
new MecanumDrivePoseEstimator(
// Initial heading
initialHeading,
// Initial position
initialRobotPose,
DriveSubsystem.KINEMATICS,
// Standard deviations of wheel odometry x, y, and theta
VecBuilder.fill(0.05, 0.05, Units.degreesToRadians(5)),
// Standard deviation of gyroscope heading
VecBuilder.fill(Units.degreesToRadians(0.01)),
// Vision measurement standard deviations
VecBuilder.fill(0.5, 0.5, Units.degreesToRadians(30)),
Constants.PERIOD_SECONDS);
odometry =
new MecanumDriveOdometry(DriveSubsystem.KINEMATICS, initialHeading, initialRobotPose);
}
public Localization(
DriveSubsystem driveSubsystem,
CargoVisionSubsystem visionSubsystem,
ImuSubsystem imuSubsystem) {
this(
driveSubsystem,
visionSubsystem,
imuSubsystem,
// Default to being in the center of the field
// This should only really be used for debugging
new Pose2d(UpperHubVisionTarget.COORDINATES, new Rotation2d()));
}
@Override
public void periodic() {
final var rotation = imuSubsystem.getRotation();
final var wheelSpeeds = driveSubsystem.getWheelSpeeds();
final var odometryPose = odometry.update(rotation, wheelSpeeds);
// The robot's position, just using odometry
Logger.getInstance()
.recordOutput("Localization/OdometryPose", LoggingUtil.poseToArray(odometryPose));
try {
final var localizationPose = poseEstimator.update(imuSubsystem.getRotation(), wheelSpeeds);
// The robot's position using both odometry and vision
Logger.getInstance()
.recordOutput("Localization/RobotPose", LoggingUtil.poseToArray(localizationPose));
} catch (SingularMatrixException e) {
// Ignore errors that occur from an unsolvable matrix due to uncountable numbers
// This seems to periodically happen when driving around IRL with the camera on
// This is probably from the Cholesky decomposition not finding a solution
odometryErrorCount++;
}
try {
final var optionalVisionPose = getRawVisionPose();
if (optionalVisionPose.isPresent()) {
final var visionPose = optionalVisionPose.get();
// The robot's position, just using the vision data
Logger.getInstance()
.recordOutput("Localization/VisionPose", LoggingUtil.poseToArray(visionPose.pose));
poseEstimator.addVisionMeasurement(visionPose.pose, visionPose.timestamp);
}
} catch (SingularMatrixException e) {
// Ignore errors that occur from an unsolvable matrix due to uncountable numbers
// This seems to periodically happen when driving around IRL with the camera on
// This is probably from the Cholesky decomposition not finding a solution
visionErrorCount++;
}
Logger.getInstance().recordOutput("Localization/Errors/OdometryErrorCount", odometryErrorCount);
Logger.getInstance().recordOutput("Localization/Errors/VisionErrorCount", visionErrorCount);
}
/** Returns the robot's position using both vision and odometry. */
public Pose2d getPose() {
return poseEstimator.getEstimatedPosition();
}
public void resetPose(Pose2d robotPose) {
imuSubsystem.resetHeadingTo(robotPose.getRotation());
poseEstimator.resetPosition(robotPose, imuSubsystem.getRotation());
odometry.resetPosition(robotPose, imuSubsystem.getRotation());
}
/**
* Returns the robot pose from the vision system directly, if available. You probably want to use
* {@link #getPose()} instead.
*/
private Optional<TimestampedPose2d> getRawVisionPose() {
return visionSubsystem.getPastRobotPose();
}
}
| 38.1625
| 100
| 0.731575
|
3d37778dfe064991bb84ec3a2b5c5a53bf3d4685
| 1,718
|
/*
* Copyright 2019, 2020 grondag
*
* 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 grondag.canvas.apiimpl.util;
import net.minecraft.util.math.Direction;
import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper;
public class FaceConstants {
public static final int NORTH_INDEX = ModelHelper.toFaceIndex(Direction.NORTH);
public static final int SOUTH_INDEX = ModelHelper.toFaceIndex(Direction.SOUTH);
public static final int EAST_INDEX = ModelHelper.toFaceIndex(Direction.EAST);
public static final int WEST_INDEX = ModelHelper.toFaceIndex(Direction.WEST);
public static final int UP_INDEX = ModelHelper.toFaceIndex(Direction.UP);
public static final int DOWN_INDEX = ModelHelper.toFaceIndex(Direction.DOWN);
public static final int UNASSIGNED_INDEX = ModelHelper.NULL_FACE_ID;
public static final int NORTH_FLAG = 1 << NORTH_INDEX;
public static final int SOUTH_FLAG = 1 << SOUTH_INDEX;
public static final int EAST_FLAG = 1 << EAST_INDEX;
public static final int WEST_FLAG = 1 << WEST_INDEX;
public static final int UP_FLAG = 1 << UP_INDEX;
public static final int DOWN_FLAG = 1 << DOWN_INDEX;
public static final int UNASSIGNED_FLAG = 1 << UNASSIGNED_INDEX;
}
| 42.95
| 81
| 0.770081
|
84d50f3e84dc6bc0dd65fdc9575d5fbfff1536e1
| 1,677
|
package dev.bstk.gameokk.plataforma.usuarios.domain;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
@AllArgsConstructor
public class UsuarioService {
private final UsuarioRepository usuarioRepository;
public Usuario cadastraNovoUsuario(final Usuario usuario) {
validarDadosUsuario(usuario);
usuarioRepository.save(usuario);
return usuario;
}
/// TODO: REFATORAR LÓGICA PARA ATUALIZAR DADOS DE UM USUÁRIO
public Usuario atualizarUsuario(final Usuario usuario) {
validarDadosUsuario(usuario);
usuarioRepository.save(usuario);
return usuario;
}
public Usuario usuarioPorApelido(final String apelido) {
return usuarioRepository.usuarioPorApelido(apelido);
}
public List<Usuario> usuarios() {
return usuarioRepository.findAll();
}
private void validarDadosUsuario(final Usuario usuario) {
Objects.requireNonNull(usuario, "Dados do usuário não podem ser nulos!");
final boolean existeUsuarioComEmailJaCadastrado = usuarioRepository.existeUsuarioComEmailJaCadastrado(usuario.getEmail());
if (existeUsuarioComEmailJaCadastrado) {
throw new IllegalArgumentException("Usuário ja castrado para o email: " + usuario.getEmail());
}
final boolean existeUsuarioComApelidoJaCadastrado = usuarioRepository.existeUsuarioComApelidoJaCadastrado(usuario.getApelido());
if (existeUsuarioComApelidoJaCadastrado) {
throw new IllegalArgumentException("Apelido já existe: " + usuario.getApelido());
}
}
}
| 31.641509
| 136
| 0.730471
|
c52677b7655c778e2968f7dddeae9570c9bdcdef
| 1,713
|
package com.alibaba.sreworks.dataset.domain.req.inter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 数据接口配置信息
*
* @author: fangzong.lyj@alibaba-inc.com
* @date: 2021/07/21 17:04
*/
@Data
@ApiModel(value="数据接口配置信息")
public class DataInterfaceConfigBaseReq {
@ApiModelProperty(value = "接口标识", example = "appId")
String label;
@ApiModelProperty(value = "接口名称", example = "应用ID")
String name;
// @ApiModelProperty(value = "内置接口", example = "false")
// Boolean buildIn;
@ApiModelProperty(value = "归属模型ID", example = "1")
Integer modelId;
@ApiModelProperty(value = "团队ID", example = "0")
Integer teamId;
@ApiModelProperty(value = "创建人", example = "sreworks")
String creator;
@ApiModelProperty(value = "负责人", example = "sreworks")
String owners;
@ApiModelProperty(value = "请求方法", example = "GET")
String requestMethod;
@ApiModelProperty(value = "媒体类型", example = "application/json")
String contentType;
@ApiModelProperty(value = "响应字段列表", example = "a,b,c")
String responseFields;
@ApiModelProperty(value = "排序字段列表")
DataInterfaceSortFieldReq[] sortFields;
@ApiModelProperty(value = "分页", example = "false")
Boolean paging;
public DataInterfaceSortFieldReq[] getSortFields() {
if (sortFields != null) {
// 检查字段是否合法
for (DataInterfaceSortFieldReq sortFieldReq : sortFields) {
sortFieldReq.getFieldName();
sortFieldReq.getOrder();
sortFieldReq.getMode();
sortFieldReq.getFormat();
}
}
return sortFields;
}
}
| 25.954545
| 71
| 0.642148
|
fa1ce3032a51f08b681f08f017e05eeb0f05ad57
| 50
|
package ewhine.models;
public class Message {
}
| 8.333333
| 22
| 0.74
|
2963d9e1d34d73e7b5eba42f382747a79aca0819
| 4,866
|
package com.mapswithme.maps.purchase;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
abstract class AbstractPurchaseController<V, B, UiCallback extends PurchaseCallback>
implements PurchaseController<UiCallback>
{
private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.BILLING);
private static final String TAG = AbstractPurchaseController.class.getSimpleName();
@NonNull
private final PurchaseValidator<V> mValidator;
@NonNull
private final BillingManager<B> mBillingManager;
@Nullable
private UiCallback mUiCallback;
@Nullable
private final List<String> mProductIds;
AbstractPurchaseController(@NonNull PurchaseValidator<V> validator,
@NonNull BillingManager<B> billingManager,
@Nullable String... productIds)
{
mValidator = validator;
mBillingManager = billingManager;
mProductIds = productIds != null ? Collections.unmodifiableList(Arrays.asList(productIds))
: null;
}
@Override
public final void initialize(@Nullable Activity activity)
{
if (activity == null)
throw new AssertionError("Activity must be non-null");
mBillingManager.initialize(activity);
onInitialize(activity);
}
@Override
public final void destroy()
{
mBillingManager.destroy();
onDestroy();
}
@Override
public void addCallback(@NonNull UiCallback callback)
{
mUiCallback = callback;
}
@Override
public void removeCallback()
{
mUiCallback = null;
}
@Nullable
UiCallback getUiCallback()
{
return mUiCallback;
}
@Override
public boolean isPurchaseSupported()
{
return mBillingManager.isBillingSupported();
}
@Override
public void launchPurchaseFlow(@NonNull String productId)
{
mBillingManager.launchBillingFlowForProduct(productId);
}
@Override
public void queryProductDetails()
{
if (mProductIds == null)
throw new IllegalStateException("Product ids must be non-null!");
getBillingManager().queryProductDetails(mProductIds);
}
@Override
public void validateExistingPurchases()
{
getBillingManager().queryExistingPurchases();
}
@NonNull
PurchaseValidator<V> getValidator()
{
return mValidator;
}
@NonNull
BillingManager<B> getBillingManager()
{
return mBillingManager;
}
@Nullable
final Purchase findTargetPurchase(@NonNull List<Purchase> purchases)
{
if (mProductIds == null)
return null;
for (Purchase purchase: purchases)
{
if (mProductIds.contains(purchase.getSku()))
return purchase;
}
return null;
}
abstract void onInitialize(@NonNull Activity activity);
abstract void onDestroy();
@Override
public void onSave(@NonNull Bundle outState)
{
mValidator.onSave(outState);
}
@Override
public void onRestore(@NonNull Bundle inState)
{
mValidator.onRestore(inState);
}
abstract class AbstractPlayStoreBillingCallback implements PlayStoreBillingCallback
{
@Override
public void onPurchaseSuccessful(@NonNull List<Purchase> purchases)
{
Purchase target = findTargetPurchase(purchases);
if (target == null)
return;
LOGGER.i(TAG, "Validating purchase '" + target.getSku() + " " + target.getOrderId()
+ "' on backend server...");
validate(target.getOriginalJson());
if (getUiCallback() != null)
getUiCallback().onValidationStarted();
}
@Override
public void onProductDetailsLoaded(@NonNull List<SkuDetails> details)
{
if (getUiCallback() != null)
getUiCallback().onProductDetailsLoaded(details);
}
@Override
public void onPurchaseFailure(@BillingClient.BillingResponse int error)
{
if (getUiCallback() != null)
getUiCallback().onPaymentFailure(error);
}
@Override
public void onProductDetailsFailure()
{
if (getUiCallback() != null)
getUiCallback().onProductDetailsFailure();
}
@Override
public void onStoreConnectionFailed()
{
if (getUiCallback() != null)
getUiCallback().onStoreConnectionFailed();
}
@Override
public void onConsumptionSuccess()
{
// Do nothing by default.
}
@Override
public void onConsumptionFailure()
{
// Do nothing by default.
}
abstract void validate(@NonNull String purchaseData);
}
}
| 23.507246
| 100
| 0.691944
|
af7922d5ed37ede4ead79853bcd0e73e10e597d5
| 2,442
|
package com.example.lesiadspro;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class viewNewsMain extends AppCompatActivity {
private RecyclerView recyclerView;
NewspaperAdpter adapter; // Create Object of the Adapter class
DatabaseReference databaseReference; // Create object of the
// Firebase Realtime Database
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_main);
//Testing
//Log.d("abc",user.toString());
// Create a instance of the database and get
// its reference
String uid = FirebaseAuth.getInstance().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("News").child(uid);
Log.d("abc",databaseReference.toString());
recyclerView = findViewById(R.id.recycler1);
// To display the Recycler view linearly
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// It is a class provide by the FirebaseUI to make a
// query in the database to fetch appropriate data
FirebaseRecyclerOptions<AddNews> options = new FirebaseRecyclerOptions.Builder<AddNews>().setQuery(databaseReference, AddNews.class).build();
// Connecting object of required Adapter class to
// the Adapter class itself
adapter = new NewspaperAdpter(options);
// Connecting Adapter class with the Recycler view*/
recyclerView.setAdapter(adapter);
}
// Function to tell the app to start getting
// data from database on starting of the activity
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
// Function to tell the app to stop getting
// data from database on stopping of the activity
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
| 34.885714
| 149
| 0.718264
|
1e5088bef90b29e3f5881916d4fc455b824388d4
| 6,821
|
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.fixes;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.groupingBy;
import com.google.gerrit.common.RawInputUtil;
import com.google.gerrit.extensions.restapi.BinaryResult;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.reviewdb.client.FixReplacement;
import com.google.gerrit.server.change.FileContentUtil;
import com.google.gerrit.server.edit.tree.ChangeFileContentModification;
import com.google.gerrit.server.edit.tree.TreeModification;
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
/** An interpreter for {@code FixReplacement}s. */
@Singleton
public class FixReplacementInterpreter {
private static final Comparator<FixReplacement> ASC_RANGE_FIX_REPLACEMENT_COMPARATOR =
Comparator.comparing(fixReplacement -> fixReplacement.range);
private final FileContentUtil fileContentUtil;
@Inject
public FixReplacementInterpreter(FileContentUtil fileContentUtil) {
this.fileContentUtil = fileContentUtil;
}
/**
* Transforms the given {@code FixReplacement}s into {@code TreeModification}s.
*
* @param repository the affected Git repository
* @param projectState the affected project
* @param patchSetCommitId the patch set which should be modified
* @param fixReplacements the replacements which should be applied
* @return a list of {@code TreeModification}s representing the given replacements
* @throws ResourceNotFoundException if a file to which one of the replacements refers doesn't
* exist
* @throws ResourceConflictException if the replacements can't be transformed into {@code
* TreeModification}s
*/
public List<TreeModification> toTreeModifications(
Repository repository,
ProjectState projectState,
ObjectId patchSetCommitId,
List<FixReplacement> fixReplacements)
throws ResourceNotFoundException, IOException, ResourceConflictException {
checkNotNull(fixReplacements, "Fix replacements must not be null");
Map<String, List<FixReplacement>> fixReplacementsPerFilePath =
fixReplacements.stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
List<TreeModification> treeModifications = new ArrayList<>();
for (Map.Entry<String, List<FixReplacement>> entry : fixReplacementsPerFilePath.entrySet()) {
TreeModification treeModification =
toTreeModification(
repository, projectState, patchSetCommitId, entry.getKey(), entry.getValue());
treeModifications.add(treeModification);
}
return treeModifications;
}
private TreeModification toTreeModification(
Repository repository,
ProjectState projectState,
ObjectId patchSetCommitId,
String filePath,
List<FixReplacement> fixReplacements)
throws ResourceNotFoundException, IOException, ResourceConflictException {
String fileContent = getFileContent(repository, projectState, patchSetCommitId, filePath);
String newFileContent = getNewFileContent(fileContent, fixReplacements);
return new ChangeFileContentModification(filePath, RawInputUtil.create(newFileContent));
}
private String getFileContent(
Repository repository, ProjectState projectState, ObjectId patchSetCommitId, String filePath)
throws ResourceNotFoundException, IOException {
try (BinaryResult fileContent =
fileContentUtil.getContent(repository, projectState, patchSetCommitId, filePath)) {
return fileContent.asString();
}
}
private static String getNewFileContent(String fileContent, List<FixReplacement> fixReplacements)
throws ResourceConflictException {
List<FixReplacement> sortedReplacements = new ArrayList<>(fixReplacements);
sortedReplacements.sort(ASC_RANGE_FIX_REPLACEMENT_COMPARATOR);
LineIdentifier lineIdentifier = new LineIdentifier(fileContent);
StringModifier fileContentModifier = new StringModifier(fileContent);
for (FixReplacement fixReplacement : sortedReplacements) {
Comment.Range range = fixReplacement.range;
try {
int startLineIndex = lineIdentifier.getStartIndexOfLine(range.startLine);
int startLineLength = lineIdentifier.getLengthOfLine(range.startLine);
int endLineIndex = lineIdentifier.getStartIndexOfLine(range.endLine);
int endLineLength = lineIdentifier.getLengthOfLine(range.endLine);
if (range.startChar > startLineLength || range.endChar > endLineLength) {
throw new ResourceConflictException(
String.format(
"Range %s refers to a non-existent offset (start line length: %s,"
+ " end line length: %s)",
toString(range), startLineLength, endLineLength));
}
int startIndex = startLineIndex + range.startChar;
int endIndex = endLineIndex + range.endChar;
fileContentModifier.replace(startIndex, endIndex, fixReplacement.replacement);
} catch (StringIndexOutOfBoundsException e) {
// Most of the StringIndexOutOfBoundsException should never occur because we reject fix
// replacements for invalid ranges. However, we can't cover all cases for efficiency
// reasons. For instance, we don't determine the number of lines in a file. That's why we
// need to map this exception and thus provide a meaningful error.
throw new ResourceConflictException(
String.format("Cannot apply fix replacement for range %s", toString(range)), e);
}
}
return fileContentModifier.getResult();
}
private static String toString(Comment.Range range) {
return String.format(
"(%s:%s - %s:%s)", range.startLine, range.startChar, range.endLine, range.endChar);
}
}
| 44.581699
| 99
| 0.753848
|
b811412a53978cb462d38c1ee97556f011fe762f
| 461
|
package org.pentaho.di.ui.spoon.partition.processor;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.ui.spoon.delegates.SpoonDelegates;
import org.pentaho.di.ui.spoon.partition.PartitionSettings;
/**
* @author Evgeniy_Lyakhov@epam.com
*/
public interface MethodProcessor {
void schemaSelection( PartitionSettings settings, Shell shell, SpoonDelegates delegates ) throws KettleException;
}
| 32.928571
| 115
| 0.815618
|
3c720e0d7bb113372b9dc7e0fd7111949b6701fa
| 3,064
|
/**
* 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.axis2;
import org.apache.axis2.jaxws.message.factory.ClassFinderFactory;
import org.apache.axis2.jaxws.registry.FactoryRegistry;
import org.apache.geronimo.axis2.osgi.GeronimoBundleClassFinder;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.gbean.annotation.GBean;
import org.apache.geronimo.gbean.annotation.ParamSpecial;
import org.apache.geronimo.gbean.annotation.SpecialAttributeType;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* @version $Rev$ $Date$
*/
@GBean
public class Axis2SystemInitializer implements GBeanLifecycle {
private BundleContext bundleContext;
private ServiceReference packageAdminServiceReference;
private GeronimoBundleClassFinder bundleClassFinder;
public Axis2SystemInitializer(@ParamSpecial(type = SpecialAttributeType.bundleContext) BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
@Override
public void doFail() {
try {
doStop();
} catch (Exception e) {
}
}
@Override
public void doStart() throws Exception {
packageAdminServiceReference = bundleContext.getServiceReference(PackageAdmin.class.getName());
PackageAdmin packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminServiceReference);
ClassFinderFactory classFinderFactory = (ClassFinderFactory) FactoryRegistry.getFactory(ClassFinderFactory.class);
bundleClassFinder = new GeronimoBundleClassFinder(packageAdmin);
classFinderFactory.setClassFinder(bundleClassFinder);
bundleContext.addBundleListener(bundleClassFinder);
}
@Override
public void doStop() throws Exception {
ClassFinderFactory classFinderFactory = (ClassFinderFactory) FactoryRegistry.getFactory(ClassFinderFactory.class);
classFinderFactory.setClassFinder(null);
if (packageAdminServiceReference != null) {
try {
bundleContext.ungetService(packageAdminServiceReference);
} catch (Exception e) {
}
}
bundleContext.removeBundleListener(bundleClassFinder);
}
}
| 38.78481
| 122
| 0.749347
|
a24dc3b2437f176370e92839f4447728494aefc5
| 725
|
package st.sql.mapping;
import st.sql.STSQLException;
/** マッピングエラーが発生した際にスローされる例外 */
public class ResultSetMappingException extends STSQLException {
public ResultSetMappingException() {
super();
}
public ResultSetMappingException(Throwable e) {
super(50000, e);
}
public ResultSetMappingException(int errorCode) {
super(errorCode);
}
public ResultSetMappingException(int errorCode, Throwable exception) {
super(errorCode, exception);
}
public ResultSetMappingException(int errorCode, String message) {
super(errorCode, message);
}
public ResultSetMappingException(int errorCode, String message, Throwable exception) {
super(errorCode, message, exception);
}
}
| 22.65625
| 88
| 0.736552
|
944e5728daa16b05567be425c0c960969b3f07de
| 5,355
|
package repast.simphony.visualization.editedStyle;
/**
*
* @author Eric Tatara
*
* @param <T>
*/
public class EditedStyleData<T> implements PaintableStyleData, SizeableStyleData {
protected String shapeWkt;
protected float size;
protected float sizeMax;
protected float sizeMin;
protected float sizeScale;
protected String sizeMethodName;
protected String sizeMaxMethodName;
protected String sizeMinMethodName;
protected String sizeScaleMethodName;
protected String label;
protected String labelMethod;
protected String labelPosition;
protected int labelPrecision;
protected float labelOffset;
protected int labelFontSize;
protected int labelFontType;
protected String labelFontFamily;
protected float[] labelColor;
protected float[] color;
protected String redMethodName;
protected String greenMethodName;
protected String blueMethodName;
protected float[] colorMax;
protected float[] colorMin;
protected float[] colorScale;
protected String iconFile2D;
protected String modelFile3D;
protected String textureFile3D;
public float getSize() {
return size;
}
public float getSizeMax() {
return sizeMax;
}
public float getSizeMin() {
return sizeMin;
}
public float getSizeScale() {
return sizeScale;
}
public String getSizeMaxMethodName() {
return sizeMaxMethodName;
}
public String getSizeMethodName() {
return sizeMethodName;
}
public String getSizeMinMethodName() {
return sizeMinMethodName;
}
public String getSizeScaleMethodName() {
return sizeScaleMethodName;
}
public String getRedMethod() {
return redMethodName;
}
public String getGreenMethod() {
return greenMethodName;
}
public String getBlueMethod() {
return blueMethodName;
}
public String getLabel() {
return label;
}
public String getLabelPosition() {
return labelPosition;
}
public String getLabelMethod() {
return labelMethod;
}
public float getLabelOffset() {
return labelOffset;
}
public void setSize(float size) {
this.size = size;
}
public void setSizeMax(float sizeMax) {
this.sizeMax = sizeMax;
}
public void setSizeMin(float sizeMin) {
this.sizeMin = sizeMin;
}
public void setSizeScale(float sizeScale) {
this.sizeScale = sizeScale;
}
public void setSizeMaxMethodName(String sizeMaxMethodName) {
this.sizeMaxMethodName = sizeMaxMethodName;
}
public void setSizeMethodName(String sizeMethodName) {
this.sizeMethodName = sizeMethodName;
}
public void setSizeMinMethodName(String sizeMinMethodName) {
this.sizeMinMethodName = sizeMinMethodName;
}
public void setSizeScaleMethodName(String sizeScaleMethodName) {
this.sizeScaleMethodName = sizeScaleMethodName;
}
public void setLabel(String label) {
this.label = label;
}
public void setLabelPosition(String angle) {
this.labelPosition = angle;
}
public void setLabelMethod(String labelMethod) {
this.labelMethod = labelMethod;
}
public void setLabelOffset(float offset) {
this.labelOffset = offset;
}
public void setRedMethod(String redMethod) {
this.redMethodName = redMethod;
}
public void setGreenMethod(String greenMethod) {
this.greenMethodName = greenMethod;
}
public void setBlueMethod(String blueMethod) {
this.blueMethodName = blueMethod;
}
public float[] getColorMax() {
return colorMax;
}
public void setColorMax(float[] colorMax) {
this.colorMax = colorMax;
}
public float[] getColorMin() {
return colorMin;
}
public void setColorMin(float[] colorMin) {
this.colorMin = colorMin;
}
public float[] getColorScale() {
return colorScale;
}
public void setColorScale(float[] colorScale) {
this.colorScale = colorScale;
}
public float[] getColor() {
return color;
}
public void setColor(float[] color) {
this.color = color;
}
public int getLabelFontSize() {
return labelFontSize;
}
public void setLabelFontSize(int labelFontSize) {
this.labelFontSize = labelFontSize;
}
public int getLabelFontType() {
return labelFontType;
}
public void setLabelFontType(int labelFontType) {
this.labelFontType = labelFontType;
}
public String getLabelFontFamily() {
return labelFontFamily;
}
public void setLabelFontFamily(String labelFontFamily) {
this.labelFontFamily = labelFontFamily;
}
public float[] getLabelColor() {
return labelColor;
}
public void setLabelColor(float[] labelColor) {
this.labelColor = labelColor;
}
public String getShapeWkt() {
return shapeWkt;
}
public void setShapeWkT(String shapeWkt) {
this.shapeWkt = shapeWkt;
}
public String getIconFile2D() {
return iconFile2D;
}
public void setIconFile2D(String iconFile2D) {
this.iconFile2D = iconFile2D;
}
public String getModelFile3D() {
return modelFile3D;
}
public void setModelFile3D(String modelFile3D) {
this.modelFile3D = modelFile3D;
}
public String getTextureFile3D() {
return textureFile3D;
}
public void setTextureFile3D(String textureFile3D) {
this.textureFile3D = textureFile3D;
}
public int getLabelPrecision() {
return labelPrecision;
}
public void setLabelPrecision(int labelPrecision) {
this.labelPrecision = labelPrecision;
}
}
| 24.121622
| 83
| 0.720448
|
5d7a87c5b73950e7bfc6db8cf67d2f3af2018057
| 760
|
package com.wepay.waltz.common.metadata;
import com.wepay.zktools.zookeeper.serializer.SerializerHelper;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Implements the methods to serialize and deserialize {@link GroupDescriptor} object.
*/
public class GroupDescriptorSerializer extends SerializerHelper<GroupDescriptor> {
public static final GroupDescriptorSerializer INSTANCE = new GroupDescriptorSerializer();
@Override
public void serialize(GroupDescriptor groupDescriptor, DataOutput out) throws IOException {
groupDescriptor.writeTo(out);
}
@Override
public GroupDescriptor deserialize(DataInput in) throws IOException {
return GroupDescriptor.readFrom(in);
}
}
| 28.148148
| 95
| 0.775
|
54570524fd84b6dcf46cd7aebc0bcc0f1b4e71ea
| 896
|
package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class CountUppercaseWords {
public static void main(String[] args) {
try(BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in))){
var inputString = bfr.readLine();
Predicate<String> isUpperCase = n -> Character.isUpperCase(n.charAt(0));
var upperCaseWords = Arrays.stream(inputString.split("\\s+"))
.filter(n -> isUpperCase.test(n))
.collect(Collectors.toList());
System.out.println(upperCaseWords.size());
upperCaseWords.forEach(n -> System.out.println(n));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 35.84
| 87
| 0.646205
|
0866779826981758cf4d25da4d2cde6df4d8179a
| 1,172
|
package rainbow.db.refinery;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import rainbow.core.bundle.Bean;
import rainbow.core.bundle.Extension;
import rainbow.core.util.converter.Converters;
import rainbow.db.dao.model.Column;
@Bean
@Extension
public class DateTimeRefinery implements Refinery {
@Override
public String getName() {
return "datetime";
}
@Override
public RefineryDef accept(Column column) {
switch (column.getType()) {
case TIMESTAMP:
return makeDef(true, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss");
case DATE:
return makeDef(true, "yyyy-MM-dd", "yyyy年MM月dd日");
default:
return null;
}
}
@Override
public Object refine(Column column, Object data, String param) {
if (data == null)
return null;
switch (column.getType()) {
case TIMESTAMP:
LocalDateTime datetime = Converters.convert(data, LocalDateTime.class);
return DateTimeFormatter.ofPattern(param).format(datetime);
case DATE:
LocalDate date = Converters.convert(data, LocalDate.class);
return DateTimeFormatter.ofPattern(param).format(date);
default:
return data;
}
}
}
| 23.44
| 74
| 0.734642
|
3b060bfd2346ba037ff450b59177038ad411e574
| 6,170
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|hbtop
operator|.
name|terminal
operator|.
name|impl
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Objects
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|hbtop
operator|.
name|terminal
operator|.
name|Attributes
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|hbtop
operator|.
name|terminal
operator|.
name|Color
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|yetus
operator|.
name|audience
operator|.
name|InterfaceAudience
import|;
end_import
begin_comment
comment|/** * Represents a single text cell of the terminal. */
end_comment
begin_class
annotation|@
name|InterfaceAudience
operator|.
name|Private
specifier|public
class|class
name|Cell
block|{
specifier|private
specifier|static
specifier|final
name|char
name|UNSET_VALUE
init|=
operator|(
name|char
operator|)
literal|65535
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|char
name|END_OF_LINE
init|=
literal|'\0'
decl_stmt|;
specifier|private
specifier|final
name|Attributes
name|attributes
decl_stmt|;
specifier|private
name|char
name|ch
decl_stmt|;
specifier|public
name|Cell
parameter_list|()
block|{
name|attributes
operator|=
operator|new
name|Attributes
argument_list|()
expr_stmt|;
name|ch
operator|=
literal|' '
expr_stmt|;
block|}
specifier|public
name|char
name|getChar
parameter_list|()
block|{
return|return
name|ch
return|;
block|}
specifier|public
name|void
name|setChar
parameter_list|(
name|char
name|ch
parameter_list|)
block|{
name|this
operator|.
name|ch
operator|=
name|ch
expr_stmt|;
block|}
specifier|public
name|void
name|reset
parameter_list|()
block|{
name|attributes
operator|.
name|reset
argument_list|()
expr_stmt|;
name|ch
operator|=
literal|' '
expr_stmt|;
block|}
specifier|public
name|void
name|unset
parameter_list|()
block|{
name|attributes
operator|.
name|reset
argument_list|()
expr_stmt|;
name|ch
operator|=
name|UNSET_VALUE
expr_stmt|;
block|}
specifier|public
name|void
name|endOfLine
parameter_list|()
block|{
name|attributes
operator|.
name|reset
argument_list|()
expr_stmt|;
name|ch
operator|=
name|END_OF_LINE
expr_stmt|;
block|}
specifier|public
name|boolean
name|isEndOfLine
parameter_list|()
block|{
return|return
name|ch
operator|==
name|END_OF_LINE
return|;
block|}
specifier|public
name|void
name|set
parameter_list|(
name|Cell
name|cell
parameter_list|)
block|{
name|attributes
operator|.
name|set
argument_list|(
name|cell
operator|.
name|attributes
argument_list|)
expr_stmt|;
name|this
operator|.
name|ch
operator|=
name|cell
operator|.
name|ch
expr_stmt|;
block|}
specifier|public
name|Attributes
name|getAttributes
parameter_list|()
block|{
return|return
operator|new
name|Attributes
argument_list|(
name|attributes
argument_list|)
return|;
block|}
specifier|public
name|void
name|setAttributes
parameter_list|(
name|Attributes
name|attributes
parameter_list|)
block|{
name|this
operator|.
name|attributes
operator|.
name|set
argument_list|(
name|attributes
argument_list|)
expr_stmt|;
block|}
specifier|public
name|boolean
name|isBold
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|isBold
argument_list|()
return|;
block|}
specifier|public
name|boolean
name|isBlink
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|isBlink
argument_list|()
return|;
block|}
specifier|public
name|boolean
name|isReverse
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|isReverse
argument_list|()
return|;
block|}
specifier|public
name|boolean
name|isUnderline
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|isUnderline
argument_list|()
return|;
block|}
specifier|public
name|Color
name|getForegroundColor
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|getForegroundColor
argument_list|()
return|;
block|}
specifier|public
name|Color
name|getBackgroundColor
parameter_list|()
block|{
return|return
name|attributes
operator|.
name|getBackgroundColor
argument_list|()
return|;
block|}
annotation|@
name|Override
specifier|public
name|boolean
name|equals
parameter_list|(
name|Object
name|o
parameter_list|)
block|{
if|if
condition|(
name|this
operator|==
name|o
condition|)
block|{
return|return
literal|true
return|;
block|}
if|if
condition|(
operator|!
operator|(
name|o
operator|instanceof
name|Cell
operator|)
condition|)
block|{
return|return
literal|false
return|;
block|}
name|Cell
name|cell
init|=
operator|(
name|Cell
operator|)
name|o
decl_stmt|;
return|return
name|ch
operator|==
name|cell
operator|.
name|ch
operator|&&
name|attributes
operator|.
name|equals
argument_list|(
name|cell
operator|.
name|attributes
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
return|return
name|Objects
operator|.
name|hash
argument_list|(
name|attributes
argument_list|,
name|ch
argument_list|)
return|;
block|}
block|}
end_class
end_unit
| 14.282407
| 814
| 0.790276
|
18747633b40b2dbed633940e072a48abf98cfdfd
| 1,373
|
/*
* Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Indoqa 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 com.indoqa.solr.facet.api;
import org.noggit.JSONWriter;
public class FacetList extends AbstractFacet {
public FacetList() {
super(null, null);
}
public static String toJsonString(Facet facet) {
FacetList facetList = new FacetList();
facetList.addSubFacet(facet);
return facet.toJsonString();
}
@Override
public void streamToJson(JSONWriter jsonWriter) {
if (!this.hasSubFacets()) {
return;
}
this.writeFacets(jsonWriter, this.subFacets);
}
}
| 31.204545
| 78
| 0.707939
|
ef5905352a5f0a76af69e10aa3633b85d9c9290a
| 1,230
|
/**
* This is the test class for testing classes
*/
public class Main {
/**
* This is the main method
*
* @param args
*/
public static void main(String[] args) {
//creating shapes
Circle circle1 = new Circle(19);
Circle circle2 = new Circle(3);
Rectangle rect1 = new Rectangle(1, 4, 1, 4);
Rectangle rect2 = new Rectangle(8, 5, 8, 5);
Rectangle rect3 = new Rectangle(6, 6, 6, 6);
Triangle tri1 = new Triangle(2, 2, 2);
Triangle tri2 = new Triangle(4, 4, 6);
//creating paint
Paint paint = new Paint();
//testing add methods
paint.addCircle(circle1);
paint.addCircle(circle2);
paint.addRectangle(rect1);
paint.addRectangle(rect2);
paint.addRectangle(rect3);
paint.addTriangle(tri1);
paint.addTriangle(tri2);
//testing draw and print all methods
paint.drawAll();
paint.printAll();
//Testing isSquare and isEquilateral methods
if (rect3.isSquare()) {
System.out.println("It is square!");
}
if (tri1.isEquilateral()) {
System.out.println("It is equilateral!");
}
}
}
| 29.285714
| 53
| 0.560976
|
c3f1353bf6e2d69e3d94f61769ebda0cd70dca7e
| 740
|
package com.indignado.logicbricks.utils.builders.sensors;
import com.indignado.logicbricks.core.sensors.MessageSensor;
/**
* @author Rubentxu.
*/
public class MessageSensorBuilder extends SensorBuilder<MessageSensor> {
public MessageSensorBuilder() {
brick = new MessageSensor();
}
public MessageSensorBuilder setSubject(String subject) {
brick.subject = subject;
return this;
}
public MessageSensorBuilder setAutoRegister(boolean autoRegister) {
brick.autoRegister = autoRegister;
return this;
}
@Override
public MessageSensor getBrick() {
MessageSensor brickTemp = brick;
brick = new MessageSensor();
return brickTemp;
}
}
| 19.473684
| 72
| 0.67973
|
ebda0fa2e9c72bb63738af6ce48ace2b83226064
| 2,277
|
package org.j2server.j2cache.cache;
public interface ICache<K, V> extends java.util.Map<K, V>{
/**
* Returns the name of the cache.
*
* @return the name of the cache.
*/
String getName();
/**
* Sets the name of the cache
*
* @param name the name of the cache
*/
void setName(String name);
/**
* Returns the maximum size of the cache in bytes. If the cache grows larger
* than the max size, the least frequently used items will be removed. If
* the max cache size is set to -1, there is no size limit.
*
* @return the maximum size of the cache in bytes.
*/
long getMaxCacheSize();
/**
* Sets the maximum size of the cache in bytes. If the cache grows larger
* than the max size, the least frequently used items will be removed. If
* the max cache size is set to -1, there is no size limit.
*
* @param maxSize the maximum size of the cache in bytes.
*/
void setMaxCacheSize(int maxSize);
/**
* Returns the maximum number of milliseconds that any object can live
* in cache. Once the specified number of milliseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @return the maximum number of milliseconds before objects are expired.
*/
long getMaxLifetime();
/**
* Sets the maximum number of milliseconds that any object can live
* in cache. Once the specified number of milliseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @param maxLifetime the maximum number of milliseconds before objects are expired.
*/
void setMaxLifetime(long maxLifetime);
/**
* Returns the size of the cache contents in bytes. This value is only a
* rough approximation, so cache users should expect that actual VM
* memory used by the cache could be significantly higher than the value
* reported by this method.
*
* @return the size of the cache contents in bytes.
*/
int getCacheSize();
}
| 33.485294
| 89
| 0.635046
|
73aa1427b6feeb7fb45e2e8ecff298cecea46ad1
| 572
|
package com.fao.houduan.service;
import com.fao.houduan.common.Result;
import com.fao.houduan.entity.Picture;
import com.fao.houduan.mapper.PictureMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author fao
* @Create 2021--12--12 17:12
*/
@Service
public class ProcessService {
@Resource
private PictureMapper pictureMapper;
//根据id查询图片
public Result getPictureById(Long id){
Picture picture = pictureMapper.selectById(id);
return Result.success(picture);
}
}
| 22
| 55
| 0.736014
|
198cb93afa09bb087ac28bcd9e563502e4c48a44
| 1,840
|
package com.aspose.slides.examples.text;
import com.aspose.slides.*;
import com.aspose.slides.examples.RunExamples;
import java.awt.*;
import java.io.File;
public class ApplyingOuterShadowEffects
{
public static void main(String[] args)
{
//ExStart:ShadowEffects
// The path to the documents directory.
String dataDir = RunExamples.getDataDir_Text();
// Create directory if it is not already present.
boolean IsExists = new File(dataDir).exists();
if (!IsExists)
new File(dataDir).mkdirs();
// Instantiate a PPTX class
Presentation pres = new Presentation();
try
{
// Get reference of the slide
ISlide sld = pres.getSlides().get_Item(0);
// Add an AutoShape of Rectangle type
IAutoShape aShp = sld.getShapes().addAutoShape(ShapeType.Rectangle, 150, 75, 150, 50);
// Add TextFrame to the Rectangle
aShp.addTextFrame("Aspose TextBox");
// Disable shape fill in case we want to get shadow of text
aShp.getFillFormat().setFillType(FillType.NoFill);
// Add outer shadow and set all necessary parameters
aShp.getEffectFormat().enableOuterShadowEffect();
IOuterShadow shadow = aShp.getEffectFormat().getOuterShadowEffect();
shadow.setBlurRadius(4.0);
shadow.setDirection(45);
shadow.setDistance(3);
shadow.setRectangleAlign(RectangleAlignment.TopLeft);
shadow.getShadowColor().setColor(Color.BLACK);
//Write the presentation to disk
pres.save(dataDir + "pres_out.pptx", SaveFormat.Pptx);
}
finally
{
if (pres != null) pres.dispose();
}
//ExEnd:ShadowEffects
}
}
| 30.666667
| 98
| 0.6125
|
84f180c8db0197dafbf8d9e3d997d4969f14c32d
| 8,804
|
package com.reactnativecodefly;
import android.content.Context;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
public class CodeFlyUpdateUtils {
public static final String NEW_LINE = System.getProperty("line.separator");
// Note: The hashing logic here must mirror the hashing logic in other native SDK's, as well as in the
// CLI. Ensure that any changes here are propagated to these other locations.
public static boolean isHashIgnored(String relativeFilePath) {
final String __MACOSX = "__MACOSX/";
final String DS_STORE = ".DS_Store";
final String CodeFly_METADATA = ".CodeFlyrelease";
return relativeFilePath.startsWith(__MACOSX)
|| relativeFilePath.equals(DS_STORE)
|| relativeFilePath.endsWith("/" + DS_STORE)
|| relativeFilePath.equals(CodeFly_METADATA)
|| relativeFilePath.endsWith("/" + CodeFly_METADATA);
}
private static void addContentsOfFolderToManifest(String folderPath, String pathPrefix, ArrayList<String> manifest) {
File folder = new File(folderPath);
File[] folderFiles = folder.listFiles();
for (File file : folderFiles) {
String fileName = file.getName();
String fullFilePath = file.getAbsolutePath();
String relativePath = (pathPrefix.isEmpty() ? "" : (pathPrefix + "/")) + fileName;
if (CodeFlyUpdateUtils.isHashIgnored(relativePath)) {
continue;
}
if (file.isDirectory()) {
addContentsOfFolderToManifest(fullFilePath, relativePath, manifest);
} else {
try {
manifest.add(relativePath + ":" + computeHash(new FileInputStream(file)));
} catch (FileNotFoundException e) {
// Should not happen.
throw new CodeFlyUnknownException("Unable to compute hash of update contents.", e);
}
}
}
}
private static String computeHash(InputStream dataStream) {
MessageDigest messageDigest = null;
DigestInputStream digestInputStream = null;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
digestInputStream = new DigestInputStream(dataStream, messageDigest);
byte[] byteBuffer = new byte[1024 * 8];
while (digestInputStream.read(byteBuffer) != -1) ;
} catch (NoSuchAlgorithmException | IOException e) {
// Should not happen.
throw new CodeFlyUnknownException("Unable to compute hash of update contents.", e);
} finally {
try {
if (digestInputStream != null) digestInputStream.close();
if (dataStream != null) dataStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
byte[] hash = messageDigest.digest();
return String.format("%064x", new java.math.BigInteger(1, hash));
}
public static void copyNecessaryFilesFromCurrentPackage(String diffManifestFilePath, String currentPackageFolderPath, String newPackageFolderPath) throws IOException {
FileUtils.copyDirectoryContents(currentPackageFolderPath, newPackageFolderPath);
JSONObject diffManifest = CodeFlyUtils.getJsonObjectFromFile(diffManifestFilePath);
try {
JSONArray deletedFiles = diffManifest.getJSONArray("deletedFiles");
for (int i = 0; i < deletedFiles.length(); i++) {
String fileNameToDelete = deletedFiles.getString(i);
File fileToDelete = new File(newPackageFolderPath, fileNameToDelete);
if (fileToDelete.exists()) {
fileToDelete.delete();
}
}
} catch (JSONException e) {
throw new CodeFlyUnknownException("Unable to copy files from current package during diff update", e);
}
}
public static String findJSBundleInUpdateContents(String folderPath, String expectedFileName) {
File folder = new File(folderPath);
File[] folderFiles = folder.listFiles();
for (File file : folderFiles) {
String fullFilePath = CodeFlyUtils.appendPathComponent(folderPath, file.getName());
if (file.isDirectory()) {
String mainBundlePathInSubFolder = findJSBundleInUpdateContents(fullFilePath, expectedFileName);
if (mainBundlePathInSubFolder != null) {
return CodeFlyUtils.appendPathComponent(file.getName(), mainBundlePathInSubFolder);
}
} else {
String fileName = file.getName();
if (fileName.equals(expectedFileName)) {
return fileName;
}
}
}
return null;
}
public static String getHashForBinaryContents(Context context, boolean isDebugMode) {
try {
return CodeFlyUtils.getStringFromInputStream(context.getAssets().open(CodeFlyConstants.CODE_FLY_HASH_FILE_NAME));
} catch (IOException e) {
try {
return CodeFlyUtils.getStringFromInputStream(context.getAssets().open(CodeFlyConstants.CODE_FLY_OLD_HASH_FILE_NAME));
} catch (IOException ex) {
if (!isDebugMode) {
// Only print this message in "Release" mode. In "Debug", we may not have the
// hash if the build skips bundling the files.
CodeFlyUtils.log("Unable to get the hash of the binary's bundled resources - \"codefly.gradle\" may have not been added to the build definition.");
}
}
return null;
}
}
// Hashing algorithm:
// 1. Recursively generate a sorted array of format <relativeFilePath>: <sha256FileHash>
// 2. JSON stringify the array
// 3. SHA256-hash the result
public static void verifyFolderHash(String folderPath, String expectedHash) {
CodeFlyUtils.log("Verifying hash for folder path: " + folderPath);
ArrayList<String> updateContentsManifest = new ArrayList<>();
addContentsOfFolderToManifest(folderPath, "", updateContentsManifest);
//sort manifest strings to make sure, that they are completely equal with manifest strings has been generated in cli!
Collections.sort(updateContentsManifest);
JSONArray updateContentsJSONArray = new JSONArray();
for (String manifestEntry : updateContentsManifest) {
updateContentsJSONArray.put(manifestEntry);
}
// The JSON serialization turns path separators into "\/", e.g. "CodeFly\/assets\/image.png"
String updateContentsManifestString = updateContentsJSONArray.toString().replace("\\/", "/");
CodeFlyUtils.log("Manifest string: " + updateContentsManifestString);
String updateContentsManifestHash = computeHash(new ByteArrayInputStream(updateContentsManifestString.getBytes()));
CodeFlyUtils.log("Expected hash: " + expectedHash + ", actual hash: " + updateContentsManifestHash);
if (!expectedHash.equals(updateContentsManifestHash)) {
throw new CodeFlyInvalidUpdateException("The update contents failed the data integrity check.");
}
CodeFlyUtils.log("The update contents succeeded the data integrity check.");
}
public static PublicKey parsePublicKey(String stringPublicKey) {
try {
//remove unnecessary "begin/end public key" entries from string
stringPublicKey = stringPublicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace(NEW_LINE, "");
byte[] byteKey = Base64.decode(stringPublicKey.getBytes(), Base64.DEFAULT);
X509EncodedKeySpec X509Key = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(X509Key);
} catch (Exception e) {
CodeFlyUtils.log(e.getMessage());
CodeFlyUtils.log(e.getStackTrace().toString());
return null;
}
}
}
| 44.241206
| 171
| 0.642208
|
82e508cbcc16c73d3d6a85257d036b279ec4b7a8
| 4,105
|
package eu.inloop.knight.builder;
import android.content.Context;
import android.content.Intent;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import eu.inloop.knight.ErrorMsg;
import eu.inloop.knight.Extra;
import eu.inloop.knight.name.GCN;
import eu.inloop.knight.name.GPN;
import eu.inloop.knight.util.ProcessorError;
/**
* Class {@link NavigatorBuilder}
*
* @author FrantisekGazo
* @version 2015-10-21
*/
public class NavigatorBuilder extends BaseClassBuilder {
private static final String METHOD_NAME_FOR = "for%s";
private static final String METHOD_NAME_START = "start%s";
private static final String EXTRA_ID = "%s.EXTRA_%s";
public NavigatorBuilder() throws ProcessorError {
super(GCN.NAVIGATOR, GPN.KNIGHT);
}
@Override
public void start() throws ProcessorError {
super.start();
getBuilder().addModifiers(Modifier.FINAL, Modifier.PUBLIC);
}
public void integrate(TypeElement e, ActivityBuilders activityBuilders) throws ProcessorError {
// get all fields annotated with @Extra
List<NamedExtra> extras = new ArrayList<>();
for (Element ee : e.getEnclosedElements()) {
if (ee.getAnnotation(Extra.class) != null) {
extras.add(new NamedExtra((VariableElement) ee));
}
}
// make sure that @Extra have distinct names
Set<String> names = new HashSet<>();
for (NamedExtra namedExtra : extras) {
if (names.contains(namedExtra.getName())) {
throw new ProcessorError(namedExtra.getElement(), ErrorMsg.Extra_name_not_unique);
}
names.add(namedExtra.getName());
}
addForActivityMethod(activityBuilders.getActivityName(), extras);
activityBuilders.SM.addInitMethod(extras);
}
private void addForActivityMethod(ClassName activityName, List<NamedExtra> extras) {
String forName = getMethodName(METHOD_NAME_FOR, activityName);
String context = "context";
String intent = "intent";
// build FOR method
MethodSpec.Builder forMethod = MethodSpec.methodBuilder(forName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(Context.class, context)
.returns(Intent.class);
// build START method
MethodSpec.Builder startMethod = MethodSpec.methodBuilder(getMethodName(METHOD_NAME_START, activityName))
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(Context.class, context);
forMethod.addStatement("$T $N = new $T($N, $T.class)", Intent.class, intent, Intent.class, context, activityName);
startMethod.addCode("$N.startActivity($N($N", context, forName, context);
for (NamedExtra namedExtra : extras) {
TypeName typeName = ClassName.get(namedExtra.getElement().asType());
String name = namedExtra.getName();
forMethod.addParameter(typeName, name);
forMethod.addStatement("$N.putExtra($S, $N)", intent, getExtraId(activityName, name), name);
startMethod.addParameter(typeName, name);
startMethod.addCode(", $N", name);
}
forMethod.addStatement("return $N", intent);
startMethod.addCode("));\n");
// add methods
getBuilder().addMethod(forMethod.build());
getBuilder().addMethod(startMethod.build());
}
private String getMethodName(String format, ClassName activityName) {
return String.format(format, activityName.simpleName());
}
public static String getExtraId(ClassName activityName, String name) {
return String.format(EXTRA_ID, activityName.simpleName(), name);
}
}
| 37.66055
| 122
| 0.676005
|
1892afb4aaedb3a1f2a65f953041f975e0fc39bd
| 2,116
|
/*
* 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.
*
* Copyright 2007-2016 SSAC(Systems of Social Accounting Consortium)
* <author> Yasunari Ishizuka (PieCake,Inc.)
* <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> Yuji Onuki (Statistics Bureau)
* <author> Shungo Sakaki (Tokyo University of Technology)
* <author> Akira Sasaki (HOSEI UNIVERSITY)
* <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)CommandSheetBlockNode.java 3.3.0 2016/05/06
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.util.excel2csv.command;
import ssac.util.excel2csv.poi.SheetInfo;
/**
* <code>[Excel to CSV]</code> 変換定義における処理対象シートを保持するコマンドブロックノードのインタフェース。
*
* @version 3.3.0
* @since 3.3.0
*/
public interface CommandSheetBlockNode extends CommandBlockNode
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
//------------------------------------------------------------
// Interfaces
//------------------------------------------------------------
/**
* 処理対象シートが存在するかどうかを判定する。
* @return 処理対象シートが存在しない場合は <tt>true</tt>、そうでない場合は <tt>false</tt>
*/
public boolean isTargetSheetEmpty();
/**
* 処理対象シート数を返す。
* @return 処理対象シート数
*/
public int getTargetSheetCount();
/**
* 処理対象シートの配列を設定する。
* このメソッドは、配列のインスタンスを格納する。
* @param targets このオブジェクトに設定する処理対象シート情報の配列
*/
public void setTargetSheets(SheetInfo[] targets);
/**
* 処理対象シートの配列を取得する。
* @return 処理対象シート情報の配列、処理対象シートが存在しない場合は空の配列
*/
public SheetInfo[] getTargetSheets();
}
| 29.802817
| 76
| 0.630435
|
9767bdef22adafdd54ff612537292813623c3f74
| 629
|
package com.ghoss.android.rappitest.presentation;
import android.app.Application;
import com.ghoss.android.rappitest.presentation.dagger.component.AppComponent;
import com.ghoss.android.rappitest.presentation.dagger.component.DaggerAppComponent;
/**
* Created by rrtatasciore on 14/10/17.
*/
public class RappiApplication extends Application {
private AppComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerAppComponent.builder().build();
component.inject(this);
}
public AppComponent getComponent() {
return component;
}
}
| 23.296296
| 84
| 0.72814
|
28f1411ff24f17f3e9dfc0d56b16dfbcf43f2a15
| 1,458
|
package com.metranet.finbox.service.member.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.metranet.finbox.service.member.dto.MemberDto;
@FeignClient(contextId="MemberService", name="service-member")
public interface MemberService {
@GetMapping(value = "findByEmailOrUsername/{email}/{username}", produces = "application/json")
public MemberDto findByEmailOrUsername(@PathVariable("email") String email, @PathVariable("username") String username);
@GetMapping(value = "findByEmailOrUsernameOrPhone/{email}/{username}/{phone}", produces = "application/json")
public MemberDto findByEmailOrUsernameOrPhone(@PathVariable("email") String email, @PathVariable("username") String username, @PathVariable("phone") String phone);
@GetMapping(value = "findByUsername/{username}", produces = "application/json")
public MemberDto findByUsername(@PathVariable("username") String username);
@PostMapping(value = "registerMember", consumes = "application/json")
public Long registerMember(@RequestBody MemberDto member);
@PostMapping(value = "updateMember", consumes = "application/json")
public Long updateMember(@RequestBody MemberDto member);
}
| 50.275862
| 167
| 0.778464
|
f8fa578e911694bb86caa9b71458d87042ada004
| 23,851
|
/*
* Copyright 2013 Hewlett-Packard Development Company, L.P
*
* 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.hp.alm.ali.idea.rest;
import com.hp.alm.ali.ServerVersion;
import com.hp.alm.ali.idea.FixtureFactory;
import com.hp.alm.ali.idea.IntellijTest;
import com.hp.alm.ali.idea.cfg.AliProjectConfiguration;
import com.hp.alm.ali.idea.model.HorizonStrategy;
import com.hp.alm.ali.idea.model.ServerStrategy;
import com.hp.alm.ali.rest.client.AliRestClientFactory;
import com.hp.alm.ali.rest.client.InputData;
import com.hp.alm.ali.rest.client.RestClient;
import com.hp.alm.ali.rest.client.RestClientFactory;
import com.hp.alm.ali.rest.client.ResultInfo;
import com.hp.alm.ali.rest.client.exception.AuthenticationFailureException;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.util.net.HttpConfigurable;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class RestServiceTest extends IntellijTest {
private RestService restService;
private RestClient restClient;
private AliProjectConfiguration projectConfiguration;
@Before
public void preClean() {
restService = getComponent(RestService.class);
restClient = restService.getRestClient();
projectConfiguration = getComponent(AliProjectConfiguration.class);
}
@After
public void postClean() throws Throwable {
handler.checkpoint();
RestService._setFactory(AliRestClientFactory.getInstance());
restService._setRestServiceLogger(ApplicationManager.getApplication().getComponent(TroubleShootService.class));
if(restService.getRestClient() instanceof MockRestClient) {
restService._setRestClient(restClient);
}
HttpConfigurable.getInstance().USE_HTTP_PROXY = false;
}
public RestServiceTest() {
super(ServerVersion.AGM);
}
@Test
public void testCreateRestClient_noProxy() {
HttpConfigurable httpConfigurable = HttpConfigurable.getInstance();
httpConfigurable.USE_HTTP_PROXY = false;
handler.async(3);
RestService._setFactory(new RestClientFactory() {
@Override
public RestClient create(final String location, final String domain, final String project, final String userName, final String password, final RestClient.SessionStrategy sessionStrategy) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("location", location);
Assert.assertEquals("domain", domain);
Assert.assertEquals("project", project);
Assert.assertEquals("user", userName);
Assert.assertEquals("password", password);
Assert.assertEquals(RestClient.SessionStrategy.AUTO_LOGIN, sessionStrategy);
}
});
return new MockRestClient() {
@Override
public void setEncoding(final String encoding) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertNull(encoding);
}
});
}
@Override
public void setTimeout(final int timeout) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals(10000, timeout);
}
});
}
};
}
});
RestService.createRestClient("location", "domain", "project", "user", "password", RestClient.SessionStrategy.AUTO_LOGIN);
}
@Test
public void testCreateRestClient_unauthenticatedProxy() {
HttpConfigurable httpConfigurable = HttpConfigurable.getInstance();
httpConfigurable.USE_HTTP_PROXY = true;
httpConfigurable.PROXY_HOST = "localhost";
httpConfigurable.PROXY_PORT = 1234;
httpConfigurable.PROXY_AUTHENTICATION = false;
handler.async(4);
RestService._setFactory(new RestClientFactory() {
@Override
public RestClient create(final String location, final String domain, final String project, final String userName, final String password, final RestClient.SessionStrategy sessionStrategy) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("http://location", location);
Assert.assertEquals("domain", domain);
Assert.assertEquals("project", project);
Assert.assertEquals("user", userName);
Assert.assertEquals("password", password);
Assert.assertEquals(RestClient.SessionStrategy.AUTO_LOGIN, sessionStrategy);
}
});
return new MockRestClient() {
@Override
public void setHttpProxy(final String proxyHost, final int proxyPort) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("localhost", proxyHost);
Assert.assertEquals(1234, proxyPort);
}
});
}
@Override
public void setEncoding(final String encoding) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertNull(encoding);
}
});
}
@Override
public void setTimeout(final int timeout) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals(10000, timeout);
}
});
}
};
}
});
RestService.createRestClient("http://location", "domain", "project", "user", "password", RestClient.SessionStrategy.AUTO_LOGIN);
}
@Test
public void testCreateRestClient_authenticatedProxy() {
HttpConfigurable httpConfigurable = HttpConfigurable.getInstance();
httpConfigurable.USE_HTTP_PROXY = true;
httpConfigurable.PROXY_HOST = "localhost";
httpConfigurable.PROXY_PORT = 1234;
httpConfigurable.PROXY_AUTHENTICATION = true;
httpConfigurable.PROXY_LOGIN = "admin";
httpConfigurable.PROXY_PASSWORD_CRYPT = "Y2hhbmdlaXQ=";
handler.async(5);
RestService._setFactory(new RestClientFactory() {
@Override
public RestClient create(final String location, final String domain, final String project, final String userName, final String password, final RestClient.SessionStrategy sessionStrategy) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("http://location", location);
Assert.assertEquals("domain", domain);
Assert.assertEquals("project", project);
Assert.assertEquals("user", userName);
Assert.assertEquals("password", password);
Assert.assertEquals(RestClient.SessionStrategy.AUTO_LOGIN, sessionStrategy);
}
});
return new MockRestClient() {
@Override
public void setHttpProxy(final String proxyHost, final int proxyPort) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("localhost", proxyHost);
Assert.assertEquals(1234, proxyPort);
}
});
}
@Override
public void setHttpProxyCredentials(final String username, final String password) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("admin", username);
Assert.assertEquals("changeit", password);
}
});
}
@Override
public void setEncoding(final String encoding) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertNull(encoding);
}
});
}
@Override
public void setTimeout(final int timeout) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals(10000, timeout);
}
});
}
};
}
});
RestService.createRestClient("http://location", "domain", "project", "user", "password", RestClient.SessionStrategy.AUTO_LOGIN);
}
@Test
public void testGetRestClient() {
RestClient restClient = restService.getRestClient();
Assert.assertNotNull(restClient);
Assert.assertEquals(RestClient.SessionStrategy.AUTO_LOGIN, restClient.getSessionStrategy());
Assert.assertEquals(restClient, restService.getRestClient());
}
@Test
public void testGet() {
handler.async();
restService._setRestClient(new MockRestClient() {
@Override
public int get(ResultInfo result, final String template, final Object... params) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("defects/{0}", template);
Assert.assertEquals("1", params[0]);
}
});
try {
result.getBodyStream().write("foo".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
return 200;
}
});
MyResultInfo result = new MyResultInfo();
int status = restService.get(result, "defects/{0}", "1");
Assert.assertEquals(200, status);
Assert.assertEquals("foo", result.getBodyAsString());
}
@Test
public void testPut() {
handler.async();
restService._setRestClient(new MockRestClient() {
@Override
public int put(final InputData inputData, ResultInfo result, final String template, final Object... params) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("defects/{0}", template);
Assert.assertEquals("1", params[0]);
Assert.assertEquals("bar", asString(inputData.getRequestEntity(null)));
}
});
try {
result.getBodyStream().write("foo".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
return 200;
}
});
MyResultInfo result = new MyResultInfo();
int status = restService.put("bar", result, "defects/{0}", "1");
Assert.assertEquals(200, status);
Assert.assertEquals("foo", result.getBodyAsString());
}
@Test
public void testPost() {
handler.async();
restService._setRestClient(new MockRestClient() {
@Override
public int post(final InputData inputData, ResultInfo result, final String template, final Object... params) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("defects/{0}", template);
Assert.assertEquals("1", params[0]);
Assert.assertEquals("bar", asString(inputData.getRequestEntity(null)));
}
});
try {
result.getBodyStream().write("foo".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
return 200;
}
});
MyResultInfo result = new MyResultInfo();
int status = restService.post("bar", result, "defects/{0}", "1");
Assert.assertEquals(200, status);
Assert.assertEquals("foo", result.getBodyAsString());
}
@Test
public void testDelete() {
handler.async();
restService._setRestClient(new MockRestClient() {
@Override
public int delete(ResultInfo result, final String template, final Object... params) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("defects/{0}", template);
Assert.assertEquals("1", params[0]);
}
});
try {
result.getBodyStream().write("foo".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
return 200;
}
});
MyResultInfo result = new MyResultInfo();
int status = restService.delete(result, "defects/{0}", "1");
Assert.assertEquals(200, status);
Assert.assertEquals("foo", result.getBodyAsString());
}
@Test
public void testRestServiceLogger() {
handler.async(2);
restService._setRestServiceLogger(new MockRestServiceLogger() {
@Override
public long request(Project project, final String name, final MyInputData myInput, final String template, Object... params) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals("POST", name);
Assert.assertEquals("defects", template);
Assert.assertEquals("bar", myInput.getRequestData());
}
});
return 1;
}
@Override
public void response(final long id, final int code, final MyResultInfo myResult) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals(1, id);
Assert.assertEquals(200, code);
Assert.assertEquals("foo", myResult.getBodyAsString());
}
});
}
});
restService._setRestClient(new MockRestClient() {
@Override
public int post(InputData input, ResultInfo result, final String template, final Object... params) {
try {
result.getBodyStream().write("foo".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
return 200;
}
});
restService.post("bar", new MyResultInfo(), "defects");
}
@Test
public void testRestServiceLogger_loginFailure() {
handler.async();
restService._setRestServiceLogger(new MockRestServiceLogger() {
@Override
public long request(Project project, String name, MyInputData myInput, String template, Object... params) {
return 1;
}
@Override
public void loginFailure(final long id, final AuthenticationFailureException e) {
handler.done(new Runnable() {
@Override
public void run() {
Assert.assertEquals(1, id);
Assert.assertEquals(401, e.getHttpStatus());
Assert.assertEquals("Forbidden", e.getReasonPhrase());
Assert.assertEquals("defects", e.getLocation());
}
});
}
});
restService._setRestClient(new MockRestClient() {
@Override
public int get(ResultInfo result, final String template, final Object... params) {
result.setHttpStatus(401);
result.setReasonPhrase("Forbidden");
result.setLocation(template);
throw new AuthenticationFailureException(result);
}
});
try {
restService.get(new MyResultInfo(), "defects");
Assert.fail("should have failed");
} catch (AuthenticationFailureException e) {
// expected
}
}
@Test
public void testOnChangedEvent() throws InterruptedException {
// when configuration is changed, following should happen:
//
// 1. logout request is performed
// 2. listeners receive REST configuration changed event
// 3. listeners receive server type CONNECTING event
// 4. server version is negotiated
// 5. listeners receive server type AGM event
handler.addRequest(false, "GET", "/qcbin/authentication-point/logout", 200);
FixtureFactory.handshake(handler, true);
handler.async(3);
restService.addListener(new OneTimeRestListener(handler, restService) {
@Override
protected void restConfigurationChangedEvent() {
// async done (don't remove)
}
});
restService.addServerTypeListener(new OneTimeServerTypeListener(handler, restService) {
@Override
protected void connectedToEvent(ServerType serverType) {
Assert.assertEquals(ServerType.CONNECTING, serverType);
restService.addServerTypeListener(new OneTimeServerTypeListener(handler, restService) {
@Override
protected void connectedToEvent(ServerType serverType) {
Assert.assertEquals(ServerType.AGM, serverType);
}
});
}
});
projectConfiguration.fireChanged();
// wait for handshake finish
handler.consume();
}
@Test
public void testLogout() {
handler.async();
RestService.logout(new MockRestClient() {
@Override
public void logout() {
handler.done();
}
});
}
@Test
public void testCheckConnectivity_whenDisconnected() {
// in the disconnected state perform checkConnectivity:
//
// 1. listeners receive server type CONNECTING event
// 2. server version is negotiated
// 3. listeners receive server type AGM event
FixtureFactory.handshake(handler, false);
handler.async(2);
restService.addServerTypeListener(new OneTimeServerTypeListener(handler, restService) {
@Override
protected void connectedToEvent(ServerType serverType) {
Assert.assertEquals(ServerType.CONNECTING, serverType);
restService.addServerTypeListener(new OneTimeServerTypeListener(handler, restService) {
@Override
protected void connectedToEvent(ServerType serverType) {
Assert.assertEquals(ServerType.AGM, serverType);
}
});
}
});
restService._setServerType(ServerType.NONE);
restService.checkConnectivity();
handler.consume();
}
@Test
public void testCheckConnectivity_whenConnected() {
// nothing should happen when connected
restService.checkConnectivity();
}
@Test
public void testGetServerType() throws InterruptedException {
try {
Assert.assertEquals(ServerType.AGM, restService.getServerType());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
restService._setServerType(ServerType.NONE);
try {
Assert.assertEquals(ServerType.NONE, restService.getServerType());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
restService._setServerType(ServerType.CONNECTING);
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
restService._setServerType(ServerType.AGM);
}
});
Assert.assertEquals(ServerType.AGM, restService.getServerType());
}
@Test
public void testGetServerType_whenConnected() throws InterruptedException {
Assert.assertEquals(ServerType.AGM, restService.getServerType());
}
@Test
public void testGetServerStrategy() throws InterruptedException {
restService._setServerType(ServerType.NONE);
try {
restService.getServerStrategy();
Assert.fail("Should have failed");
} catch (NotConnectedException e) {
// ok
}
restService._setServerType(ServerType.CONNECTING);
try {
restService.getServerStrategy();
Assert.fail("Should have failed");
} catch (NotConnectedException e) {
// ok
}
restService._setServerType(ServerType.AGM);
ServerStrategy serverStrategy = restService.getServerStrategy();
Assert.assertEquals(HorizonStrategy.class, serverStrategy.getClass());
}
private String asString(RequestEntity requestEntity) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
requestEntity.writeRequest(baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
return baos.toString();
}
}
| 38.531502
| 200
| 0.542325
|
333a21f623dab8d341b6557b69df2a9d4e7bde83
| 1,088
|
package cn.bootx.common.spring.aop;
import cn.bootx.common.spring.annotation.CountTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
/**
* 切面类
* @author xxm
* @date 2020/12/22
*/
@Aspect
@Slf4j
@Component
public class CountTimeAop {
@Around("@annotation(countTime)")
public Object doAround(ProceedingJoinPoint pjp, CountTime countTime){
long startTime = System.currentTimeMillis();
Object obj = null;
try {
obj = pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
log.info("方法 [{}] 花费时间:{}ms",methodName,(endTime-startTime));
return obj;
}
}
| 27.2
| 89
| 0.683824
|
328842dc7d274fc056166ade759dc23266d3d2e9
| 394
|
package info.bfly.archer.component.model;
/**
*
*
* Description: 级联选择或者查询的DataModel
*
* @version: 1.0 Create at: 2014-1-21 下午6:31:03
*
* Modification History: <br/>
* Date Author Version Description
* ------------------------------------------------------------------
* 2014-1-21 wangzhi 1.0
*/
public abstract class CascadeDataModel<T> {
}
| 23.176471
| 79
| 0.497462
|
b30b2b0172419c34041adfed8ae465a4e0dd4c9e
| 1,422
|
package com.xxyp.xxyp.main.bean;
import com.xxyp.xxyp.common.bean.BaseBean;
/**
* Description : 约拍照片bean
* Created by sunpengfei on 2017/8/10.
* Person in charge : sunpengfei
*/
public class ShotPhotoBean extends BaseBean {
/* 约拍照片id */
private String datingShotPhotoId;
/* 约拍id */
private String datingShotId;
/* 约拍图片 */
private String datingShotPhoto;
/* 约拍图片顺序 */
private int datingShotImageOrder;
/* 状态 */
private int status;
public String getDatingShotPhotoId() {
return datingShotPhotoId;
}
public void setDatingShotPhotoId(String datingShotPhotoId) {
this.datingShotPhotoId = datingShotPhotoId;
}
public String getDatingShotId() {
return datingShotId;
}
public void setDatingShotId(String datingShotId) {
this.datingShotId = datingShotId;
}
public String getDatingShotPhoto() {
return datingShotPhoto;
}
public void setDatingShotPhoto(String datingShotPhoto) {
this.datingShotPhoto = datingShotPhoto;
}
public int getDatingShotImageOrder() {
return datingShotImageOrder;
}
public void setDatingShotImageOrder(int datingShotImageOrder) {
this.datingShotImageOrder = datingShotImageOrder;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
| 20.911765
| 67
| 0.668073
|
a8e39e50fe2ab6c467bb907b8723a0df562da1c3
| 803
|
package com.mkyong.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.services.CustomerService;
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
CustomerService cust = (CustomerService)appContext.getBean("customerServiceProxy");
System.out.println("*************************");
cust.printName();
System.out.println("*************************");
cust.printURL();
System.out.println("*************************");
try{
cust.printThrowException();
}catch(Exception e){
}
}
}
| 27.689655
| 88
| 0.62391
|
7d6d8fcdcb3c2a78be6c195ac9e23f96a0b7e959
| 2,554
|
package kodkod.engine.hol;
import kodkod.ast.Formula;
import kodkod.engine.config.AbstractReporter;
import kodkod.engine.config.Options;
import kodkod.engine.config.Reporter;
import kodkod.engine.fol2sat.Translation;
import kodkod.instance.Bounds;
public abstract class HOLTranslation extends Translation {
public static class HOLException extends RuntimeException {
private static final long serialVersionUID = 3431754608057485603L;
public HOLException() {}
public HOLException(String message) { super(message); }
}
protected Reporter rep;
protected int depth;
public HOLTranslation(Bounds bounds, Options options, int depth) {
super(bounds, options);
this.depth = depth;
rep = options.reporter() != null ? options.reporter() : new AbstractReporter() {};
// rep = new AbstractReporter() {
// public void holLoopStart(HOLTranslation tr, Formula formula, Bounds bounds) {
// System.out.println("started: " + formula);
// }
// public void holCandidateFound(HOLTranslation tr, Instance candidate) {
// System.out.println(" candidate found");
// }
// public void holVerifyingCandidate(HOLTranslation tr, Instance candidate, Formula checkFormula, Bounds bounds) {
// System.out.println(" verifying: " + checkFormula);
// }
// public void holCandidateVerified(HOLTranslation tr, Instance candidate) {}
// public void holCandidateNotVerified(HOLTranslation tr, Instance candidate, Instance cex) {}
// public void holFindingNextCandidate(HOLTranslation tr, Formula inc) {
// System.out.println(" finding next: " + inc);
// }
// };
}
public abstract Formula formula();
public abstract Translation getCurrentFOLTranslation();
//TODO: override in subclasses!!!
public Formula formulaWithInc() { return formula(); };
public boolean trivial() { return false; }
public HOLTranslation next(Formula formula, Bounds bounds) { throw new RuntimeException("not implemented"); }
public HOLTranslation next(Formula formula) { return next(formula, new Bounds(bounds.universe())); }
public HOLTranslation next() { throw new RuntimeException("not implemented"); }
public boolean isFirstOrder() { return false; }
public int depth() { return depth; }
public abstract int numCandidates();
}
| 44.034483
| 125
| 0.653093
|
9cdcf31caafe3d0aa86710c22ad1c89dd1fffa50
| 482
|
package org.apache.ibatis.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)//注解保留到运行阶段,可以在运行阶段获取到注解信息
@Documented
public @interface Customize {
String className() default "customizeClass";
int filedSort() default 1;
boolean ignoreMethod() default false;
long paramId() default 1l;
String constructorName() default "";
}
| 21.909091
| 61
| 0.748963
|
e6bd04d1a633c5ca0329c22e967e08775c7d842d
| 2,913
|
package com.prowidesoftware.swift.model.mx.dic;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Provides ownership details of a person on an asset.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Ownership1", propOrder = {
"ownrshTp",
"ownrshPctg",
"usfrctPctg"
})
public class Ownership1 {
@XmlElement(name = "OwnrshTp")
protected OwnershipType3Choice ownrshTp;
@XmlElement(name = "OwnrshPctg")
protected BigDecimal ownrshPctg;
@XmlElement(name = "UsfrctPctg")
protected BigDecimal usfrctPctg;
/**
* Gets the value of the ownrshTp property.
*
* @return
* possible object is
* {@link OwnershipType3Choice }
*
*/
public OwnershipType3Choice getOwnrshTp() {
return ownrshTp;
}
/**
* Sets the value of the ownrshTp property.
*
* @param value
* allowed object is
* {@link OwnershipType3Choice }
*
*/
public Ownership1 setOwnrshTp(OwnershipType3Choice value) {
this.ownrshTp = value;
return this;
}
/**
* Gets the value of the ownrshPctg property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getOwnrshPctg() {
return ownrshPctg;
}
/**
* Sets the value of the ownrshPctg property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public Ownership1 setOwnrshPctg(BigDecimal value) {
this.ownrshPctg = value;
return this;
}
/**
* Gets the value of the usfrctPctg property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getUsfrctPctg() {
return usfrctPctg;
}
/**
* Sets the value of the usfrctPctg property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public Ownership1 setUsfrctPctg(BigDecimal value) {
this.usfrctPctg = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| 22.937008
| 88
| 0.61689
|
bcda3a538c93471d3919273ec0d934f63abecca7
| 699
|
package com.tangzhangss.commonflowable.listener;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;
/**
* 流程监听器
*
* 开始和结束
*/
@Data
public class TestExecutionListener implements ExecutionListener {
private FixedValue A;//对应流程字段flowable:field name="A"
@Override
public void notify(DelegateExecution execution) {
System.out.println(JSON.toJSONString(execution));
System.out.println("调用了执行监听器....");
execution.getExecutions();
System.out.println(execution.getExecutions().toString());
}
}
| 27.96
| 65
| 0.74392
|
8b0635e3a4ff06a3d4a5c08c081b55adeb06c10b
| 1,810
|
/**
*
*/
package com.sqltoy.quickstart.dao;
import org.sagacity.sqltoy.config.model.Translate;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.Page;
import org.sagacity.sqltoy.model.QueryExecutor;
import org.sagacity.sqltoy.support.SqlToyDaoSupport;
import org.springframework.stereotype.Repository;
import com.sqltoy.quickstart.vo.StaffInfoVO;
/**
* 演示dao的编写,正常情况下sqltoy并不需要写dao(service层调用SqlToyLazyDao即可完成)
*
* @author zhongxuchen
* @version 1.0.0,Date:2020-07-16
*/
@Repository("staffInfoDao")
public class StaffInfoDao extends SqlToyDaoSupport {
/**
* @TODO 提供一个分页并动态设置缓存翻译的演示
* @param pageModel
* @param staffInfoVO
* @return
*/
public Page<StaffInfoVO> findStaff(Page<StaffInfoVO> pageModel, StaffInfoVO staffInfoVO) {
// sql可以直接在代码中编写,复杂sql建议在xml中定义
// 单表entity查询场景下sql字段可以写成java类的属性名称
// 单表查询一般适用于接口内部查询
String sql = "#[staffName like :staffName]#[and createTime>=:beginDate]#[and createTime<=:endDate]";
return findPageEntity(pageModel, StaffInfoVO.class, EntityQuery.create().where(sql).values(staffInfoVO)
// 字典缓存必须要设置cacheType
// 单表对象查询需设置keyColumn构成select keyColumn as column模式
.translates(new Translate("dictKeyName").setColumn("sexTypeName").setCacheType("SEX_TYPE")
.setKeyColumn("sexType"))
.translates(new Translate("organIdName").setColumn("organName").setKeyColumn("organId")));
}
/**
* @TODO 提供一个分页并动态设置缓存翻译的演示
* @param pageModel
* @param staffInfoVO
* @return
*/
public Page<StaffInfoVO> findStaff1(Page<StaffInfoVO> pageModel, StaffInfoVO staffInfoVO) {
// 直接传sql或sqlId的时使用QueryExecutor
return super.findPageByQuery(pageModel, new QueryExecutor("qstart_findStaff", staffInfoVO)
.translates(new Translate("organIdName").setColumn("organName").setIndex(2))).getPageResult();
}
}
| 33.518519
| 105
| 0.762983
|
841bc719e074bea09f7ceb42909aea5f4fad272e
| 930
|
package net.androidbootcamp.chatterbox.objects;
import net.androidbootcamp.chatterbox.inviteGen.InviteGenerator;
public class InviteObject {
private int id;
private String inviteCode;
private boolean perm;
public InviteObject(int chatID){
id = chatID;
perm = false;
inviteCode = InviteGenerator.Generate();
}
public InviteObject(int chatID, boolean permanent){
id = chatID;
perm = permanent;
inviteCode = InviteGenerator.Generate();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getInviteCode() {
return inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode;
}
public boolean isPerm() {
return perm;
}
public void setPerm(boolean perm) {
this.perm = perm;
}
}
| 18.6
| 64
| 0.616129
|
bed8bfa3d14ffe6bfbdc47f26ba426692dde28ad
| 1,198
|
/*******************************************************************************
* Copyright 2017 Infosys Limited and 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 org.onap.msb.sdk.example.springboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.onap.msb.sdk.example.springboot.model.Employee;
@RestController
public class EmployeeController {
@RequestMapping("/employee")
public Employee getEmployees() {
return (new Employee(1,"John","Kelly","john.kelly@gmail.com"));
}
}
| 46.076923
| 100
| 0.661937
|
efa05a608f061f446a968d2595c0be90d9780ea3
| 238
|
import java.io.Serializable;
/**
* 服务器配置类
*/
public class ConfigInfo implements Serializable {
public String auth;
public String server;
public String mailSendHost;
public String account;
public String password;
}
| 17
| 49
| 0.714286
|
e10c1228c10a784e5c9090a12324061b63ee5b8b
| 6,935
|
package jsat.math.optimization;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import jsat.linear.DenseMatrix;
import jsat.linear.DenseVector;
import jsat.linear.LUPDecomposition;
import jsat.linear.Vec;
import jsat.math.Function;
import jsat.utils.FakeExecutor;
import jsat.utils.SystemInfo;
/**
* Provides an implementation of the Iteratively Reweighted Least Squares (IRLS) algorithm for solving certain classes
* of optimization problems. See <a href="http://en.wikipedia.org/wiki/Iteratively_reweighted_least_squares">Wikepida</a>
* for more information.
*
* @author Edward Raff
*/
public class IterativelyReweightedLeastSquares implements Optimizer
{
/**
* The hessian matrix
*/
private DenseMatrix hessian;
/**
* Contains the values of the coefficients for each data point
*/
private DenseMatrix coefficentMatrix;
private DenseVector derivatives;
private DenseVector errors;
private DenseVector gradiant;
public IterativelyReweightedLeastSquares()
{
}
public Vec optimize(double eps, int iterationLimit, Function f, Function fd, Vec vars, List<Vec> inputs, Vec outputs)
{
return optimize(eps, iterationLimit, f, fd, vars, inputs, outputs, null);
}
public Vec optimize(double eps, int iterationLimit, Function f, Function fd, Vec vars, List<Vec> inputs, Vec outputs, ExecutorService threadpool)
{
//TODO make it actually use the threadpool!
hessian = new DenseMatrix(vars.length(), vars.length());
coefficentMatrix = new DenseMatrix(inputs.size(), vars.length());
for(int i = 0; i < inputs.size(); i++)
{
Vec x_i = inputs.get(i);
coefficentMatrix.set(i, 0, 1.0);
for(int j = 1; j < vars.length(); j++)
coefficentMatrix.set(i, j, x_i.get(j-1));
}
derivatives = new DenseVector(inputs.size());
errors = new DenseVector(outputs.length());
gradiant = new DenseVector(vars.length());
double maxChange = Double.MAX_VALUE;
//No reason to do the if check in a tightish loop
if (threadpool != null && !(threadpool instanceof FakeExecutor))//Serial
{
do
{
maxChange = iterationStep(f, fd, vars, inputs, outputs, threadpool);
}
while (!Double.isNaN(maxChange) && maxChange > eps && iterationLimit-- > 0);
}
else//Parallel
{
do
{
maxChange = iterationStep(f, fd, vars, inputs, outputs);
}
while (!Double.isNaN(maxChange) && maxChange > eps && iterationLimit-- > 0);
}
return vars;
}
private double iterationStep(Function f, Function fd, Vec vars, List<Vec> inputs, Vec outputs)
{
Vec delta = null;
for(int i = 0; i < inputs.size(); i++)
{
Vec x_i = inputs.get(i);
double y = f.f(x_i);
double error = y - outputs.get(i);
errors.set(i, error);
derivatives.set(i, fd.f(x_i));
}
for (int j = 0; j < hessian.rows(); j++)
{
double gradTmp = 0;
for (int k = 0; k < coefficentMatrix.rows(); k++)
{
double coefficient_kj = coefficentMatrix.get(k, j);
gradTmp+= coefficient_kj*errors.get(k);
double multFactor = derivatives.get(k) * coefficient_kj;
for (int i = 0; i < hessian.rows(); i++)
hessian.increment(j, i, coefficentMatrix.get(k, i) * multFactor);
}
gradiant.set(j, gradTmp);
}
LUPDecomposition lupDecomp = new LUPDecomposition(hessian.clone());//We sent a clone of the hessian b/c we make incremental updates every iteration
if(Math.abs(lupDecomp.det()) < 1e-14 )
{
//TODO use a pesudo inverse instead of giving up
return Double.NaN;//Indicate that we need to stop
}
else//nomral case, solve!
{
delta = lupDecomp.solve(gradiant);
}
vars.mutableSubtract(delta);
return Math.max(delta.max(), Math.abs(delta.min()));
}
private double iterationStep(Function f, Function fd, Vec vars, List<Vec> inputs, Vec outputs, ExecutorService threadpool)
{
Vec delta = null;
for(int i = 0; i < inputs.size(); i++)
{
Vec x_i = inputs.get(i);
double y = f.f(x_i);
double error = y - outputs.get(i);
errors.set(i, error);
derivatives.set(i, fd.f(x_i));
}
int overFlow = hessian.rows()%SystemInfo.LogicalCores;
int size = hessian.rows()/SystemInfo.LogicalCores;
int start = 0;
final CountDownLatch latch = new CountDownLatch(SystemInfo.LogicalCores);
for(int t = 0; t < SystemInfo.LogicalCores; t++)
{
final int START = start;
final int TO = (overFlow-- > 0 ? 1 : 0) + START + size;
start = TO;
threadpool.submit(new Runnable() {
public void run()
{
for (int j = START; j < TO; j++)
{
double gradTmp = 0;
for (int k = 0; k < coefficentMatrix.rows(); k++)
{
double coefficient_kj = coefficentMatrix.get(k, j);
gradTmp += coefficient_kj * errors.get(k);
double multFactor = derivatives.get(k) * coefficient_kj;
for (int i = 0; i < hessian.rows(); i++)
hessian.increment(j, i, coefficentMatrix.get(k, i) * multFactor);
}
gradiant.set(j, gradTmp);
}
latch.countDown();
}
});
}
try
{
latch.await();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
LUPDecomposition lupDecomp = new LUPDecomposition(hessian.clone(), threadpool);//We sent a clone of the hessian b/c we make incremental updates every iteration
if (Math.abs(lupDecomp.det()) < 1e-14)
{
//TODO use a pesudo inverse instead of giving up
return Double.NaN;//Indicate that we need to stop
}
else//nomral case, solve!
{
delta = lupDecomp.solve(gradiant);
}
vars.mutableSubtract(delta);
return Math.max(delta.max(), Math.abs(delta.min()));
}
}
| 33.995098
| 167
| 0.540591
|
33398c14d79401fb52406632183f720cd1ddf763
| 11,438
|
/*
* Copyright (C) 2011-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* 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.rinde.rinsim.core.model.road;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verifyNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newLinkedHashMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.annotation.Nullable;
import javax.measure.quantity.Length;
import javax.measure.quantity.Velocity;
import javax.measure.unit.Unit;
import com.github.rinde.rinsim.core.model.time.TimeLapse;
import com.github.rinde.rinsim.event.EventAPI;
import com.github.rinde.rinsim.geom.Point;
import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
/**
* A common space neutral implementation of {@link RoadModel}. It implements a
* data structure for managing objects and locations and checks many
* preconditions as defined in {@link RoadModel}.
* @author Rinde van Lon
* @param <T> The type of the location representation that is used for storing
* object locations. This location representation should only be used
* internally in the model.
*/
public abstract class AbstractRoadModel<T> extends GenericRoadModel {
/**
* A mapping of {@link RoadUser} to location.
*/
protected volatile Map<RoadUser, T> objLocs;
/**
* A mapping of {@link MovingRoadUser}s to {@link DestinationPath}s.
*/
protected Map<MovingRoadUser, DestinationPath> objDestinations;
/**
* A reference to {@link RoadUnits}.
*/
protected final RoadUnits unitConversion;
/**
* Create a new instance.
* @param distanceUnit The distance unit used to interpret all supplied
* distances.
* @param speedUnit The speed unit used to interpret all supplied speeds.
*/
protected AbstractRoadModel(Unit<Length> distanceUnit,
Unit<Velocity> speedUnit) {
super();
unitConversion = new RoadUnits(distanceUnit, speedUnit);
objLocs = Collections.synchronizedMap(new LinkedHashMap<RoadUser, T>());
objDestinations = newLinkedHashMap();
}
/**
* A function for converting the location representation to a {@link Point}.
* @param locObj The location to be converted.
* @return A {@link Point} indicating the position as represented by the
* specified location.
*/
protected abstract Point locObj2point(T locObj);
/**
* A function for converting a {@link Point} to the location representation of
* this model.
* @param point The {@link Point} to be converted.
* @return The location.
*/
protected abstract T point2LocObj(Point point);
@Override
public MoveProgress followPath(MovingRoadUser object, Queue<Point> path,
TimeLapse time) {
checkArgument(objLocs.containsKey(object),
"Object: %s must have a location.", object);
checkArgument(!path.isEmpty(),
"Path can not be empty, found empty path for %s.", object);
checkArgument(time.hasTimeLeft(),
"Can not follow path when no time is left. For road user %s.", object);
final Point dest = newArrayList(path).get(path.size() - 1);
objDestinations.put(object, new DestinationPath(dest, path));
final MoveProgress mp = doFollowPath(object, path, time);
eventDispatcher.dispatchEvent(new MoveEvent(self, object, mp));
return mp;
}
@Override
public MoveProgress moveTo(MovingRoadUser object, Point destination,
TimeLapse time) {
Queue<Point> path;
if (objDestinations.containsKey(object)
&& objDestinations.get(object).destination.equals(destination)) {
// is valid move? -> assume it is
path = objDestinations.get(object).path;
} else {
path = new LinkedList<>(getShortestPathTo(object, destination));
objDestinations.put(object, new DestinationPath(destination, path));
}
final MoveProgress mp = doFollowPath(object, path, time);
eventDispatcher.dispatchEvent(new MoveEvent(self, object, mp));
return mp;
}
@Override
public MoveProgress moveTo(MovingRoadUser object, RoadUser destination,
TimeLapse time) {
return moveTo(object, getPosition(destination), time);
}
/**
* Should be overridden by subclasses to define actual
* {@link RoadModel#followPath(MovingRoadUser, Queue, TimeLapse)} behavior.
* @param object The object that is moved.
* @param path The path that is followed.
* @param time The time that is available for travel.
* @return A {@link MoveProgress} instance containing the actual travel
* details.
*/
protected abstract MoveProgress doFollowPath(MovingRoadUser object,
Queue<Point> path, TimeLapse time);
@Override
@Nullable
public Point getDestination(MovingRoadUser object) {
if (objDestinations.containsKey(object)) {
return objDestinations.get(object).destination;
}
return null;
}
@Override
public void addObjectAt(RoadUser newObj, Point pos) {
checkArgument(!objLocs.containsKey(newObj), "Object is already added: %s.",
newObj);
objLocs.put(newObj, point2LocObj(pos));
eventDispatcher.dispatchEvent(new RoadModelEvent(
RoadEventType.ADD_ROAD_USER, this, newObj));
}
@Override
public void addObjectAtSamePosition(RoadUser newObj, RoadUser existingObj) {
checkArgument(!objLocs.containsKey(newObj), "Object %s is already added.",
newObj);
checkArgument(objLocs.containsKey(existingObj),
"Object %s does not exist.", existingObj);
objLocs.put(newObj, objLocs.get(existingObj));
eventDispatcher.dispatchEvent(new RoadModelEvent(
RoadEventType.ADD_ROAD_USER, this, newObj));
}
@Override
public void removeObject(RoadUser roadUser) {
checkArgument(objLocs.containsKey(roadUser),
"RoadUser: %s does not exist.", roadUser);
objLocs.remove(roadUser);
objDestinations.remove(roadUser);
eventDispatcher.dispatchEvent(new RoadModelEvent(
RoadEventType.REMOVE_ROAD_USER, this, roadUser));
}
@Override
public void clear() {
objLocs.clear();
objDestinations.clear();
}
@Override
public boolean containsObject(RoadUser obj) {
return objLocs.containsKey(obj);
}
@Override
public boolean containsObjectAt(RoadUser obj, Point p) {
if (containsObject(obj)) {
return objLocs.get(obj).equals(p);
}
return false;
}
@Override
public boolean equalPosition(RoadUser obj1, RoadUser obj2) {
return containsObject(obj1) && containsObject(obj2)
&& getPosition(obj1).equals(getPosition(obj2));
}
@Override
public Map<RoadUser, Point> getObjectsAndPositions() {
final Map<RoadUser, T> copiedMap;
synchronized (objLocs) {
copiedMap = new LinkedHashMap<>();
copiedMap.putAll(objLocs);
// it is save to release the lock now
}
final Map<RoadUser, Point> theMap = new LinkedHashMap<>();
for (final java.util.Map.Entry<RoadUser, T> entry : copiedMap.entrySet()) {
theMap.put(entry.getKey(), locObj2point(entry.getValue()));
}
return theMap;
}
@Override
public Point getPosition(RoadUser roadUser) {
checkArgument(containsObject(roadUser), "RoadUser does not exist: %s.",
roadUser);
return locObj2point(objLocs.get(roadUser));
}
@Override
public Collection<Point> getObjectPositions() {
return getObjectsAndPositions().values();
}
@Override
public Set<RoadUser> getObjects() {
synchronized (objLocs) {
final Set<RoadUser> copy = new LinkedHashSet<>();
copy.addAll(objLocs.keySet());
return copy;
}
}
@Override
public Set<RoadUser> getObjects(Predicate<RoadUser> predicate) {
return Sets.filter(getObjects(), predicate);
}
@SuppressWarnings("unchecked")
@Override
public <Y extends RoadUser> Set<Y> getObjectsAt(RoadUser roadUser,
Class<Y> type) {
final Set<Y> result = new HashSet<>();
for (final RoadUser ru : getObjects(new SameLocationPredicate(roadUser,
type, self))) {
result.add((Y) ru);
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public <Y extends RoadUser> Set<Y> getObjectsOfType(final Class<Y> type) {
return (Set<Y>) getObjects(new Predicate<RoadUser>() {
@Override
public boolean apply(@Nullable RoadUser input) {
return type.isInstance(input);
}
});
}
@Override
public List<Point> getShortestPathTo(RoadUser fromObj, RoadUser toObj) {
checkArgument(objLocs.containsKey(toObj),
"To object (%s) should be in RoadModel.", toObj);
return getShortestPathTo(fromObj, getPosition(toObj));
}
@Override
public List<Point> getShortestPathTo(RoadUser fromObj, Point to) {
checkArgument(objLocs.containsKey(fromObj),
"From object (%s) should be in RoadModel.", fromObj);
return getShortestPathTo(getPosition(fromObj), to);
}
@Override
public boolean doRegister(RoadUser roadUser) {
LOGGER.info("register {}", roadUser);
roadUser.initRoadUser(self);
return true;
}
@Override
public boolean unregister(RoadUser roadUser) {
final boolean contains = containsObject(roadUser);
LOGGER.info("unregister {} succes: {}", roadUser, contains);
if (contains) {
removeObject(roadUser);
return true;
}
return false;
}
@Override
public final EventAPI getEventAPI() {
return eventDispatcher.getPublicEventAPI();
}
@Override
public Unit<Length> getDistanceUnit() {
return unitConversion.getExDistUnit();
}
@Override
public Unit<Velocity> getSpeedUnit() {
return unitConversion.getExSpeedUnit();
}
@SuppressWarnings("null")
private static class SameLocationPredicate implements Predicate<RoadUser> {
private final RoadUser reference;
private final RoadModel model;
private final Class<?> type;
SameLocationPredicate(final RoadUser pReference, final Class<?> pType,
final RoadModel pModel) {
reference = pReference;
type = pType;
model = pModel;
}
@Override
public boolean apply(@Nullable RoadUser input) {
return type.isInstance(input)
&& model.equalPosition(verifyNotNull(input), reference);
}
}
/**
* Simple class for storing destinations and paths leading to them.
* @author Rinde van Lon
*/
protected class DestinationPath {
/**
* The destination of the path.
*/
public final Point destination;
/**
* The path leading to the destination.
*/
public final Queue<Point> path;
DestinationPath(Point dest, Queue<Point> p) {
destination = dest;
path = p;
}
}
}
| 31.081522
| 80
| 0.703008
|
6e00dcb332d5cfcf6584cc7fbc1a2292b818a6b0
| 1,563
|
package binarysearch;
import binarysearch.templates.LLNode;
import binarysearch.templates.Tree;
import java.util.ArrayList;
import java.util.LinkedList;
/*
* Problem: https://binarysearch.com/problems/Linked-List-Union
* Submission: https://binarysearch.com/problems/Linked-List-Union/submissions/7414229
*/
public class P0404 {
class Solution {
public LLNode solve(LLNode ll0, LLNode ll1) {
var ans = new LLNode();
var cur = ans;
var i = ll0;
var j = ll1;
Integer last = null;
while (i != null && j != null) {
if (i.val <= j.val) {
if (last == null || last != i.val) {
cur.next = new LLNode();
cur.next.val = i.val;
cur = cur.next;
last = i.val;
}
i = i.next;
}
else {
if (last == null || last != j.val) {
cur.next = new LLNode();
cur.next.val = j.val;
cur = cur.next;
last = j.val;
}
j = j.next;
}
}
while (i != null) {
if (last == null || last != i.val) {
cur.next = new LLNode();
cur.next.val = i.val;
cur = cur.next;
}
i = i.next;
}
while (j != null) {
if (last == null || last != j.val) {
cur.next = new LLNode();
cur.next.val = j.val;
cur = cur.next;
}
j = j.next;
}
return ans.next;
}
}
}
| 22.014085
| 87
| 0.449136
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.