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
|
---|---|---|---|---|---|
0d80dd2813d0e847bef311dd39c4257d5338dda9 | 805 | package com.study.LXF01.Package06Reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class GetField {
public static void main(String[] args) throws Exception {
Field f = String.class.getDeclaredField("value");
f.getName();
f.getType();
int m = f.getModifiers();
Modifier.isFinal(m);
Modifier.isPublic(m);
Modifier.isProtected(m);
Modifier.isPrivate(m);
Modifier.isStatic(m);
}
}
/**
* 小结:
* java的反射 api提供的 Field类封装了字段的所有信息
* 通过 Class实例的方法可以获取 Field实例:getField(), getFields(), getDeclaredField(), getDeclaredFields()
* 通过 Field实例可以获取字段信息:getName(), getType(), getModifiers()
* 通过 Field实例可以读取或设置某个对象的字段,如果存在访问限制,要首先调用 setAccessible(true)来访问非 public字段
* 通过反射读写字段是一种非常规方法,它会破坏对象的封装
*/
| 28.75 | 93 | 0.688199 |
02d9e4302ca8ffedc59c79f36693084ba474f0b2 | 4,717 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.access.index;
import java.io.IOException;
import com.gemstone.gemfire.cache.query.internal.IndexUpdater;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.engine.access.GemFireTransaction;
import com.pivotal.gemfirexd.internal.engine.access.operations.MemOperation;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.engine.sql.catalog.ExtraIndexInfo;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.io.LimitObjectInput;
import com.pivotal.gemfirexd.internal.iapi.store.raw.Compensation;
import com.pivotal.gemfirexd.internal.iapi.store.raw.Transaction;
import com.pivotal.gemfirexd.internal.iapi.store.raw.log.LogInstant;
/**
* This class enables us to delay the index conglomerate refresh in
* GfxdIndexManager till the commit time. Also helps to avoid refreshing during
* a DML operation, since that should really take a DD read lock which is not
* possible. See bugs #40707, #39808 which are likely due to inability to take
* DD read lock during refresh.
*
* @author swale
*/
public final class MemIndexRefresh extends MemOperation {
private final GfxdIndexManager indexManager;
private boolean lockGIIDone;
private final boolean unlockForIndexGII;
private int dropColumnPos;
/**
* Creates a new instance of {@link MemIndexRefresh}.
*
* @param indexManager
* the {@link GfxdIndexManager} of the indexes to refresh
* @param unlockForIndexGII
* if set to true then {@link IndexUpdater#unlockForIndexGII()}
* during execution at commit
* @param forceRefresh
* true if refresh has to be forced at commit else it can be
* conflated with other {@link MemIndexRefresh}es; currently this
* behaviour is not used or implemented
*/
MemIndexRefresh(GfxdIndexManager indexManager, boolean unlockForIndexGII,
boolean forceRefresh) {
super(indexManager.getContainer());
this.indexManager = indexManager;
this.lockGIIDone = false;
this.unlockForIndexGII = unlockForIndexGII;
}
void setDropColumnPosition(int pos) {
this.dropColumnPos = pos;
}
@Override
public void doMe(Transaction xact, LogInstant instant, LimitObjectInput in)
throws StandardException, IOException {
final GemFireTransaction tc = (GemFireTransaction)xact;
try {
// ignore during abort if no LCC in current context
if (Misc.getLanguageConnectionContext() != null) {
this.indexManager.refreshIndexListAndConstriantDesc(!this.lockGIIDone,
false, tc);
if (this.dropColumnPos > 0) {
// update the column positions for indexes (#47156)
for (GemFireContainer index : this.indexManager.getAllIndexes()) {
GemFireXDUtils.dropColumnAdjustColumnPositions(
index.getBaseColumnPositions(), this.dropColumnPos);
final ExtraIndexInfo indexInfo = index.getExtraIndexInfo();
if (indexInfo != null) {
indexInfo.dropColumnForPrimaryKeyFormatter(this.dropColumnPos);
}
}
}
}
} finally {
try {
if (this.lockGIIDone) {
this.indexManager.unlockForGII(true, tc);
}
} finally {
if (this.unlockForIndexGII) {
this.indexManager.unlockForIndexGII(true, tc);
}
}
}
}
void lockGII(GemFireTransaction tc) {
if (!this.lockGIIDone) {
this.lockGIIDone = this.indexManager.lockForGII(true, tc);
}
}
@Override
public boolean doAtCommitOrAbort() {
return true;
}
@Override
public Compensation generateUndo(Transaction xact, LimitObjectInput in)
throws StandardException, IOException {
// don't adjust for drop column for abort
this.dropColumnPos = 0;
return null;
}
}
| 35.734848 | 79 | 0.717193 |
6c10cbde95cb2fa5d3f3f2f759f121a7e7fbe5e5 | 1,993 | package org.jboss.resteasy.test.resource.param.resource;
import org.jboss.resteasy.test.resource.param.QueryParamAsPrimitiveTest;
import org.junit.Assert;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Path("/default/null")
public class QueryParamAsPrimitiveResourceDefaultNull {
@GET
@Produces("application/boolean")
public String doGet(@QueryParam("boolean") boolean v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, false, v);
return "content";
}
@GET
@Produces("application/byte")
public String doGet(@QueryParam("byte") byte v) {
Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
return "content";
}
@GET
@Produces("application/short")
public String doGet(@QueryParam("short") short v) {
Assert.assertTrue(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0 == v);
return "content";
}
@GET
@Produces("application/int")
public String doGet(@QueryParam("int") int v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0, v);
return "content";
}
@GET
@Produces("application/long")
public String doGet(@QueryParam("long") long v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0L, v);
return "content";
}
@GET
@Produces("application/float")
public String doGet(@QueryParam("float") float v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0.0f, v, 0.0f);
return "content";
}
@GET
@Produces("application/double")
public String doGet(@QueryParam("double") double v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, 0.0d, v, 0.0);
return "content";
}
@GET
@Produces("application/char")
public String doGet(@QueryParam("char") char v) {
Assert.assertEquals(QueryParamAsPrimitiveTest.ERROR_MESSAGE, Character.MIN_VALUE, v);
return "content";
}
}
| 28.884058 | 91 | 0.698445 |
70c3a52c37571500cb65cf8ac248715157c630e1 | 1,018 | package ru.alexproject.blogserver.services;
import org.junit.Assert;
import org.junit.Test;
import ru.alexproject.blogserver.BaseTest;
import ru.alexproject.blogserver.model.domain.Post;
import ru.alexproject.blogserver.model.dto.PostDto;
public class PostServiceTest extends BaseTest {
@Test
public void createPost() {
PostDto postDto = createBasePostDto();
postService.save(modelMapper.convert(postDto, Post.class));
Assert.assertNotNull(postService.getPostById(postDto.getId()));
}
@Test
public void updatePost() {
String newTitle = "Updated Title";
PostDto postDto = createBasePostDto();
postService.save(modelMapper.convert(postDto, Post.class));
Post persistentPost = postService.getPostById(postDto.getId());
persistentPost.setTitle(newTitle);
postService.updatePost(persistentPost.getId(), persistentPost);
Assert.assertEquals(newTitle, postService.getPostById(persistentPost.getId()).getTitle());
}
}
| 35.103448 | 98 | 0.726916 |
376c973143aff338a941076c85ee9e05fcd3729c | 3,618 | /**
* Leetcode - Algorithm - PalindromePermutation
*/
package com.ciaoshen.leetcode;
import java.util.*;
import com.ciaoshen.leetcode.myUtils.*;
/**
* Each problem is initialized with 3 solutions.
* You can expand more solutions.
* Before using your new solutions, don't forget to register them to the solution registry.
*/
class PalindromePermutation implements Problem {
private Map<Integer,Solution> solutions = new HashMap<>(); // solutions registry
// register solutions HERE...
private PalindromePermutation() {
register(new Solution1());
register(new Solution2());
register(new Solution3());
}
private abstract class Solution {
private int id = 0;
abstract public boolean canPermutePalindrome(String s);
protected void sometest() { return; }
}
private class Solution1 extends Solution {
{ super.id = 1; }
public boolean canPermutePalindrome(String s) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!set.add(c)) { set.remove(c); }
}
return set.size() < 2;
}
protected void sometest() {
for (char i = 'a'; i <= 'z'; i++) {
for (char j = 'a'; j <= 'z'; j++) {
System.out.println("\"" + i + "\" XOR \"" + j + "\" = " + (i ^ j));
}
}
for (char i = 'A'; i <= 'Z'; i++) {
for (char j = 'A'; j <= 'Z'; j++) {
System.out.println("\"" + i + "\" XOR \"" + j + "\" = " + (i ^ j));
}
}
}
}
private class Solution2 extends Solution {
{ super.id = 2; }
public boolean canPermutePalindrome(String s) {
return false;
}
}
private class Solution3 extends Solution {
{ super.id = 3; }
public boolean canPermutePalindrome(String s) {
return false;
}
}
// you can expand more solutions HERE if you want...
/**
* register a solution in the solution registry
* return false if this type of solution already exist in the registry.
*/
private boolean register(Solution s) {
return (solutions.put(s.id,s) == null)? true : false;
}
/**
* chose one of the solution to test
* return null if solution id does not exist
*/
private Solution solution(int id) {
return solutions.get(id);
}
private static class Test {
private PalindromePermutation problem = new PalindromePermutation();
private Solution solution = null;
// call method in solution
private void call(String s, String answer) {
System.out.println(s + "? " + solution.canPermutePalindrome(s) + " [answer:" + answer + "]");
}
// public API of Test interface
public void test(int id) {
solution = problem.solution(id);
if (solution == null) { System.out.println("Sorry, [id:" + id + "] doesn't exist!"); return; }
System.out.println("\nCall Solution" + solution.id);
// some small tests
solution.sometest();
// call main method
call("code","false");
call("aab","true");
call("carerac","true");
call("abdg","false");
}
}
public static void main(String[] args) {
Test test = new Test();
test.test(1);
// test.test(2);
// test.test(3);
}
}
| 31.189655 | 114 | 0.52764 |
9cea608eff3904952a870def7983da114f233b06 | 885 | package dev.dankom.game.minecraft.hypixel.player.friend;
import dev.dankom.game.minecraft.hypixel.HypixelAPI;
import dev.dankom.game.minecraft.hypixel.player.PlayerWrapper;
import dev.dankom.game.minecraft.hypixel.reader.HypixelReader;
import dev.dankom.util.general.MapBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FriendWrapper extends HypixelReader {
private final List<Friend> friends = new ArrayList<>();
public FriendWrapper(HypixelAPI api, PlayerWrapper player) {
super(api.buildURL("friends", new MapBuilder<String, Object>().put("uuid", player.uuid)));
for (Object o : (JSONArray) json().get("records")) {
friends.add(new Friend(api, (JSONObject) o));
}
}
public List<Friend> getFriends() {
return friends;
}
}
| 32.777778 | 98 | 0.724294 |
742b67fc4a25b828d8850fc00183fd2517dadfb1 | 518 | package edu.kit.ss17.chatsys.team1.shared.ProtocolError;
import edu.kit.ss17.chatsys.team1.shared.ProtocolError.ErrorElements.ErrorElement;
/**
* Used to describe errors.
*/
public interface ProtocolErrorInterface {
/**
* @return the error message
*/
String getErrorMessage();
/**
* @return if this error is recoverable or not
*/
boolean isFatal();
/**
* @return a serializable {@Link ErrorElement} subclass that is used inside a {@Link StreamProcessor}.
*/
ErrorElement makeErrorElement();
}
| 20.72 | 103 | 0.723938 |
538318085c9726e5d33530e25db967e730818782 | 2,619 | package com.ctbri.wxcc.entity;
import java.util.List;
public class CommunityCommentBean {
private CommunityCommentContaienr data;
public CommunityCommentContaienr getData() {
return data;
}
public void setData(CommunityCommentContaienr data) {
this.data = data;
}
public static class CommunityCommentContaienr{
private int type;
private int is_end;
private int last_index;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getIs_end() {
return is_end;
}
public void setIs_end(int is_end) {
this.is_end = is_end;
}
public int getLast_index() {
return last_index;
}
public void setLast_index(int last_index) {
this.last_index = last_index;
}
public String getCommunity_id() {
return community_id;
}
public void setCommunity_id(String community_id) {
this.community_id = community_id;
}
public List<CommunityComment> getCommList() {
return commList;
}
public void setCommList(List<CommunityComment> commList) {
this.commList = commList;
}
private String community_id;
private List<CommunityComment> commList;
}
public static class CommunityComment{
private String comment_id;
private String user_name;
private String create_time;
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
private String pic_url;
private String comment_zan_num = "0";
public String getComment_id() {
return comment_id;
}
public void setComment_id(String comment_id) {
this.comment_id = comment_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
public String getComment_zan_num() {
return comment_zan_num;
}
public void setComment_zan_num(String comment_zan_num) {
this.comment_zan_num = comment_zan_num;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private String content;
private String status;
}
}
| 24.027523 | 61 | 0.65903 |
881700f19d053460ff886d596332b4acd8e6868c | 327 | package com.example.android.sunshine.app;
import android.app.Application;
import com.facebook.stetho.Stetho;
/**
* Created by safwanx on 7/17/16.
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
| 19.235294 | 50 | 0.700306 |
741bd02c528733beaaf69ca9a9e1cb0c0c241641 | 442 | package com.wrc.tutor.upms.back.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wrc.tutor.common.entity.po.Organisation;
import com.wrc.tutor.common.mapper.OrganisationMapper;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wrc
* @since 2019-08-23
*/
@Service
public class BackOrganisationService extends ServiceImpl<OrganisationMapper, Organisation> {
}
| 22.1 | 92 | 0.771493 |
cc560561c2d0c03ad8f1992196dc4b0a86e4fc20 | 14,324 | package com.diozero.internal.provider.remote.grpc;
/*-
* #%L
* Organisation: diozero
* Project: diozero - Remote Provider
* Filename: GrpcClientI2CDevice.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2021 diozero
* %%
* 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.
* #L%
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.diozero.api.I2CConstants;
import com.diozero.api.I2CDevice.ProbeMode;
import com.diozero.api.I2CDeviceInterface;
import com.diozero.api.RuntimeIOException;
import com.diozero.internal.spi.AbstractDevice;
import com.diozero.internal.spi.InternalI2CDeviceInterface;
import com.diozero.remote.DiozeroProtosConverter;
import com.diozero.remote.message.protobuf.BooleanResponse;
import com.diozero.remote.message.protobuf.ByteResponse;
import com.diozero.remote.message.protobuf.BytesResponse;
import com.diozero.remote.message.protobuf.I2C;
import com.diozero.remote.message.protobuf.I2CServiceGrpc.I2CServiceBlockingStub;
import com.diozero.remote.message.protobuf.Response;
import com.diozero.remote.message.protobuf.Status;
import com.diozero.remote.message.protobuf.WordResponse;
import com.google.protobuf.ByteString;
import io.grpc.StatusRuntimeException;
public class GrpcClientI2CDevice extends AbstractDevice implements InternalI2CDeviceInterface {
private I2CServiceBlockingStub i2cBlockingStub;
private int controller;
private int address;
public GrpcClientI2CDevice(GrpcClientDeviceFactory deviceFactory, String key, int controller, int address,
I2CConstants.AddressSize addressSize) {
super(key, deviceFactory);
i2cBlockingStub = deviceFactory.getI2CServiceStub();
this.controller = controller;
this.address = address;
try {
Response response = i2cBlockingStub.open(I2C.Open.newBuilder().setController(controller).setAddress(address)
.setAddressSize(addressSize.getSize()).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C open: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C open: " + e, e);
}
}
@Override
public boolean probe(ProbeMode mode) throws RuntimeIOException {
try {
BooleanResponse response = i2cBlockingStub.probe(I2C.Probe.newBuilder().setController(controller)
.setAddress(address).setProbeMode(DiozeroProtosConverter.convert(mode)).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C probe: " + response.getDetail());
}
return response.getData();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C probe: " + e, e);
}
}
@Override
public void writeQuick(byte bit) {
try {
Response response = i2cBlockingStub
.writeQuick(I2C.Bit.newBuilder().setController(controller).setAddress(address).setBit(bit).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write quick: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write quick: " + e, e);
}
}
@Override
public byte readByte() throws RuntimeIOException {
try {
ByteResponse response = i2cBlockingStub
.readByte(I2C.Identifier.newBuilder().setController(controller).setAddress(address).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read byte: " + response.getDetail());
}
return (byte) response.getData();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read byte: " + e, e);
}
}
@Override
public void writeByte(byte b) throws RuntimeIOException {
try {
Response response = i2cBlockingStub.writeByte(I2C.ByteMessage.newBuilder().setController(controller)
.setAddress(address).setData(b & 0xff).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write byte: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write byte: " + e, e);
}
}
@Override
public byte readByteData(int register) throws RuntimeIOException {
try {
ByteResponse response = i2cBlockingStub.readByteData(I2C.Register.newBuilder().setController(controller)
.setAddress(address).setRegister(register).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read byte data: " + response.getDetail());
}
return (byte) response.getData();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read byte data: " + e, e);
}
}
@Override
public void writeByteData(int register, byte b) throws RuntimeIOException {
try {
Response response = i2cBlockingStub.writeByteData(I2C.RegisterAndByte.newBuilder().setController(controller)
.setAddress(address).setRegister(register).setData(b & 0xff).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write byte data: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write byte data: " + e, e);
}
}
@Override
public short readWordData(int register) throws RuntimeIOException {
try {
WordResponse response = i2cBlockingStub.readWordData(I2C.Register.newBuilder().setController(controller)
.setAddress(address).setRegister(register).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read word data: " + response.getDetail());
}
return (short) response.getData();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read word data: " + e, e);
}
}
@Override
public void writeWordData(int register, short s) throws RuntimeIOException {
try {
Response response = i2cBlockingStub.writeWordData(I2C.RegisterAndWordData.newBuilder()
.setController(controller).setAddress(address).setRegister(register).setData(s & 0xffff).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write word data: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write word data: " + e, e);
}
}
@Override
public short processCall(int register, short s) throws RuntimeIOException {
try {
WordResponse response = i2cBlockingStub.processCall(I2C.RegisterAndWordData.newBuilder()
.setController(controller).setAddress(address).setRegister(register).setData(s & 0xffff).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C process call: " + response.getDetail());
}
return (short) response.getData();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C process call: " + e, e);
}
}
@Override
public byte[] readBlockData(int register) throws RuntimeIOException {
try {
I2C.ByteArrayWithLengthResponse response = i2cBlockingStub.readBlockData(I2C.Register.newBuilder()
.setController(controller).setAddress(address).setRegister(register).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read block data: " + response.getDetail());
}
return response.getData().toByteArray();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read block data: " + e, e);
}
}
@Override
public void writeBlockData(int register, byte... data) throws RuntimeIOException {
try {
Response response = i2cBlockingStub
.writeBlockData(I2C.RegisterAndByteArray.newBuilder().setController(controller).setAddress(address)
.setRegister(register).setData(ByteString.copyFrom(data)).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write block data: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write block data: " + e, e);
}
}
@Override
public byte[] blockProcessCall(int register, byte... txData) throws RuntimeIOException {
try {
BytesResponse response = i2cBlockingStub
.blockProcessCall(I2C.RegisterAndByteArray.newBuilder().setController(controller)
.setAddress(address).setRegister(register).setData(ByteString.copyFrom(txData)).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C block process call: " + response.getDetail());
}
return response.getData().toByteArray();
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C block process call: " + e, e);
}
}
@Override
public int readI2CBlockData(int register, byte[] buffer) throws RuntimeIOException {
try {
BytesResponse response = i2cBlockingStub
.readI2CBlockData(I2C.RegisterAndNumBytes.newBuilder().setController(controller).setAddress(address)
.setRegister(register).setLength(buffer.length).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read I2C block data: " + response.getDetail());
}
byte[] response_data = response.getData().toByteArray();
System.arraycopy(response_data, 0, buffer, 0, response_data.length);
return response_data.length;
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read I2C block: " + e, e);
}
}
@Override
public void writeI2CBlockData(int register, byte... data) throws RuntimeIOException {
try {
Response response = i2cBlockingStub
.writeI2CBlockData(I2C.RegisterAndByteArray.newBuilder().setController(controller)
.setAddress(address).setRegister(register).setData(ByteString.copyFrom(data)).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write I2C block data: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write I2C block data: " + e, e);
}
}
@Override
public int readBytes(byte[] buffer) throws RuntimeIOException {
try {
BytesResponse response = i2cBlockingStub.readBytes(I2C.NumBytes.newBuilder().setController(controller)
.setAddress(address).setLength(buffer.length).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C read bytes: " + response.getDetail());
}
byte[] response_data = response.getData().toByteArray();
System.arraycopy(response_data, 0, buffer, 0, response_data.length);
return response_data.length;
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C read bytes: " + e, e);
}
}
@Override
public void writeBytes(byte... data) throws RuntimeIOException {
try {
Response response = i2cBlockingStub.writeBytes(I2C.ByteArray.newBuilder().setController(controller)
.setAddress(address).setData(ByteString.copyFrom(data)).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C write bytes: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C write bytes: " + e, e);
}
}
@Override
public void readWrite(I2CDeviceInterface.I2CMessage[] messages, byte[] buffer) {
try {
I2C.ReadWrite.Builder request_builder = I2C.ReadWrite.newBuilder().setController(controller)
.setAddress(address);
// Extract the write message data
int buffer_pos = 0;
byte[] tx_data;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
for (I2CDeviceInterface.I2CMessage message : messages) {
if (message.isWrite()) {
baos.write(buffer, buffer_pos, message.getLength());
}
buffer_pos += message.getLength();
request_builder.addMessage(I2C.I2CMessage.newBuilder().setFlags(message.getFlags())
.setLen(message.getLength()).build());
}
tx_data = baos.toByteArray();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
request_builder.setData(ByteString.copyFrom(tx_data));
BytesResponse response = i2cBlockingStub.readWrite(request_builder.build());
// Copy the read data back into buffer
byte[] rx_data = response.getData().toByteArray();
buffer_pos = 0;
int rx_data_pos = 0;
for (I2CDeviceInterface.I2CMessage message : messages) {
if (message.isRead()) {
System.arraycopy(rx_data, rx_data_pos, buffer, buffer_pos, message.getLength());
rx_data_pos += message.getLength();
}
buffer_pos += message.getLength();
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C readWrite: " + e, e);
}
}
@Override
protected void closeDevice() throws RuntimeIOException {
try {
Response response = i2cBlockingStub
.close(I2C.Identifier.newBuilder().setController(controller).setAddress(address).build());
if (response.getStatus() != Status.OK) {
throw new RuntimeIOException("Error in I2C close: " + response.getDetail());
}
} catch (StatusRuntimeException e) {
throw new RuntimeIOException("Error in I2C close: " + e, e);
}
}
}
| 38.197333 | 111 | 0.730941 |
d63195587ba6524d18713f4f8ed7b1081028bf22 | 1,085 | package display;
import display.internal.Shader;
import display.internal.Window;
import imgui.ImGui;
import imgui.extension.implot.ImPlot;
import imgui.extension.implot.ImPlotContext;
public abstract class Application implements AutoCloseable {
public Window window;
public ImPlotContext imPlotContext = ImPlot.createContext();
private UI ui;
public Application(int width, int height, String title) {
window = new Window(width,height,title);
window.registerStart(this::onInit);
window.registerLoop(this::onUpdate);
window.registerClose(this::onClose);
}
public void bindUI(UI ui) {
this.ui = ui;
}
public void onInit() {
ImPlot.setCurrentContext(imPlotContext);
Shader.SHADER.create("basic");
}
public abstract void onUpdate(Float deltaTime);
public void onClose() {
close();
}
protected void startDockSpace() {
if (ui!=null) window.setupDockSpace(ui::buildDockSpace);
}
protected void endDockSpace() {
if (ui!=null) ImGui.end();
}
@Override
public void close() {
Shader.SHADER.destroy();
if (ui!=null) ui.destroy();
}
}
| 20.865385 | 61 | 0.727189 |
d189e5ab777c54d0afad61a6c73618ce20b16fe3 | 989 | package ${package}.tapestry.integration.pages;
import org.apache.tapestry5.test.SeleniumTestCase;
import org.testng.annotations.Test;
public class LoginTest extends SeleniumTestCase {
@Test
void loginSuccess() {
// given
open("/login");
assertTrue(getTitle().startsWith("Login"));
// when
type("//input[@name='email']", "[email protected]");
type("//input[@name='password']", "Tapestry5");
submit("//form[@id='login']");
// then
waitForPageToLoad();
assertTrue(getTitle().startsWith("Index"));
}
@Test
void loginError() {
// given
open("/login");
assertTrue(getTitle().startsWith("Login"));
// when
type("//input[@name='email']", "xxx");
type("//input[@name='password']", "xxx");
submit("//form[@id='login']");
// then
waitForPageToLoad();
assertTrue(getTitle().startsWith("Login"));
}
}
| 24.121951 | 68 | 0.55814 |
ba3f70a27a7bf35fd92a943192ac99a5815870aa | 7,401 | package org.openrdf.http.object.chain;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.openrdf.annotations.Method;
import org.openrdf.annotations.Path;
import org.openrdf.annotations.Type;
import org.openrdf.http.object.exceptions.BadGateway;
import org.openrdf.http.object.helpers.ObjectContext;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.ObjectRepository;
import org.openrdf.repository.object.config.ObjectRepositoryConfig;
import org.openrdf.repository.object.config.ObjectRepositoryFactory;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.memory.MemoryStore;
public class TestHeadRequestExecChain extends TestCase {
private static final String RESOURCE = "http://example.org/";
public static class TestResponse {
public static int counter;
@Method("HEAD")
public HttpResponse head() {
HttpResponse head = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
head.addHeader("Cache-Control", "no-store");
return head;
}
@Method("GET")
@Type("text/plain")
public String get() {
counter++;
return "Hello World!";
}
@Method("POST")
public void post(@Type("text/plain") String text) {
counter++;
System.out.println(text);
}
@Method("GET")
@Path("etag")
@Type("text/plain")
@org.openrdf.annotations.Header("ETag:\"tag\"")
public String getETag() {
counter++;
return "Hello World!";
}
@Method("GET")
@Path("intercept-etag")
@Type("text/plain")
public String getInterceptETag() {
counter++;
return "Hello World!";
}
}
private ObjectContext context;
private ObjectRepository repository;
private RequestExecChain chain;
static InputStream body;
public void setUp() throws Exception {
context = ObjectContext.create();
context.setProtocolScheme("http");
SailRepository memory = new SailRepository(new MemoryStore());
memory.initialize();
ObjectRepositoryConfig config = new ObjectRepositoryConfig();
config.addBehaviour(TestResponse.class, "urn:test:test-response");
repository = new ObjectRepositoryFactory().createRepository(config,
memory);
ObjectConnection con = repository.getConnection();
ValueFactory vf = con.getValueFactory();
con.add(vf.createURI(RESOURCE), RDF.TYPE,
vf.createURI("urn:test:test-response"));
con.close();
chain = new RequestExecChain();
chain.addRepository(RESOURCE, repository);
}
public void tearDown() throws Exception {
chain.shutdown();
repository.shutDown();
chain.awaitTermination(1, TimeUnit.SECONDS);
}
public void testGetHelloWorld() throws Exception {
BasicHttpRequest request = new BasicHttpRequest("GET", RESOURCE,
HttpVersion.HTTP_1_1);
request.setHeader("Accept", "text/plain");
HttpResponse resp = execute(request);
assertEquals(resp.getStatusLine().getReasonPhrase(), 200, resp
.getStatusLine().getStatusCode());
assertEquals("Hello World!", EntityUtils.toString(resp.getEntity()));
Header length = resp.getFirstHeader("Content-Length");
assertNotNull(length);
assertEquals(Integer.toString("Hello World!".length()), length.getValue());
}
public void testPostHelloWorld() throws Exception {
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", RESOURCE,
HttpVersion.HTTP_1_1);
request.setHeader("Content-Type", "text/plain");
request.setEntity(new StringEntity("Hello World!"));
HttpResponse resp = execute(request);
assertEquals(resp.getStatusLine().getReasonPhrase(), 204, resp
.getStatusLine().getStatusCode());
}
public void testGetETagHelloWorld() throws Exception {
TestResponse.counter = 0;
InterceptorTester.callback = new HttpRequestChainInterceptor() {
@Override
public HttpResponse intercept(HttpRequest request,
HttpContext context) throws HttpException, IOException {
String m = request.getRequestLine().getMethod();
HttpRequest or = ObjectContext.adapt(context)
.getOriginalRequest();
assertTrue("GET".equals(m) || or != null
&& "GET".equals(or.getRequestLine().getMethod()));
return null;
}
@Override
public void process(HttpRequest request, HttpResponse response,
HttpContext context) throws HttpException, IOException {
HttpEntity e = response.getEntity();
Header ct = e == null ? response.getFirstHeader("Content-Type") : e.getContentType();
assertTrue(String.valueOf(ct).contains("text/plain"));
}
};
BasicHttpRequest request = new BasicHttpRequest("GET", RESOURCE + "etag",
HttpVersion.HTTP_1_1);
request.setHeader("Accept", "text/plain");
HttpResponse resp = execute(request);
assertEquals(resp.getStatusLine().getReasonPhrase(), 200, resp
.getStatusLine().getStatusCode());
assertEquals("\"tag\"", resp.getFirstHeader("ETag").getValue());
execute(request);
InterceptorTester.callback = null;
assertEquals(2, TestResponse.counter);
}
public void testGetInterceptETagHelloWorld() throws Exception {
TestResponse.counter = 0;
InterceptorTester.callback = new HttpRequestChainInterceptor() {
@Override
public HttpResponse intercept(HttpRequest request,
HttpContext context) throws HttpException, IOException {
String m = request.getRequestLine().getMethod();
HttpRequest or = ObjectContext.adapt(context)
.getOriginalRequest();
assertTrue("GET".equals(m)
|| "GET".equals(or.getRequestLine().getMethod()));
return null;
}
@Override
public void process(HttpRequest request, HttpResponse response,
HttpContext context) throws HttpException, IOException {
response.addHeader("ETag", "\"intercept-etag\"");
}
};
BasicHttpRequest request = new BasicHttpRequest("GET", RESOURCE + "intercept-etag",
HttpVersion.HTTP_1_1);
request.setHeader("Accept", "text/plain");
HttpResponse resp = execute(request);
assertEquals(resp.getStatusLine().getReasonPhrase(), 200, resp
.getStatusLine().getStatusCode());
execute(request);
InterceptorTester.callback = null;
assertEquals(2, TestResponse.counter);
}
private HttpResponse execute(HttpRequest request)
throws InterruptedException, ExecutionException {
return chain.execute(new HttpHost("example.org"), request, context,
new FutureCallback<HttpResponse>() {
public void failed(Exception ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new BadGateway(ex);
}
}
public void completed(HttpResponse result) {
// yay!
}
public void cancelled() {
// oops!
}
}).get();
}
}
| 33.188341 | 97 | 0.738279 |
4ccca027bed5b9ddc2f9a2413b6c558e6158dd4a | 1,981 | /*
* Copyright 2015-2018 Micro Focus or one of its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.hpe.caf.autoscale.scaler.marathon;
import com.hpe.caf.api.ConfigurationException;
import com.hpe.caf.api.ConfigurationSource;
import com.hpe.caf.api.autoscale.ScalerException;
import com.hpe.caf.api.autoscale.ServiceScaler;
import com.hpe.caf.api.autoscale.ServiceScalerProvider;
import com.hpe.caf.autoscale.MarathonAutoscaleConfiguration;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class MarathonServiceScalerProvider implements ServiceScalerProvider
{
@Override
public ServiceScaler getServiceScaler(final ConfigurationSource configurationSource)
throws ScalerException
{
try {
MarathonAutoscaleConfiguration config = configurationSource.getConfiguration(MarathonAutoscaleConfiguration.class);
URL url = new URL(config.getEndpoint());
Marathon marathon = MarathonClient.getInstance(url.toString());
return new MarathonServiceScaler(marathon, config.getMaximumInstances(), url, new AppInstancePatcher(url.toURI()));
} catch (ConfigurationException | MalformedURLException | URISyntaxException e) {
throw new ScalerException("Failed to create service scaler", e);
}
}
}
| 40.428571 | 127 | 0.760727 |
8d535d732fe6dba10bef429695b78b05ef3bc5ff | 246 | package com.aaron.demo.patterns.strategy;
public class CashReturn implements CashSuper {
@Override
public double acceptCash(double money) {
if (money >= 300) {
return money - 300;
}
return 0;
}
}
| 18.923077 | 46 | 0.597561 |
9c78765cba1ecc077056279ef24271b7209d4a27 | 1,164 | package com.loserico.pattern.singleton;
import java.lang.reflect.Constructor;
/**
* 懒汉式v2版在反射的作用下,单例结构是会被破坏的
*
* <p>
* Copyright: Copyright (c) 2018-05-05 20:40
* <p>
* Company: DataSense
* <p>
* @author Rico Yu [email protected]
* @version 1.0
* @on
*/
public class SynchronizedLazySingletonTest {
public static void main(String[] args) {
//创建第一个实例
SynchronizedLazySingleton instance1 = SynchronizedLazySingleton.getInstance();
//通过反射创建第二个实例
SynchronizedLazySingleton instance2 = null;
try {
Class<SynchronizedLazySingleton> clazz = SynchronizedLazySingleton.class;
Constructor<SynchronizedLazySingleton> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
instance2 = constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
/*
* 检查两个实例的hash值
* Instance 1 hash:5433634
* Instance 2 hash:2430287
*
* 根据哈希值可以看出,反射破坏了单例的特性,因此懒汉式StatisticInnerClassLazySingleton版诞生了
* @on
*/
System.out.println("Instance 1 hash:" + instance1.hashCode());
System.out.println("Instance 2 hash:" + instance2.hashCode());
}
} | 27.069767 | 88 | 0.698454 |
f7634bde94798bcaa5907ffd711a313782c5411c | 2,377 | /*
* Copyright (C) 2013 - 2018 Michael Bulla [[email protected]]
*
* 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.popper.fw.jemmy.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.netbeans.jemmy.TimeoutExpiredException;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.popper.fw.annotations.ImplementedBy;
import org.popper.fw.interfaces.IAnnotationProcessor;
import org.popper.fw.interfaces.LocatorContextInformation;
import org.popper.fw.interfaces.ReEvalutateException;
import org.popper.fw.jemmy.JemmyContext;
import org.popper.fw.jemmy.JemmyPageObjectHelper.SearchContextProvider;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ImplementedBy(DoesExistProcessor.class)
public @interface DoesExist {
}
class DoesExistProcessor implements IAnnotationProcessor<DoesExist, Boolean> {
private final JemmyContext context;
public DoesExistProcessor(JemmyContext context) {
super();
this.context = context;
}
@Override
public Boolean processAnnotation(DoesExist dialogLocator, LocatorContextInformation info, Boolean lastResult)
throws ReEvalutateException {
int oldTimeout = context.getRelevantTimeouts();
try {
context.setRelevantTimeouts(0);
ContainerOperator op = info.getParent().getExtension(SearchContextProvider.class).getSearchContext();
return op.isShowing() && op.isVisible();
} catch (TimeoutExpiredException e) {
return false;
} finally {
context.setRelevantTimeouts(oldTimeout);
}
}
} | 36.569231 | 114 | 0.730753 |
1f83b87d95acb73cb599799126e1d4eaf3d91591 | 2,232 | /*
* Cloud Resource & Information Management System (CRIMSy)
* Copyright 2020 Leibniz-Institut f. Pflanzenbiochemie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.ipb_halle.lbac.admission;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "nestingpathsets")
public class NestingPathSetEntity implements Serializable {
/**
* This class associates a nesting path (i.e. a collection
* of nesting path elements) to a nested membership. The nested
* <code>Membership</code> is specified by the <code>membership_id</code>
* field. However, this class does NOT contain the single path elements,
* as this part is covered by <code>NestingPathEntity</code>.
*
* A nested membership can be constituted by more than one
* nesting path.
*/
private final static long serialVersionUID = 1L;
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Integer id;
@Column(name = "membership_id")
private Integer membership_id;
public NestingPathSetEntity() {
}
public NestingPathSetEntity(Integer id, Integer membershipId) {
this.id = id;
this.membership_id = membershipId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMembership_id() {
return membership_id;
}
public void setMembership_id(Integer membership_id) {
this.membership_id = membership_id;
}
}
| 29.368421 | 77 | 0.709229 |
ef36b452764c28614e4b8347e984b525865a2674 | 1,768 | package co.currere.controller;
import co.currere.domain.Game;
import co.currere.service.GameService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ExtendWith(SpringExtension.class)
@WebMvcTest(GameController.class)
public class GameControllerTest {
@MockBean
private GameService gameService;
@Autowired
private MockMvc mvc;
private JacksonTester<Game> jsonGame;
@BeforeEach
public void setup() {
JacksonTester.initFields(this, new ObjectMapper());
}
@Test
public void getRandomGameTest() throws Exception {
given(gameService.createNewGame()).willReturn(new Game(230, 20));
MockHttpServletResponse response = mvc.perform(
get("/service/game").accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonGame.write(new Game(230, 20)).getJson());
}
} | 34 | 86 | 0.811652 |
134e73cb5b41916a7a7c0a312ad05eebe39a7a31 | 710 | import java.util.*;
import java.io.*;
class gcd {
// naive approach-->O(n)
static int findGcd(int a,int b){
int min=Math.min(a,b);
int ans=1;
for(int i=2;i<=min;i++){
ans=(a%i==0 && b%i==0)?i:ans;
}
return ans;
}
// optimized approach--->O(log(min(a,b)))
static int calcGCD(int a,int b){
while(b!=0){
int temp=a;
a=b;
b=a%b;
}
return a;
}
public static void main(String args[]){
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();
System.out.println(findGcd(a, b));
System.out.println(calcGCD(a, b));
}
}
| 22.903226 | 45 | 0.474648 |
7a844e9e712752ab15944af140962ddf3c76d652 | 7,375 | package study.daydayup.wolf.business.trade.buy.biz.loan.entity;
import org.springframework.validation.annotation.Validated;
import study.daydayup.wolf.business.trade.api.config.TradeTag;
import study.daydayup.wolf.business.trade.api.domain.entity.Contract;
import study.daydayup.wolf.business.trade.api.domain.entity.Order;
import study.daydayup.wolf.business.trade.api.domain.entity.contract.LoanTerm;
import study.daydayup.wolf.business.trade.api.domain.entity.contract.RepaymentTerm;
import study.daydayup.wolf.business.trade.api.domain.entity.trade.TradeStateLog;
import study.daydayup.wolf.business.trade.api.domain.enums.PaymentReturnEnum;
import study.daydayup.wolf.business.trade.api.domain.enums.TradeTypeEnum;
import study.daydayup.wolf.business.trade.api.domain.event.base.PaidEvent;
import study.daydayup.wolf.business.trade.api.domain.state.base.PaidState;
import study.daydayup.wolf.business.trade.api.domain.state.base.WaitToPayState;
import study.daydayup.wolf.business.trade.api.domain.util.StateUtil;
import study.daydayup.wolf.business.trade.api.dto.buy.base.TradeNotification;
import study.daydayup.wolf.common.lang.enums.finance.FeeStrategyEnum;
import study.daydayup.wolf.common.lang.enums.trade.TradePhaseEnum;
import study.daydayup.wolf.common.model.type.string.id.TradeNo;
import study.daydayup.wolf.common.model.type.string.Tag;
import study.daydayup.wolf.common.util.lang.DecimalUtil;
import study.daydayup.wolf.common.util.lang.StringUtil;
import study.daydayup.wolf.framework.layer.domain.AbstractEntity;
import study.daydayup.wolf.framework.layer.domain.Entity;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
* study.daydayup.wolf.business.trade.buy.loan
*
* @author Wingle
* @since 2019/12/13 4:41 下午
**/
public class LoanOrderEntity extends AbstractEntity<Order> implements Entity {
private Contract contract;
public LoanOrderEntity(Contract contract) {
this.contract = contract;
this.isNew = true;
}
public LoanOrderEntity(Order order) {
model = order;
key = Order.builder()
.tradeNo(model.getTradeNo())
.tradeType(model.getTradeType())
.buyerId(model.getBuyerId())
.sellerId(model.getSellerId())
.build();
isNew = false;
}
private void initChanges() {
if (changes != null) {
return;
}
changes = new Order();
}
public int paid(@Validated TradeNotification notification) {
if (StateUtil.equals(model.getState(), new PaidState())) {
return PaymentReturnEnum.DUPLICATE.getCode();
}
if (!StateUtil.equals(model.getState(), new WaitToPayState())) {
return PaymentReturnEnum.ERROR.getCode();
}
PaidEvent event = PaidEvent.builder()
.tradeNo(model.getTradeNo())
.buyerId(model.getBuyerId())
.sellerId(model.getSellerId())
.build();
key.setState(model.getState());
model.setStateEvent(event);
model.setOutTradeNo(notification.getOutTradeNo());
model.setPaymentMethod(notification.getPaymentMethod());
initChanges();
changes.setStateEvent(event);
changes.setOutTradeNo(notification.getOutTradeNo());
changes.setPaymentMethod(notification.getPaymentMethod());
logStateChange();
return PaymentReturnEnum.SUCCESS.getCode();
}
public void loan() {
if (contract == null) {
return;
}
isNew = true;
LocalDateTime expiredAt = LocalDateTime.now().plusDays(30);
model = createOrder(TradeTypeEnum.LOAN_ORDER);
model.setAmount(getLoanAmount());
model.setExpiredAt(expiredAt);
setLoanTag();
}
public void loanByProxy() {
}
public void repay() {
RepaymentTerm repayment = contract.getRepaymentTerm();
if (contract == null || null == repayment) {
return;
}
isNew = true;
TradeTypeEnum tradeType = TradeTypeEnum.REPAY_ORDER;
model = createOrder(tradeType);
model.setAmount(repayment.getAmount());
LocalDateTime expireAt = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));
model.setExpiredAt(expireAt);
setRepayTag();
}
public void prepayAll() {
}
public void collect() {
}
public void collectPartly() {}
public void collectAll() {
}
private void setLoanTag() {
Tag contractTag = new Tag(contract.getTags());
if (!contractTag.contains(TradeTag.FIRST_TRADE)) {
return;
}
model.setTags(TradeTag.FIRST_TRADE);
}
private void setRepayTag() {
Tag contractTag = new Tag(contract.getTags());
String repayTags = contract.getRepaymentTerm().getTags();
Tag orderTag = new Tag(repayTags);
String firstInstallment = StringUtil.join(TradeTag.INSTALLMENT_PREFIX, 1);
if (contractTag.contains(TradeTag.FIRST_TRADE) && orderTag.contains(firstInstallment)) {
orderTag.add(TradeTag.FIRST_TRADE);
}
model.setTags(orderTag.toString());
}
private Order createOrder(TradeTypeEnum tradeType) {
return Order.builder()
.tradeNo(createOrderNo())
.tradeType(tradeType.getCode())
.relatedTradeNo(contract.getTradeNo())
.buyerId(contract.getBuyerId())
.buyerName(contract.getBuyerName())
.sellerId(contract.getSellerId())
.sellerName(contract.getSellerName())
.source(contract.getSource())
.createdAt(LocalDateTime.now())
.postage(BigDecimal.ZERO)
.currency(contract.getLoanTerm().getCurrency())
.build();
}
private String createOrderNo() {
return TradeNo.builder()
.accountId(contract.getBuyerId())
.tradePhase(TradePhaseEnum.ORDER_PHASE)
.build()
.create();
}
private BigDecimal getLoanAmount() {
LoanTerm loan = contract.getLoanTerm();
if (FeeStrategyEnum.PRE.getCode() == loan.getFeePayStrategy()) {
BigDecimal result = loan.getAmount();
result = result.subtract(loan.getHandlingFee());
return DecimalUtil.scale(result);
}
return loan.getAmount();
}
private void logStateChange() {
TradeStateLog log = TradeStateLog.builder()
.tradeNo(model.getTradeNo())
.relatedTradeNo(model.getRelatedTradeNo())
.tradeType(model.getTradeType())
.buyerId(model.getBuyerId())
.sellerId(model.getSellerId())
.sourceState(model.getState().getCode())
.amount(model.getAmount())
.paymentMethod(model.getPaymentMethod())
.consignMethod(model.getConsignMethod())
.tags(model.getTags())
.source(model.getSource())
.sourceVersion(model.getVersion())
.createdAt(LocalDateTime.now())
.build();
changes.setStateLog(log);
}
}
| 33.071749 | 96 | 0.639864 |
f75b58a6d3e9937a2e3d3795ad51dc74311662ec | 668 | /**
*
*/
package com.ugiant.common.utils.excel.fieldtype;
import org.apache.commons.lang3.StringUtils;
import com.ugiant.modules.sys.model.Office;
import com.ugiant.modules.sys.utils.UserUtils;
/**
* 字段类型转换
*
* @version 2013-03-10
*/
public class OfficeType {
/**
* 获取对象值(导入)
*/
public static Object getValue(String val) {
for (Office e : UserUtils.getOfficeList()){
if (StringUtils.trimToEmpty(val).equals(e.getName())){
return e;
}
}
return null;
}
/**
* 设置对象值(导出)
*/
public static String setValue(Object val) {
if (val != null && ((Office)val).getName() != null){
return ((Office)val).getName();
}
return "";
}
}
| 16.7 | 57 | 0.639222 |
f5f3e8e78c191c4a95aca3d95c9833f36f42ec59 | 289 | package in.brewcode.api.persistence.dao;
import in.brewcode.api.persistence.dao.common.IOperationsDao;
import in.brewcode.api.persistence.entity.Content;
import java.util.List;
public interface IContentDao extends IOperationsDao<Content>{
List<Content> getArticleContents(Long id);
}
| 24.083333 | 61 | 0.820069 |
b8ef92a6d3bd1c5226344947caa92fa871d94ee1 | 759 | package projects.nyinyihtunlwin.talks.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import projects.nyinyihtunlwin.talks.R;
import projects.nyinyihtunlwin.talks.data.vo.PlaylistsVO;
import projects.nyinyihtunlwin.talks.viewholders.PlaylistsViewHolder;
/**
* Created by Dell on 1/24/2018.
*/
public class PlaylistsAdapter extends BaseAdapter<PlaylistsViewHolder, PlaylistsVO> {
public PlaylistsAdapter(Context context) {
super(context);
}
@Override
public PlaylistsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.view_item_playlists, parent, false);
return new PlaylistsViewHolder(view);
}
}
| 26.172414 | 89 | 0.769433 |
6493d68f891faa0b05a9139969d8281454bac7d0 | 1,778 | package com.lambkit.core.api.route;
/**
* @author Henry Yang 杨勇 ([email protected])
* @version 1.0
* @Package com.lambkit.core.api.route
*/
public class ApiRequest {
private String memberId;
private String accessToken;
private String sign;
private String uCode;
private String eCode;
private String timestamp;
private String clientIp;
private boolean isLogin;
private String params;
private String methodName;
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getuCode() {
return uCode;
}
public void setuCode(String uCode) {
this.uCode = uCode;
}
public String geteCode() {
return eCode;
}
public void seteCode(String eCode) {
this.eCode = eCode;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public boolean isLogin() {
return isLogin;
}
public void setLogin(boolean login) {
isLogin = login;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
}
| 17.431373 | 50 | 0.670979 |
d64cc49e373ec95b036de166571b9dd7799a8c8a | 13,892 | /*
* Copyright © 2016 Intel Corporation. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.webrtc.sample.utils;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.intel.webrtc.base.FilterCallback;
import com.intel.webrtc.base.VideoFrameFilterInterface;
import org.webrtc.EglBase;
import org.webrtc.GlUtil;
import java.nio.FloatBuffer;
import java.util.concurrent.CountDownLatch;
public class WoogeenBrightenFilter implements VideoFrameFilterInterface {
// Vertex coordinates in Normalized Device Coordinates, i.e. (-1, -1) is bottom-left and (1,1) is top-right.
private static final FloatBuffer FULL_RECTANGLE_BUF =
GlUtil.createFloatBuffer(new float[]{
-1.0f, -1.0f, // Bottom left.
1.0f, -1.0f, // Bottom right.
-1.0f, 1.0f, // Top left.
1.0f, 1.0f, // Top right.
});
// Texture coordinates - (0, 0) is bottom-left and (1, 1) is top-right.
private static final FloatBuffer FULL_RECTANGLE_TEX_BUF =
GlUtil.createFloatBuffer(new float[]{
0.0f, 1.0f,
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f
});
private static final String VERTEX_SHADER_STRING =
"varying vec2 interp_tc;\n"
+ "attribute vec4 in_pos;\n"
+ "attribute vec4 in_tc;\n"
+ "\n"
+ "uniform mat4 texMatrix;\n"
+ "\n"
+ "void main() {\n"
+ " gl_Position = in_pos;\n"
+ " interp_tc = (texMatrix * in_tc).xy;\n"
+ "}\n";
private static final String BRIGHTEN_FRAGMENT_SHADER_STRING =
"#extension GL_OES_EGL_image_external : require\n"
+ "precision mediump float;\n"
+ "varying vec2 interp_tc;\n"
+ "\n"
+ "uniform samplerExternalOES oes_tex;\n"
+ "\n"
+ "void main() {\n"
+ " lowp vec4 textureColor = texture2D(oes_tex, interp_tc);\n"
+ " gl_FragColor = vec4((textureColor.rgb + vec3(0.25)), textureColor.w);\n"
+ "}\n";
//OpenGL program id.
private int glProgramId = 0;
private int[] glFramebufferId;
private int[] glFramebufferTextureId;
//Frame size.
private int frameWidth = 0;
private int frameHeight = 0;
//shader string
private String vertexShaderString;
private String fragmentShaderString;
//EglBase that holds the context the app runs on.
private EglBase eglBase;
private boolean isInitialized = false;
//Singleton instance.
private static WoogeenBrightenFilter filterInstance;
//All OpenGL actions are excused on filter handler thread.
private static HandlerThread filterThread;
private static Handler filterHandler;
public static WoogeenBrightenFilter create(final EglBase.Context sharedContext) {
return create(sharedContext, null, null);
}
public static WoogeenBrightenFilter create(final EglBase.Context sharedContext,
final String vertexShaderString,
final String fragmentShaderString) {
filterThread = new HandlerThread("FilterHandlerThread");
filterThread.start();
filterHandler = new Handler(filterThread.getLooper());
try {
final CountDownLatch barrier = new CountDownLatch(1);
filterHandler.post(new Runnable() {
@Override
public void run() {
if (filterInstance == null) {
filterInstance = new WoogeenBrightenFilter(sharedContext,
vertexShaderString,
fragmentShaderString);
}
barrier.countDown();
}
});
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return filterInstance;
}
private WoogeenBrightenFilter(EglBase.Context sharedContext, String vertexShaderString,
String fragmentShaderString) {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
this.vertexShaderString = vertexShaderString == null ? VERTEX_SHADER_STRING
: vertexShaderString;
this.fragmentShaderString = fragmentShaderString == null ? BRIGHTEN_FRAGMENT_SHADER_STRING
: fragmentShaderString;
eglBase = EglBase.create(sharedContext, EglBase.CONFIG_PIXEL_BUFFER);
eglBase.createDummyPbufferSurface();
}
private void initGL(String vertexShaderString, String fragmentShaderString) {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
int vertexShader;
int fragmentShader;
int programId;
int[] link = new int[1];
eglBase.makeCurrent();
vertexShader = loadShader(vertexShaderString, GLES20.GL_VERTEX_SHADER);
if (vertexShader == 0) {
Log.e("Load Program", "Vertex Shader Failed");
eglBase.detachCurrent();
return;
}
fragmentShader = loadShader(fragmentShaderString, GLES20.GL_FRAGMENT_SHADER);
if (fragmentShader == 0) {
Log.e("Load Program", "Fragment Shader Failed");
eglBase.detachCurrent();
return;
}
programId = GLES20.glCreateProgram();
GLES20.glAttachShader(programId, vertexShader);
GLES20.glAttachShader(programId, fragmentShader);
GLES20.glLinkProgram(programId);
GLES20.glGetProgramiv(programId, GLES20.GL_LINK_STATUS, link, 0);
if (link[0] <= 0) {
Log.d("Load Program", "Linking Failed");
eglBase.detachCurrent();
return;
}
glProgramId = programId;
GLES20.glUseProgram(glProgramId);
GLES20.glUniform1i(GLES20.glGetUniformLocation(glProgramId, "oes_tex"), 0);
GLES20.glEnableVertexAttribArray(GLES20.glGetAttribLocation(glProgramId, "in_pos"));
GLES20.glVertexAttribPointer(GLES20.glGetAttribLocation(glProgramId, "in_pos"), 2,
GLES20.GL_FLOAT, false, 0, FULL_RECTANGLE_BUF);
GLES20.glEnableVertexAttribArray(GLES20.glGetAttribLocation(glProgramId, "in_tc"));
GLES20.glVertexAttribPointer(GLES20.glGetAttribLocation(glProgramId, "in_tc"), 2,
GLES20.GL_FLOAT, false, 0, FULL_RECTANGLE_TEX_BUF);
GLES20.glDeleteShader(vertexShader);
GLES20.glDeleteShader(fragmentShader);
GlUtil.checkNoGLES2Error("ImageFilter.initGL");
eglBase.detachCurrent();
}
private int loadShader(final String strSource, final int iType) {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
int[] compiled = new int[1];
int iShader = GLES20.glCreateShader(iType);
GLES20.glShaderSource(iShader, strSource);
GLES20.glCompileShader(iShader);
GLES20.glGetShaderiv(iShader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e("Load Shader Failed", "Compilation\n" + GLES20.glGetShaderInfoLog(iShader));
return 0;
}
return iShader;
}
//init FBO
private void initFrameBuffer() {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
if (glFramebufferId == null) {
glFramebufferId = new int[1];
glFramebufferTextureId = new int[1];
eglBase.makeCurrent();
GLES20.glGenFramebuffers(1, glFramebufferId, 0);
GLES20.glGenTextures(1, glFramebufferTextureId, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glFramebufferTextureId[0]);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, frameWidth, frameHeight, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, glFramebufferId[0]);
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D, glFramebufferTextureId[0], 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
eglBase.detachCurrent();
}
}
private void reInitFrameBuffer() {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
if (glFramebufferId != null) {
eglBase.makeCurrent();
GLES20.glDeleteFramebuffers(1, glFramebufferId, 0);
GLES20.glDeleteTextures(1, glFramebufferTextureId, 0);
glFramebufferId = null;
glFramebufferTextureId = null;
eglBase.detachCurrent();
}
initFrameBuffer();
}
@Override
public void filterTextureFrame(final int textureId, final int frameWidth, final int frameHeight,
final float[] transformMatrix, final FilterCallback callback) {
filterHandler.post(new Runnable() {
@Override
public void run() {
textureFrameAvailableOnThread(textureId, frameWidth, frameHeight, transformMatrix,
callback);
}
});
}
private void textureFrameAvailableOnThread(int textureId, int width, int height,
float[] transformMatrix, FilterCallback callback) {
if (Thread.currentThread() != filterHandler.getLooper().getThread()) {
throw new RuntimeException("Wrong Thread");
}
if (frameWidth != width || frameHeight != height) {
frameWidth = width;
frameHeight = height;
reInitFrameBuffer();
}
if (!isInitialized) {
initGL(vertexShaderString, fragmentShaderString);
initFrameBuffer();
isInitialized = true;
}
if (glFramebufferId == null) {
return;
}
eglBase.makeCurrent();
GLES20.glViewport(0, 0, frameWidth, frameHeight);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, glFramebufferId[0]);
if (textureId != -1) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
}
GLES20.glUniformMatrix4fv(GLES20.glGetUniformLocation(glProgramId, "texMatrix"), 1, false,
transformMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
GLES20.glViewport(0, 0, frameWidth, frameHeight);
eglBase.detachCurrent();
//Finish processing texture, trigger callback.
callback.onComplete(glFramebufferTextureId[0], true);
}
}
| 40.979351 | 112 | 0.606464 |
d6f53ae0626ce2429558683f4f165d93d679bf82 | 3,133 | package app;
import java.util.concurrent.TimeUnit;
public class Time {
private long time;
private Clock clock, inspection, delay;
private Scramble scramble;
private boolean onInspection = false;
private boolean onDelay = false;
private int inspectionTime = 15;
public boolean pressed = false;
public int holdColor = 0;
public Time() {
this.clock = new Clock();
this.inspection = new Clock();
this.delay = new Clock();
this.time = clock.getTime();
this.scramble = new Scramble();
this.scramble.newScramble();
}
public Time(long time, Scramble scramble) {
this.time = time;
this.clock = new Clock(time);
this.scramble = scramble;
}
public void startInspection() {
// Starts the inspection time counting down from this.length
inspection.start();
onInspection = true;
}
public void stopInspection() {
// Stops the inspection time
inspection.stop();
onInspection = false;
}
public void startDelay() {
if (delay != null) {
delay.start();
onDelay = true;
}
}
public void stopDelay() {
if (delay != null) {
delay.stop();
onDelay = false;
}
}
public String getScramble() {
return scramble.toString();
}
public void reScramble() {
// Creates a new scramble sequence
scramble.newScramble();
}
public long getTime(Clock clock) {
// time variable is simultaneously updated
time = clock.getTime();
return this.time;
}
public long getTime() {
time = this.clock.getTime();
return this.time;
}
public String getTimeString() {
// Returns the string that is to be shown on screen
String outString;
if (!pressed && onDelay){
stopDelay();
if (delay != null) {
delay = new Clock();
}
holdColor = 0;
}
if (onInspection) {
// Returns an integer (String) between inspectionTime and 0
long millis = this.getTime(inspection);
if (pressed && !onDelay) {
startDelay();
holdColor = 1;
}
if (pressed && onDelay) {
if (getTime(delay) > 300) {
holdColor = 2;
}
}
long allSecs = TimeUnit.MILLISECONDS.toSeconds(millis);
outString = ""+(inspectionTime-allSecs);
if (millis > inspectionTime*1000
&& millis < inspectionTime*1000 + 2000) {
outString = "+2";
} else if (millis > inspectionTime*1000 + 2000){
outString = "DNF";
}
} else {
// Returns a time formatted as either
// s.cc ss.cc m:ss.cc mm:ss.cc
long millis = this.getTime(clock);
long allSecs = TimeUnit.MILLISECONDS.toSeconds(millis);
long mins = TimeUnit.MILLISECONDS.toMinutes(millis);
long secs = allSecs - TimeUnit.MINUTES.toSeconds(mins);
long restMillis = millis - TimeUnit.SECONDS.toMillis(allSecs);
long centis = restMillis / 10;
if (millis < 60000) {
outString = String.format("%d.%02d", secs, centis);
} else {
outString = String.format("%d:%02d.%02d", mins, secs, centis);
}
}
return outString;
}
public void startTime() {
// Starts the timer after inspection
clock.start();
delay = null;
inspection = null;
}
public void stopTime() {
// Stops the timer
clock.stop();
}
}
| 18.538462 | 66 | 0.644111 |
9ce6745dc8652a2e78bb43f68d69e21c0fad36de | 2,488 | /*
* Copyright 2014 Shazam Entertainment Limited
*
* 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.shazam.fork.summary;
import com.android.ddmlib.logcat.LogCatMessage;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shazam.fork.runtime.LogCatFilenameFactory;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import static com.shazam.fork.runtime.LogCatFilenameFactory.createLogCatFilenamePrefix;
public class JsonLogCatRetriever implements LogCatRetriever {
private final Gson gson;
private final File output;
public JsonLogCatRetriever(File output, Gson gson) {
this.output = output;
this.gson = gson;
}
@Override
public List<LogCatMessage> retrieveLogCat(String poolName, String serial, TestIdentifier testIdentifier) {
String filenamePrefix = createLogCatFilenamePrefix(poolName, serial, testIdentifier);
final PrefixFileFilter prefixFileFilter = new PrefixFileFilter(filenamePrefix);
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(LogCatFilenameFactory.JSON);
final AndFileFilter filter = new AndFileFilter(prefixFileFilter, suffixFileFilter);
File[] files = output.listFiles((FileFilter) filter);
if (files.length == 0) {
return new ArrayList<>();
}
File logcatJsonFile = files[0];
try {
FileReader fileReader = new FileReader(logcatJsonFile);
return gson.fromJson(fileReader, new TypeToken<List<LogCatMessage>>() {}.getType());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
} | 40.786885 | 118 | 0.745579 |
cb4b7df917e19e0df725800634d6dcf04aae7c30 | 6,122 | package com.app.app1.activities.user;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.app.app1.R;
import com.app.app1.activities.JogoActivity;
import com.app.app1.adapters.AdapterJogos;
import com.app.app1.config.ConfiguracaoFirebase;
import com.app.app1.helper.UsuarioFirebase;
import com.app.app1.model.Jogos;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class UsuarioLogadoActivity extends AppCompatActivity implements AdapterJogos.JogoListener {
private List<Jogos> listaDeJogosSalvos = new ArrayList<>();
private DatabaseReference jogosRef;
private FirebaseUser usuarioFirebase;
private AdapterJogos adapterJogos;
private RecyclerView rvJogosSalvosUser;
private ValueEventListener eventListener;
private TextView tvNomeUsuario, tvEmailUsuario;
Retrofit retrofit;
String baseUrl;
String token = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usuario_logado);
//referenciação
rvJogosSalvosUser = findViewById(R.id.rvJogosSalvosUser);
String idUsuario = UsuarioFirebase.getIdUsuario();
jogosRef = ConfiguracaoFirebase.getFirebaseDatabase().child("usuarios").child(idUsuario).child("listaDeJogos");
usuarioFirebase = UsuarioFirebase.getUsuarioAtual();
tvEmailUsuario = findViewById(R.id.tvEmailUsuario);
tvEmailUsuario.setText(usuarioFirebase.getEmail());
//btn back action bar
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
recuperarJogosSalvos();
recyclerJogosSalvos();
baseUrl = "https://fcm.googleapis.com/fcm/";
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
@Override
protected void onStop() {
super.onStop();
jogosRef.removeEventListener(eventListener);
}
public void recuperarJogosSalvos() {
eventListener = jogosRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) { //faz a leitura de forma assíncrona
listaDeJogosSalvos.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
listaDeJogosSalvos.add(ds.getValue(Jogos.class));
}
//(ordenar lista)
adapterJogos.notifyDataSetChanged();
Log.i("info", "onDataChange usuarioLogadoActivity");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.i("info", databaseError.getMessage());
}
});
}
public void recyclerJogosSalvos() {
adapterJogos = new AdapterJogos(listaDeJogosSalvos, this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
rvJogosSalvosUser.setLayoutManager(layoutManager);
rvJogosSalvosUser.setHasFixedSize(true);
rvJogosSalvosUser.setAdapter(adapterJogos);
}
public void deslogarUsuario(View view) {
FirebaseAuth usuarioAutenticado = ConfiguracaoFirebase.getFirebaseAutenticacao();
usuarioAutenticado.signOut();
Toast.makeText(UsuarioLogadoActivity.this, "usuário deslogado", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void jogoClick(int position) {
Jogos jogo = listaDeJogosSalvos.get(position);
Intent intent = new Intent(UsuarioLogadoActivity.this, JogoActivity.class);
intent.putExtra("jogo", jogo);
startActivity(intent);
}
//finalizar a activity ao pressionar btn back
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
/*public void enviarNot(View view) {
recuperarToken();
//monta objeto notificação
Notificacao notificacao = new Notificacao("titulo", "aqui é o corpo");
NotificacaoDados notificacaoDados = new NotificacaoDados(token, notificacao);
NotificacaoService service = retrofit.create(NotificacaoService.class);
Call<NotificacaoDados> chamada = service.enviarNotificacao(notificacaoDados);
chamada.enqueue(new Callback<NotificacaoDados>() {
@Override
public void onResponse(Call<NotificacaoDados> call, Response<NotificacaoDados> response) {
Log.i("infoNotificação", "" + response.code());
}
@Override
public void onFailure(Call<NotificacaoDados> call, Throwable t) {
}
});
}
public void recuperarToken() {
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
token = task.getResult().getToken();
Log.i("infoNotificação", "" + token);
}
});
}*/
}
| 36.011765 | 123 | 0.688337 |
e56955de6d5e16f1dfc21f13824def878f9170b6 | 974 | package cn.hutool.core.comparator;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Field;
/**
* Bean字段排序器<br>
* 参阅feilong-core中的PropertyComparator
*
* @param <T> 被比较的Bean
* @author Looly
*/
public class FieldComparator<T> extends BaseFieldComparator<T> {
private static final long serialVersionUID = 9157326766723846313L;
private final Field field;
/**
* 构造
*
* @param beanClass Bean类
* @param fieldName 字段名
*/
public FieldComparator(Class<T> beanClass, String fieldName) {
this.field = ClassUtil.getDeclaredField(beanClass, fieldName);
if (this.field == null) {
throw new IllegalArgumentException(StrUtil.format("Field [{}] not found in Class [{}]", fieldName, beanClass.getName()));
}
}
/**
* 构造
*
* @param field 字段
*/
public FieldComparator(Field field) {
this.field = field;
}
@Override
public int compare(T o1, T o2) {
return compareItem(o1, o2, this.field);
}
}
| 20.723404 | 124 | 0.701232 |
0e1e82a13360ac2dd6251f830ea6511ea653e736 | 782 | import java.util.ArrayList;
import java.util.Iterator;
class ProgressMonitor {
/**
* Return a snapshot of the ProgressSource list
*/
public ArrayList<ProgressSource> getProgressSources() {
ArrayList<ProgressSource> snapshot = new ArrayList<>();
try {
synchronized (progressSourceList) {
for (Iterator<ProgressSource> iter = progressSourceList.iterator(); iter.hasNext();) {
ProgressSource pi = iter.next();
// Clone ProgressSource and add to snapshot
snapshot.add((ProgressSource) pi.clone());
}
}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return snapshot;
}
private ArrayList<ProgressSource> progressSourceList = new ArrayList<ProgressSource>();
}
| 25.225806 | 103 | 0.694373 |
c54573764a5609b9a8f8320fd0de2d162c4652cb | 4,362 | package com.github.extermania.leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Temp {
class Solution {
List<Character> pos(char[][] board, int i, int j){
int[] arr = new int[9];
for(int n=0; n<9; n++) //check row
if(board[i][n]!='.') arr[board[i][n]-'1']++;
for(int n=0; n<9; n++) //check col
if(board[n][j]!='.') arr[board[n][j]-'1']++;
int nn = (i/3)*3; int mm=(j/3)*3;
for(int n=nn; n<nn+3; n++) //check cell
for(int m=mm; m<mm+3; m++)
if(board[n][m]!='.') arr[board[n][m]-'1']++;
List<Character> result = new ArrayList<>();
for(int n=0; n<9; n++)
if(arr[n]==0) result.add((char)(n+'1'));
return result;
}
boolean done(char[][] board){
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
if(board[i][j]=='.') return false;
return true;
}
char[][] copy(char[][] board){
char[][] a = new char[9][9];
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
a[i][j]=board[i][j];
return a;
}
boolean valid(char[][] board, int i, int j){
int[] arr = new int[9];
for(int n=0; n<9; n++) //check row
if(board[i][n]!='.') {
arr[board[i][n]-'1']++;
if(board[i][n]-'1'>1) return false;
}
for(int n=0; n<9; n++) //check col
if(board[n][j]!='.') {
arr[board[n][j]-'1']++;
if(board[n][j]-'1'>1) return false;
}
int nn = (i/3)*3; int mm=(j/3)*3;
for(int n=nn; n<nn+3; n++) //check cell
for(int m=mm; m<mm+3; m++)
if(board[n][m]!='.') {
arr[board[n][m]-'1']++;
if(board[n][m]-'1'>1) return false;
}
return true;
}
boolean solveSudoku0(char[][] board) {
char[][] a = copy(board);
Map<Integer, List<Character>> pos = null;
int cnt = 1;
while(cnt>0){
pos=new TreeMap<>();
cnt = 0;
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(a[i][j]=='.'){
List<Character> list = pos(board, i, j);
pos.put(i*10+j, list);
//System.out.println(i+" "+j+":"+list);
if(list.size()==1){
cnt++;
a[i][j]=list.get(0);
}
}
}
}
}
if(done(a)) return true;
for(Map.Entry<Integer, List<Character>> e:pos.entrySet()){
Integer key = e.getKey();
List<Character> list = e.getValue();
int i = key/10; int j = key%10;
for(Character tr:list){
a[i][j]=tr;
if(valid(a, i, j)){
if(solveSudoku0(a)) return true;
}
a[i][j]='.';
}
}
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
System.out.print(board[i][j]+" ");
}
System.out.println();
}
System.out.println(pos);
return false;
}
public void solveSudoku(char[][] board) {
int cnt = 1;
while(cnt>0){
cnt = 0;
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(board[i][j]=='.'){
List<Character> list = pos(board, i, j);
if(list.size()==1){
cnt++;
board[i][j]=list.get(0);
}
}
}
}
}
if(done(board)) return;
solveSudoku0(board);
}
}
}
| 31.608696 | 68 | 0.340899 |
3b7320bae74c36d8e10d5cbab89380a11ba33145 | 8,189 | package de.metas.event.log;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import de.metas.cache.CCache;
import de.metas.common.util.time.SystemTime;
import de.metas.error.AdIssueId;
import de.metas.event.model.I_AD_EventLog;
import de.metas.event.model.I_AD_EventLog_Entry;
import de.metas.logging.LogManager;
import de.metas.util.GuavaCollectors;
import de.metas.util.NumberUtils;
import de.metas.util.Services;
import de.metas.util.StringUtils;
import lombok.NonNull;
import org.adempiere.ad.dao.IQueryBL;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.exceptions.DBException;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.slf4j.Logger;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/*
* #%L
* de.metas.async
* %%
* Copyright (C) 2020 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
/**
* Blatant ripoff of IWorkpackageLogsRepository's implementation.
*/
@Repository
public class EventLogsRepository
{
private static final Logger logger = LogManager.getLogger(EventLogsRepository.class);
private final CCache<UUID, EventLogId> uuid2eventLogId = CCache.newLRUCache(
I_AD_EventLog.Table_Name + "#by#" + I_AD_EventLog.COLUMNNAME_Event_UUID,
500,
15 /* expireMinutes=15 because it's unlikely that event log records need to be in cache for longer periods of time */);
public void saveLogs(@NonNull final Collection<EventLogEntry> logEntries)
{
if (logEntries.isEmpty())
{
return;
}
// warm up UUID->EventLogId cache
final ImmutableSet<UUID> uuids = logEntries.stream().map(EventLogEntry::getUuid).collect(ImmutableSet.toImmutableSet());
getEventLogIdsUsingCacheOutOfTrx(uuids);
final Set<EventLogId> eventLogsWithError = insertEventLogIds(logEntries);
// Update EventLog's error flag from entries
updateUpdateEventLogErrorFlagFromEntries(eventLogsWithError);
}
@NonNull
private Set<EventLogId> insertEventLogIds(@NonNull final Collection<EventLogEntry> logEntries)
{
final Set<EventLogId> eventLogsWithError = new HashSet<>();
final String sql = "INSERT INTO " + I_AD_EventLog_Entry.Table_Name + "("
+ I_AD_EventLog_Entry.COLUMNNAME_AD_Client_ID + "," // 1
+ I_AD_EventLog_Entry.COLUMNNAME_AD_Org_ID + "," // 2
+ I_AD_EventLog_Entry.COLUMNNAME_AD_EventLog_ID + "," // 3
+ I_AD_EventLog_Entry.COLUMNNAME_AD_EventLog_Entry_ID + "," // 4
+ I_AD_EventLog_Entry.COLUMNNAME_AD_Issue_ID + "," // 5
+ I_AD_EventLog_Entry.COLUMNNAME_Created + "," // 6
+ I_AD_EventLog_Entry.COLUMNNAME_CreatedBy + "," // 7
+ I_AD_EventLog_Entry.COLUMNNAME_IsActive + "," // 8
+ I_AD_EventLog_Entry.COLUMNNAME_IsError + "," // 9
+ I_AD_EventLog_Entry.COLUMNNAME_Processed + "," // 10
+ I_AD_EventLog_Entry.COLUMNNAME_MsgText + "," // 11
+ I_AD_EventLog_Entry.COLUMNNAME_Classname + "," // 12
+ I_AD_EventLog_Entry.COLUMNNAME_Updated + "," // 13
+ I_AD_EventLog_Entry.COLUMNNAME_UpdatedBy // 14
+ ")"
+ " VALUES ("
+ "?," // 1 - AD_Client_ID
+ "?," // 2 - AD_Org_ID
+ "?," // 3 - AD_EventLog_ID
+ DB.TO_TABLESEQUENCE_NEXTVAL(I_AD_EventLog_Entry.Table_Name) + "," // 4 - AD_EventLog_Entry_ID
+ "?," // 5 - AD_Issue_ID
+ "?," // 6 - Created
+ "?," // 7 - CreatedBy
+ "'Y'," // 8 - IsActive
+ "?," // 9 - IsError
+ "?," // 10 - Processed
+ "?," // 11 - MsgText
+ "?," // 12 - Classname
+ "?," // 13 - Updated
+ "?" // 14 - UpdatedBy
+ ")";
PreparedStatement pstmt = null;
try
{
// NOTE: always create the logs out of transaction because we want them to be persisted even if the workpackage processing fails
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
final Timestamp timestamp = SystemTime.asTimestamp();
final int ad_user_id = Env.getAD_User_ID();
for (final EventLogEntry logEntry : logEntries)
{
final EventLogId eventLogId = getEventLogIdUsingCacheOutOfTrx(logEntry.getUuid());
final Object[] params = {
logEntry.getClientId(), // 1 - AD_Client_ID
logEntry.getOrgId(), // 2 - AD_Org_ID
eventLogId.getRepoId(), // 3 - AD_EventLog_ID
// + DB.TO_TABLESEQUENCE_NEXTVAL(I_AD_EventLog_Entry.Table_Name) + "," // 4 - AD_EventLog_Entry_ID
AdIssueId.toRepoId(logEntry.getAdIssueId()), // 5 - AD_Issue_ID
timestamp, // 6 - Created
ad_user_id, // 7 - CreatedBy
// + "'Y'," // 8 - IsActive
StringUtils.ofBoolean(logEntry.isError(), "N"), // 9 - IsError
StringUtils.ofBoolean(logEntry.isProcessed(), "N"), // 10 - Processed
logEntry.getMessage(), // 11 - MsgText
logEntry.getEventHandlerClassName(), // 12 - Classname
timestamp, // 9 - Updated
ad_user_id // 10 - UpdatedBy
};
DB.setParameters(pstmt, params);
pstmt.addBatch();
if (logEntry.isError())
{
eventLogsWithError.add(eventLogId);
}
}
pstmt.executeBatch();
}
catch (final SQLException ex)
{
throw new DBException(ex, sql);
}
finally
{
DB.close(pstmt);
}
return eventLogsWithError;
}
private EventLogId getEventLogIdUsingCacheOutOfTrx(@NonNull final UUID uuid)
{
final Collection<EventLogId> eventLogIds = getEventLogIdsUsingCacheOutOfTrx(ImmutableSet.of(uuid));
if (eventLogIds.isEmpty())
{
throw new AdempiereException("No EventLog found for " + uuid);
}
else
{
if (eventLogIds.size() > 1) // shall not happen
{
logger.warn("More than one EventLogId found for {}: {}. Returning first one.", uuid, eventLogIds);
}
return eventLogIds.iterator().next();
}
}
private Collection<EventLogId> getEventLogIdsUsingCacheOutOfTrx(@NonNull final Collection<UUID> uuids)
{
return uuid2eventLogId.getAllOrLoad(uuids, this::retrieveAllRecordIdOutOfTrx);
}
private ImmutableMap<UUID, EventLogId> retrieveAllRecordIdOutOfTrx(@NonNull final Collection<UUID> uuids)
{
if (uuids.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableSet<String> uuidStrs = uuids.stream().map(UUID::toString).collect(ImmutableSet.toImmutableSet());
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_EventLog.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_AD_EventLog.COLUMN_Event_UUID, uuidStrs)
.orderBy(I_AD_EventLog.COLUMN_AD_EventLog_ID) // just to have a predictable order
.create()
.listColumns(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID, I_AD_EventLog.COLUMNNAME_Event_UUID)
.stream()
.map(map -> {
final int eventLogRepoId = NumberUtils.asInt(map.get(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID), -1);
final EventLogId eventLogId = EventLogId.ofRepoId(eventLogRepoId);
final UUID uuid = UUID.fromString(map.get(I_AD_EventLog.COLUMNNAME_Event_UUID).toString());
return GuavaCollectors.entry(uuid, eventLogId);
})
.collect(GuavaCollectors.toImmutableMap());
}
private void updateUpdateEventLogErrorFlagFromEntries(@NonNull final Set<EventLogId> eventLogsWithError)
{
if (eventLogsWithError.isEmpty())
{
return;
}
Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_EventLog.class)
.addInArrayFilter(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID, eventLogsWithError)
.create()
.updateDirectly()
.addSetColumnValue(I_AD_EventLog.COLUMNNAME_IsError, true)
.execute();
}
}
| 34.263598 | 131 | 0.718525 |
2f85fa753505960c73793fd1760f67b294310cfe | 2,438 | /*
* Copyright (c) 2020, 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.connector.connection;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileSystemOptions;
import org.wso2.carbon.connector.exception.FileServerConnectionException;
import org.wso2.carbon.connector.pojo.ConnectionConfiguration;
import org.wso2.carbon.connector.utils.Const;
/**
* Protocol specific file system setup strategy.
*/
public interface ProtocolBasedFileSystemSetup {
String setupFileSystemHandler(FileSystemOptions fso, ConnectionConfiguration fsConfig)
throws FileServerConnectionException;
/**
* Constructs VFS url based on configurations.
*
* @param fsConfig Input configs
* @return Constructed url
*/
default String constructVfsUrl(ConnectionConfiguration fsConfig) {
StringBuilder sb = new StringBuilder();
if (fsConfig.getRemoteServerConfig() != null) {
String username = fsConfig.getRemoteServerConfig().getUsername();
String password = fsConfig.getRemoteServerConfig().getPassword();
String host = fsConfig.getRemoteServerConfig().getHost();
int port = fsConfig.getRemoteServerConfig().getPort();
if (StringUtils.isNotEmpty(username)) {
sb.append(username);
if (StringUtils.isNotEmpty(password)) {
sb.append(":").append(password);
}
sb.append("@");
}
sb.append(host).append(":").append(port);
}
if (StringUtils.isNotEmpty(fsConfig.getWorkingDir())) {
sb.append(Const.FILE_SEPARATOR).append(fsConfig.getWorkingDir());
}
return sb.toString();
}
}
| 38.698413 | 91 | 0.662838 |
bb8de8c4d7c394d65a1be06a823578d9560d6dc0 | 952 | package com.frontbackend.thymeleaf.bootstrap.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.frontbackend.thymeleaf.bootstrap.model.PriceRange;
import com.frontbackend.thymeleaf.bootstrap.service.ProductService;
@Controller
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public String filterProducts(PriceRange priceRange, Model model) {
model.addAttribute("products", productService.filterProducts(priceRange.getMin(), priceRange.getMax()));
return "products";
}
}
| 32.827586 | 112 | 0.795168 |
6cb12ae943d99d539118915f957ae83603fda86a | 4,471 | package io.blockchainetl.anomaloustransactions.domain.bitcoin;
import com.google.common.base.Objects;
import org.apache.avro.reflect.Nullable;
import org.apache.beam.sdk.coders.AvroCoder;
import org.apache.beam.sdk.coders.DefaultCoder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import java.math.BigInteger;
import java.util.List;
@DefaultCoder(AvroCoder.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransactionInput {
@Nullable
private Long index;
@Nullable
@JsonProperty("spent_transaction_hash")
private String spentTransactionHash;
@Nullable
@JsonProperty("spent_output_index")
private Long spentOutputIndex;
@Nullable
@JsonProperty("script_asm")
private String scriptAsm;
@Nullable
@JsonProperty("script_hex")
private String scriptHex;
@Nullable
private Long sequence;
@Nullable
@JsonProperty("required_signatures")
private Long requiredSignatures;
@Nullable
private String type;
@Nullable
private List<String> addresses;
@Nullable
private BigInteger value;
public Long getIndex() {
return index;
}
public void setIndex(Long index) {
this.index = index;
}
public String getSpentTransactionHash() {
return spentTransactionHash;
}
public void setSpentTransactionHash(String spentTransactionHash) {
this.spentTransactionHash = spentTransactionHash;
}
public Long getSpentOutputIndex() {
return spentOutputIndex;
}
public void setSpentOutputIndex(Long spentOutputIndex) {
this.spentOutputIndex = spentOutputIndex;
}
public String getScriptAsm() {
return scriptAsm;
}
public void setScriptAsm(String scriptAsm) {
this.scriptAsm = scriptAsm;
}
public String getScriptHex() {
return scriptHex;
}
public void setScriptHex(String scriptHex) {
this.scriptHex = scriptHex;
}
public Long getSequence() {
return sequence;
}
public void setSequence(Long sequence) {
this.sequence = sequence;
}
public Long getRequiredSignatures() {
return requiredSignatures;
}
public void setRequiredSignatures(Long requiredSignatures) {
this.requiredSignatures = requiredSignatures;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public BigInteger getValue() {
return value;
}
public void setValue(BigInteger value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TransactionInput that = (TransactionInput) o;
return Objects.equal(index, that.index) &&
Objects.equal(spentTransactionHash, that.spentTransactionHash) &&
Objects.equal(spentOutputIndex, that.spentOutputIndex) &&
Objects.equal(scriptAsm, that.scriptAsm) &&
Objects.equal(scriptHex, that.scriptHex) &&
Objects.equal(sequence, that.sequence) &&
Objects.equal(requiredSignatures, that.requiredSignatures) &&
Objects.equal(type, that.type) &&
Objects.equal(addresses, that.addresses) &&
Objects.equal(value, that.value);
}
@Override
public int hashCode() {
return Objects.hashCode(index, spentTransactionHash, spentOutputIndex, scriptAsm, scriptHex, sequence,
requiredSignatures, type, addresses, value);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("index", index)
.add("spentTransactionHash", spentTransactionHash)
.add("spentOutputIndex", spentOutputIndex)
.add("scriptAsm", scriptAsm)
.add("scriptHex", scriptHex)
.add("sequence", sequence)
.add("requiredSignatures", requiredSignatures)
.add("type", type)
.add("addresses", addresses)
.add("value", value)
.toString();
}
}
| 25.548571 | 110 | 0.645046 |
881ba53f884cbeb9c631f4b77a07f3f7d7786bd6 | 4,975 | /*
* Copyright (C) 2009-2014 Steve Rowe <[email protected]>
* Copyright (C) 2017-2021 Google, LLC.
*
* License: https://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.jflex.testcase.unicode.unicode_3_0;
import static de.jflex.util.javac.JavaPackageUtils.getPathForClass;
import de.jflex.testing.unicodedata.AbstractEnumeratedPropertyDefinedScanner;
import de.jflex.testing.unicodedata.TestingUnicodeProperties;
import de.jflex.testing.unicodedata.UnicodeDataScanners;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Function;
import javax.annotation.Generated;
import org.junit.Test;
// Generate from UnicodeCompatibilityPropertiesTest.java.vm
/**
* Test for compatibility property, derived from UnicodeData(-X.X.X).txt, PropList(-X|-X.X.X).txt
* and/or DerivedCoreProperties(-X.X.X).txt.
*/
@Generated(
"de.jflex.migration.unicodedatatest.testcompat.UnicodeCompatibilityPropertiesTestGenerator")
public class UnicodeCompatibilityPropertiesTest_3_0 {
private static final String TEST_DIR =
getPathForClass(UnicodeCompatibilityPropertiesTest_3_0.class);
/** Test the character class syntax of the Unicode 3.0 'alnum' compatibility property. */
@Test
public void alnum() throws Exception {
checkCompatibility(
"alnum",
UnicodeCompatibilityProperties_alnum_3_0.class,
UnicodeCompatibilityProperties_alnum_3_0::new,
UnicodeCompatibilityProperties_alnum_3_0.YYEOF);
}
/** Test the character class syntax of the Unicode 3.0 'blank' compatibility property. */
@Test
public void blank() throws Exception {
checkCompatibility(
"blank",
UnicodeCompatibilityProperties_blank_3_0.class,
UnicodeCompatibilityProperties_blank_3_0::new,
UnicodeCompatibilityProperties_blank_3_0.YYEOF);
}
/** Test the character class syntax of the Unicode 3.0 'graph' compatibility property. */
@Test
public void graph() throws Exception {
checkCompatibility(
"graph",
UnicodeCompatibilityProperties_graph_3_0.class,
UnicodeCompatibilityProperties_graph_3_0::new,
UnicodeCompatibilityProperties_graph_3_0.YYEOF);
}
/** Test the character class syntax of the Unicode 3.0 'print' compatibility property. */
@Test
public void print() throws Exception {
checkCompatibility(
"print",
UnicodeCompatibilityProperties_print_3_0.class,
UnicodeCompatibilityProperties_print_3_0::new,
UnicodeCompatibilityProperties_print_3_0.YYEOF);
}
/** Test the character class syntax of the Unicode 3.0 'xdigit' compatibility property. */
@Test
public void xdigit() throws Exception {
checkCompatibility(
"xdigit",
UnicodeCompatibilityProperties_xdigit_3_0.class,
UnicodeCompatibilityProperties_xdigit_3_0::new,
UnicodeCompatibilityProperties_xdigit_3_0.YYEOF);
}
private static <T extends AbstractEnumeratedPropertyDefinedScanner<Boolean>>
void checkCompatibility(
String propName, Class<T> scannerClass, Function<Reader, T> constructorRef, int eof)
throws IOException {
Path expectedFile =
Paths.get("javatests")
.resolve(TEST_DIR)
.resolve("UnicodeCompatibilityProperties_" + propName + "_3_0.output");
TestingUnicodeProperties.checkProperty(
constructorRef, eof, expectedFile, UnicodeDataScanners.Dataset.ALL);
}
}
| 42.887931 | 103 | 0.757588 |
ebedad890d341e254eacd97af508867890879af3 | 1,582 | /*
* Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.pipeline.entity.model;
import lombok.Value;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Model analysis result.
*/
@Value
public class AnalysisResult {
/**
* A set of named in-memory CSV files.
*
* Map keys are the same that were specified in {@link AbstractStepParameters#outputs}.
*
* For example, it can represent the following files content:
*
* data_1.csv
* column1,column2
* value11,value12
*
* data_2.csv
* column1,column2,column3
* value11,value12,value13
* value21,value22,value23
* value31,value32,value33
*
* As a single map:
*
* {
* "VAL1": [Row1, Row2],
* "VAL2": [Row1, Row2, Row3]
* }
*/
private final Map<String, List<Row>> outputs;
public static AnalysisResult empty() {
return new AnalysisResult(Collections.emptyMap());
}
}
| 25.934426 | 91 | 0.659292 |
35b30c266cb34f416aa49214d459bbd15ec32915 | 773 | /*
* KIELER - Kiel Integrated Environment for Layout Eclipse RichClient
*
* http://www.informatik.uni-kiel.de/rtsys/kieler/
*
* Copyright 2010 by
* + Christian-Albrechts-University of Kiel
* + Department of Computer Science
* + Real-Time and Embedded Systems Group
*
* This code is provided under the terms of the Eclipse Public License (EPL).
* See the file epl-v10.html for the license text.
*/
package de.cau.cs.kieler.klay.layered.properties;
/**
* Definition of port types.
*
* @author msp
* @kieler.design 2011-03-14 reviewed by cmot, cds
* @kieler.rating proposed yellow by msp
*/
public enum PortType {
/** undefined port type. */
UNDEFINED,
/** input port type. */
INPUT,
/** output port type. */
OUTPUT;
}
| 23.424242 | 77 | 0.670116 |
1e7e4bafd7282504d0d2e7411b7e67d880d2cdd3 | 3,480 | /*******************************************************************************
* Copyright (c) 2021 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* 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.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package tlc2.value.impl;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import tla2sany.semantic.ExprOrOpArgNode;
import tla2sany.semantic.OpDefNode;
import tlc2.output.EC;
import tlc2.tool.TLCState;
import tlc2.tool.coverage.CostModel;
import tlc2.tool.impl.Tool;
import tlc2.util.Context;
import util.Assert;
public class PriorityEvaluatingValue extends EvaluatingValue {
private static final Comparator<EvaluatingValue> comparator = new Comparator<EvaluatingValue>() {
@Override
public int compare(EvaluatingValue o1, EvaluatingValue o2) {
return Integer.compare(o1.priority, o2.priority);
}
};
private final ArrayList<EvaluatingValue> handles = new ArrayList<>();
public PriorityEvaluatingValue(final Method md, final int minLevel, final int priority, final OpDefNode opDef,
final EvaluatingValue ev) {
super(md, minLevel, priority, opDef);
if (ev.opDef != this.opDef || ev.minLevel != this.minLevel) {
// TODO Specific error code.
Assert.fail(EC.GENERAL);
}
this.handles.add(this);
this.handles.add(ev);
this.handles.sort(comparator);
}
public void add(EvaluatingValue ev) {
if (ev.opDef != this.opDef || ev.minLevel != this.minLevel) {
// TODO Specific error code.
Assert.fail(EC.GENERAL);
}
this.handles.add(ev);
this.handles.sort(comparator);
}
@Override
public Value eval(final Tool tool, final ExprOrOpArgNode[] args, final Context c, final TLCState s0,
final TLCState s1, final int control, final CostModel cm) {
try {
for (EvaluatingValue ev : handles) {
final Object invoke = ev.mh.invoke(tool, args, c, s0, s1, control, cm);
if (invoke != null) {
return (Value) invoke;
}
}
// Fall back to pure (TLA+) operator definition if the Java module overrides
// returned null.
return tool.eval(opDef.getBody(), c, s0, s1, control, cm);
} catch (Throwable e) {
Assert.fail(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[] { this.md.toString(), e.getMessage() });
return null; // make compiler happy
}
}
}
| 37.419355 | 111 | 0.701724 |
5381c6d0dad2c4a04eb91a4d1fa6e7a32dbeeca8 | 3,807 | package net.sourceforge.ganttproject.export;
import org.apache.fop.fonts.FontFileReader;
import org.apache.fop.fonts.TTFFile;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* @author bard
* Date: 07.01.2004
*/
public class JDKFontLocator {
private FontMetricsStorage myFontMetricsStorage = new FontMetricsStorage();
public FontRecord[] getFontRecords() {
String javaHome = System.getProperty("java.home");
File fontDirectory = new File(javaHome+"/lib/fonts");
//TTFReader ttfReader = new TTFReader();
File[] children = fontDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".ttf");
}
});
if (children==null) {
children = new File[0];
}
ArrayList result = new ArrayList(children.length);
for (int i=0; i<children.length; i++) {
try {
FontRecord record = new FontRecord(children[i], myFontMetricsStorage);
if (record.getMetricsLocation()!=null) {
populateWithTriplets(record);
result.add(record);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
return (FontRecord[]) result.toArray(new FontRecord[0]);
}
private void populateWithTriplets(FontRecord record) {
TTFFileExt ttfFile = record.getTTFFile();
boolean isItalic = ttfFile.isItalic();
boolean isBold = ttfFile.isBold();
String name = ttfFile.getFamilyName();
FontTriplet triplet = new FontTriplet(name, isItalic, isBold);
record.addTriplet(triplet);
if (name.toLowerCase().indexOf("typewriter")>=0) {
FontTriplet monospaceTriplet = new FontTriplet("monospace", isItalic, isBold);
record.addTriplet(monospaceTriplet);
} else if (name.toLowerCase().indexOf("sans")>=0) {
FontTriplet sansTriplet = new FontTriplet("sans-serif", isItalic, isBold);
record.addTriplet(sansTriplet);
}
else {
FontTriplet serifTriplet = new FontTriplet("serif", isItalic, isBold);
record.addTriplet(serifTriplet);
}
}
}
class TTFFileExt extends TTFFile {
private final File myFile;
private Font myAwtFont;
TTFFileExt(File file) throws IOException {
if (!file.exists()) {
throw new RuntimeException("File="+file+" does not exist");
}
System.err.println("[TTFileExt] <ctor> file="+file.getAbsolutePath());
myFile = file;
FontFileReader reader = new FontFileReader(file.getCanonicalPath());
readFont(reader);
}
public boolean isItalic() {
return Integer.parseInt(getItalicAngle())>>16 !=0;
}
public boolean isBold() {
return getAwtFont().isBold();
}
public File getFile() {
return myFile;
}
private Font getAwtFont() {
if (myAwtFont==null) {
try {
myAwtFont = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(getFile()));
}
catch (FontFormatException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
}
return myAwtFont;
}
}
| 32.262712 | 103 | 0.596795 |
758656c98eeb6c8fbc3a90a62d51af9f52ec2bd2 | 264 | package org.nutz.castor;
public enum AlipayNotifyType {
StatusSync("trade_status_sync");
private String state;
private AlipayNotifyType(String s) {
state = s;
}
@Override
public String toString() {
return state;
}
}
| 15.529412 | 40 | 0.628788 |
77bf1c7f53f31d17a9d9de4baa7e5bb10ea2da1f | 318 | package com.synopsys.integration.jira.oauth;
import com.google.api.client.auth.oauth.OAuthGetAccessToken;
public class JiraOAuthGetAccessToken extends OAuthGetAccessToken {
public JiraOAuthGetAccessToken(String accessTokenRequestUrl) {
super(accessTokenRequestUrl);
this.usePost = true;
}
}
| 26.5 | 66 | 0.77673 |
26025c6f0f97469f9ad93b644090f09c73937885 | 3,600 | package de.dfki.nlp.loader;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import de.dfki.nlp.config.AnnotatorConfig;
import de.dfki.nlp.domain.IdList;
import de.dfki.nlp.domain.ParsedInputText;
import de.dfki.nlp.io.RetryHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Optional;
@Slf4j
@Component
public class PMCDocumentFetcher extends AbstractDocumentFetcher {
private final AnnotatorConfig annotatorConfig;
private final RetryHandler retryHandler;
private final XPathFactory xpathFactory = XPathFactory.newInstance();
private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
public PMCDocumentFetcher(AnnotatorConfig annotatorConfig, RetryHandler retryHandler) {
this.annotatorConfig = annotatorConfig;
this.retryHandler = retryHandler;
}
@Override
List<ParsedInputText> load(IdList idList) {
// load multiple pmc documents at once
String listOfIds = Joiner.on(",").join(idList.getIds());
String pmc = retryHandler.retryableGet(
annotatorConfig.pmc.url,
String.class, listOfIds);
List<ParsedInputText> res = Lists.newArrayList();
if (StringUtils.isEmpty(pmc)) return res;
InputSource source = new InputSource(new StringReader(pmc));
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDocument = db.parse(source);
XPath xpath = xpathFactory.newXPath();
// loop article
NodeList result = (NodeList) xpath.evaluate("/pmc-articleset/article", xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < result.getLength(); i++) {
String title = xpath.evaluate("front/article-meta/title-group/article-title", result.item(i));
String abstractT = xpath.evaluate("front/article-meta/abstract[not(@*)]", result.item(i));
title = StringUtils.defaultIfEmpty(StringUtils.trim(title), null);
abstractT = StringUtils.defaultIfEmpty(StringUtils.trim(abstractT), null);
final String id = xpath.evaluate("front/article-meta/article-id[@pub-id-type='pmc']", result.item(i));
// match id with incoming
Optional<String> matchedID = idList.getIds().stream().filter(givenId -> StringUtils.contains(givenId, id)).findFirst();
if (!matchedID.isPresent()) {
log.error("Did not find a matching ID {} in {}", id, idList.getIds().get(i));
}
res.add(new ParsedInputText(matchedID.orElse(id), title, abstractT, null));
}
//parsedInputText = new ParsedInputText(document.getDocument_id(), title, abstractT, null);
} catch (ParserConfigurationException | IOException | XPathExpressionException | SAXException e) {
log.error("Error parsing pmc results", e);
}
return res;
}
}
| 37.113402 | 135 | 0.689167 |
2e4ecc6513a27d8011724f30221a93bc9755325e | 602 | package net.emaze.dysfunctional.dispatching.actions;
import java.util.function.BiConsumer;
/**
* A null binary functor with no return value effectively doing nothing. Much
* better than {@literal Noop<T>}.
*
* @param <T1> the former type parameter
* @param <T2> the latter type parameter
* @author rferranti
*/
public class BinaryNoop<T1, T2> implements BiConsumer<T1, T2> {
/**
* Does nothing, ignoring parameters.
*
* @param former the first parameter
* @param latter the second parameter
*/
@Override
public void accept(T1 former, T2 latter) {
}
}
| 24.08 | 77 | 0.681063 |
ffe87d391c56e3af4e8efbcdab954f809fa113e6 | 9,474 | package com.tw.go.authentication;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.IOUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
@Extension
public class SampleAuthenticationPluginImpl implements GoPlugin {
private static Logger LOGGER = Logger.getLoggerFor(SampleAuthenticationPluginImpl.class);
public static final String PLUGIN_ID = "sample.authenticator";
public static final String EXTENSION_NAME = "authentication";
private static final List<String> goSupportedVersions = asList("1.0");
public static final String PLUGIN_CONFIGURATION = "go.authentication.plugin-configuration";
public static final String SEARCH_USER = "go.authentication.search-user";
public static final String AUTHENTICATE_USER = "go.authentication.authenticate-user";
public static final String WEB_REQUEST_INDEX = "index";
public static final String WEB_REQUEST_AUTHENTICATE = "authenticate";
public static final int SUCCESS_RESPONSE_CODE = 200;
public static final int REDIRECT_RESPONSE_CODE = 302;
public static final int INTERNAL_ERROR_RESPONSE_CODE = 500;
private GoApplicationAccessor goApplicationAccessor;
@Override
public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
this.goApplicationAccessor = goApplicationAccessor;
}
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) {
String requestName = goPluginApiRequest.requestName();
if (requestName.equals(PLUGIN_CONFIGURATION)) {
return handlePluginConfigurationRequest();
} else if (requestName.equals(SEARCH_USER)) {
return handleSearchUserRequest(goPluginApiRequest);
} else if (requestName.equals(AUTHENTICATE_USER)) {
return handleAuthenticateUserRequest(goPluginApiRequest);
} else if (requestName.equals(WEB_REQUEST_INDEX)) {
return handleSetupLoginWebRequest(goPluginApiRequest);
} else if (requestName.equals(WEB_REQUEST_AUTHENTICATE)) {
return handleAuthenticateWebRequest(goPluginApiRequest);
}
return renderResponse(404, null, null);
}
@Override
public GoPluginIdentifier pluginIdentifier() {
return getGoPluginIdentifier();
}
private GoPluginApiResponse handlePluginConfigurationRequest() {
Map<String, Object> configuration = new HashMap<String, Object>();
configuration.put("display-name", "Sample");
configuration.put("display-image-url", "http://icons.iconarchive.com/icons/saki/snowish/32/Authentication-Lock-icon.png");
configuration.put("supports-web-based-authentication", true);
configuration.put("supports-password-based-authentication", true);
return renderResponse(SUCCESS_RESPONSE_CODE, null, JSONUtils.toJSON(configuration));
}
private GoPluginApiResponse handleSearchUserRequest(GoPluginApiRequest goPluginApiRequest) {
Map<String, String> requestBodyMap = (Map<String, String>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());
String searchTerm = requestBodyMap.get("search-term");
List<Map> searchResults = new ArrayList<Map>();
if (searchTerm.equalsIgnoreCase("t") || searchTerm.equalsIgnoreCase("te") || searchTerm.equalsIgnoreCase("tes") || searchTerm.equalsIgnoreCase("test")) {
searchResults.add(getUserJSON("test", "display name", "[email protected]"));
}
return renderResponse(SUCCESS_RESPONSE_CODE, null, JSONUtils.toJSON(searchResults));
}
private GoPluginApiResponse handleAuthenticateUserRequest(GoPluginApiRequest goPluginApiRequest) {
Map<String, Object> requestBodyMap = (Map<String, Object>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());
String username = (String) requestBodyMap.get("username");
String password = (String) requestBodyMap.get("password");
if (username.equals("test") && password.equals("test")) {
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("user", getUserJSON("test", "display name", ""));
return renderResponse(SUCCESS_RESPONSE_CODE, null, JSONUtils.toJSON(userMap));
} else {
return renderResponse(SUCCESS_RESPONSE_CODE, null, null);
}
}
private GoPluginApiResponse handleSetupLoginWebRequest(GoPluginApiRequest goPluginApiRequest) {
try {
String responseBody = getFileContents("/views/login.html");
return renderResponse(SUCCESS_RESPONSE_CODE, null, responseBody);
} catch (Exception e) {
LOGGER.error("Error occurred while Login setup.", e);
return renderResponse(INTERNAL_ERROR_RESPONSE_CODE, null, null);
}
}
private GoPluginApiResponse handleAuthenticateWebRequest(final GoPluginApiRequest goPluginApiRequest) {
try {
String verificationCode = goPluginApiRequest.requestParameters().get("verification_code");
if (verificationCode == null || verificationCode.trim().isEmpty() || !verificationCode.equals("123456")) {
return renderRedirectResponse(getServerBaseURL() + "/go/auth/login?login_error=1");
}
String displayName = "test";
String fullName = "display name";
String emailId = "";
emailId = emailId == null ? emailId : emailId.toLowerCase().trim();
authenticateUser(displayName, fullName, emailId);
return renderRedirectResponse(getServerBaseURL());
} catch (Exception e) {
LOGGER.error("Error occurred while Login authenticate.", e);
return renderResponse(INTERNAL_ERROR_RESPONSE_CODE, null, null);
}
}
private GoPluginApiResponse renderRedirectResponse(String redirectURL) {
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Location", redirectURL);
return renderResponse(REDIRECT_RESPONSE_CODE, responseHeaders, null);
}
private void authenticateUser(String displayName, String fullName, String emailId) {
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("user", getUserJSON(displayName, fullName, emailId));
GoApiRequest authenticateUserRequest = createGoApiRequest("go.processor.authentication.authenticate-user", JSONUtils.toJSON(userMap));
GoApiResponse authenticateUserResponse = goApplicationAccessor.submit(authenticateUserRequest);
// handle error
}
// TODO: this needs to be dynamic (system property)
private String getServerBaseURL() {
return "http://" + "localhost:8153";
}
private String getFileContents(String filePath) {
try {
return IOUtils.toString(getClass().getResource(filePath));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Map<String, String> getUserJSON(String username, String displayName, String emailId) {
Map<String, String> userMap = new HashMap<String, String>();
userMap.put("username", username);
userMap.put("display-name", displayName);
userMap.put("email-id", emailId);
return userMap;
}
private GoPluginIdentifier getGoPluginIdentifier() {
return new GoPluginIdentifier(EXTENSION_NAME, goSupportedVersions);
}
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
return new GoApiRequest() {
@Override
public String api() {
return api;
}
@Override
public String apiVersion() {
return "1.0";
}
@Override
public GoPluginIdentifier pluginIdentifier() {
return getGoPluginIdentifier();
}
@Override
public Map<String, String> requestParameters() {
return null;
}
@Override
public Map<String, String> requestHeaders() {
return null;
}
@Override
public String requestBody() {
return responseBody;
}
};
}
private GoPluginApiResponse renderResponse(final int responseCode, final Map<String, String> responseHeaders, final String responseBody) {
return new GoPluginApiResponse() {
@Override
public int responseCode() {
return responseCode;
}
@Override
public Map<String, String> responseHeaders() {
return responseHeaders;
}
@Override
public String responseBody() {
return responseBody;
}
};
}
}
| 41.920354 | 161 | 0.681022 |
65557e3aaa1d2b55200fab0566fcb7d33600b7a9 | 3,187 | package com.weychain.erp.service;
import com.weychain.erp.domain.DO.Unit;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
<<<<<<< HEAD
public interface UnitService {
Unit getUnit(long id)throws Exception;
List<Unit> getUnit()throws Exception;
List<Unit> select(String name, int offset, int rows)throws Exception;
Long countUnit(String name)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int insertUnit(String beanJson, HttpServletRequest request)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int updateUnit(String beanJson, Long id)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int deleteUnit(Long id)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int batchDeleteUnit(String ids) throws Exception;
int checkIsNameExist(Long id, String name)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int batchDeleteUnitByIds(String ids)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
int batchDeleteUnitByIdsNormal(String ids) throws Exception;
=======
import java.util.Map;
public interface UnitService {
abstract Unit getUnit(long id)throws Exception;
abstract List<Unit> getUnit()throws Exception;
abstract List<Unit> select(String name, int offset, int rows)throws Exception;
abstract Long countUnit(String name)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int insertUnit(String beanJson, HttpServletRequest request)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int updateUnit(String beanJson, Long id)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int deleteUnit(Long id)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int batchDeleteUnit(String ids) throws Exception;
Object selectOne(Long id) throws Exception;
List<?> select(Map<String, String> map)throws Exception;
List<?> getUnitList(Map<String, String> map)throws Exception;
Long counts(Map<String, String> map)throws Exception;
int insert(String beanJson, HttpServletRequest request)throws Exception;
int update(String beanJson, Long id)throws Exception;
int delete(Long id)throws Exception;
int batchDelete(String ids)throws Exception;
abstract int checkIsNameExist(Long id, String name)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int batchDeleteUnitByIds(String ids)throws Exception;
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
abstract int batchDeleteUnitByIdsNormal(String ids) throws Exception;
>>>>>>> d55d0fe9e143a7b7fe4f5ca36e71a433c102f9b6
}
| 36.632184 | 89 | 0.767493 |
9991db35903dfa69acf4ae3a6094785ee85fbdce | 879 | package com.bitlove.fetlife.model.pojos.fetlife.json;
import com.bitlove.fetlife.model.pojos.fetlife.dbjson.Member;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Mention {
@JsonProperty("offset")
private int offset;
@JsonProperty("length")
private int length;
@JsonProperty("member")
private Member member;
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
}
| 20.44186 | 61 | 0.667804 |
5d34eb7fe8218ca8877f4f5a60065abe13707397 | 26,058 | /*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.drools.guvnor.client.moduleeditor.drools;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import org.drools.guvnor.client.common.*;
import org.drools.guvnor.client.explorer.ClientFactory;
import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.resources.DroolsGuvnorImageResources;
import org.drools.guvnor.client.resources.DroolsGuvnorImages;
import org.drools.guvnor.client.rpc.*;
import org.drools.guvnor.client.widgets.categorynav.CategoryExplorerWidget;
import org.drools.guvnor.client.widgets.categorynav.CategorySelectHandler;
import org.drools.guvnor.client.widgets.drools.tables.BuildPackageErrorsSimpleTable;
import org.kie.uberfirebootstrap.client.widgets.ErrorPopup;
import org.kie.uberfirebootstrap.client.widgets.FormStyleLayout;
import org.kie.uberfirebootstrap.client.widgets.FormStylePopup;
import org.kie.uberfirebootstrap.client.widgets.InfoPopup;
import java.util.ArrayList;
import java.util.List;
/**
* This is the widget for building packages, validating etc. Visually decorates
* or wraps a rule editor widget with buttons for this purpose.
*/
public class PackageBuilderWidget extends Composite {
private Module conf;
private final FormStyleLayout buildWholePackageLayout = new FormStyleLayout();
private final FormStyleLayout builtInSelectorLayout = new FormStyleLayout();
private final FormStyleLayout customSelectorLayout = new FormStyleLayout();
private String buildMode = "buildWholePackage";
private final ClientFactory clientFactory;
public PackageBuilderWidget(final Module conf,
ClientFactory clientFactory) {
this.conf = conf;
this.clientFactory = clientFactory;
// UI above the results table
FormStyleLayout layout = new FormStyleLayout();
final VerticalPanel container = new VerticalPanel();
final VerticalPanel buildResults = new VerticalPanel();
RadioButton wholePackageRadioButton = new RadioButton("action",
Constants.INSTANCE.BuildWholePackage());
RadioButton builtInSelectorRadioButton = new RadioButton("action",
Constants.INSTANCE.BuildPackageUsingBuiltInSelector());
RadioButton customSelectorRadioButton = new RadioButton("action",
Constants.INSTANCE.BuildPackageUsingCustomSelector());
wholePackageRadioButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
buildWholePackageLayout.setVisible(true);
builtInSelectorLayout.setVisible(false);
customSelectorLayout.setVisible(false);
buildMode = "buildWholePackage";
}
});
builtInSelectorRadioButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
buildWholePackageLayout.setVisible(false);
builtInSelectorLayout.setVisible(true);
customSelectorLayout.setVisible(false);
buildMode = "BuiltInSelector";
}
});
customSelectorRadioButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
buildWholePackageLayout.setVisible(false);
builtInSelectorLayout.setVisible(false);
customSelectorLayout.setVisible(true);
buildMode = "customSelector";
}
});
VerticalPanel verticalPanel = new VerticalPanel();
HorizontalPanel wholePackageRadioButtonPanel = new HorizontalPanel();
wholePackageRadioButtonPanel.add(wholePackageRadioButton);
wholePackageRadioButtonPanel.add(new InfoPopup(Constants.INSTANCE.BuildWholePackage(),
Constants.INSTANCE.BuildWholePackageTip()));
verticalPanel.add(wholePackageRadioButtonPanel);
HorizontalPanel builtInSelectorRadioButtonPanel = new HorizontalPanel();
builtInSelectorRadioButtonPanel.add(builtInSelectorRadioButton);
builtInSelectorRadioButtonPanel.add(new InfoPopup(Constants.INSTANCE.BuiltInSelector(),
Constants.INSTANCE.BuiltInSelectorTip()));
verticalPanel.add(builtInSelectorRadioButtonPanel);
HorizontalPanel customSelectorRadioButtonPanel = new HorizontalPanel();
customSelectorRadioButtonPanel.add(customSelectorRadioButton);
customSelectorRadioButtonPanel.add(new InfoPopup(Constants.INSTANCE.CustomSelector(),
Constants.INSTANCE.SelectorTip()));
verticalPanel.add(customSelectorRadioButtonPanel);
layout.addAttribute("",
verticalPanel);
wholePackageRadioButton.setValue(true);
buildWholePackageLayout.setVisible(true);
builtInSelectorLayout.setVisible(false);
customSelectorLayout.setVisible(false);
// Build whole package layout
layout.addRow(buildWholePackageLayout);
// Built-in selector layout
builtInSelectorLayout.addRow(new HTML(" <i>"
+ Constants.INSTANCE.BuildPackageUsingFollowingAssets()
+ "</i>"));
HorizontalPanel builtInSelectorStatusPanel = new HorizontalPanel();
final CheckBox enableStatusCheckBox = new CheckBox();
enableStatusCheckBox.setValue(false);
builtInSelectorStatusPanel.add(enableStatusCheckBox);
builtInSelectorStatusPanel.add(new HTML(" <i>"
+ Constants.INSTANCE.BuildPackageUsingBuiltInSelectorStatus()
+ " </i>"));
final ListBox statusOperator = new ListBox();
String[] vals = new String[]{"=", "!="};
for (int i = 0; i < vals.length; i++) {
statusOperator.addItem(vals[i],
vals[i]);
}
builtInSelectorStatusPanel.add(statusOperator);
final TextBox statusValue = new TextBox();
statusValue.setTitle(Constants.INSTANCE.WildCardsSearchTip());
builtInSelectorStatusPanel.add(statusValue);
builtInSelectorLayout.addRow(builtInSelectorStatusPanel);
HorizontalPanel builtInSelectorCatPanel = new HorizontalPanel();
final CheckBox enableCategoryCheckBox = new CheckBox();
enableCategoryCheckBox.setValue(false);
builtInSelectorCatPanel.add(enableCategoryCheckBox);
builtInSelectorCatPanel.add(new HTML(" <i>"
+ Constants.INSTANCE.BuildPackageUsingBuiltInSelectorCat()
+ " </i>"));
final ListBox catOperator = new ListBox();
String[] catVals = new String[]{"=", "!="};
for (int i = 0; i < catVals.length; i++) {
catOperator.addItem(catVals[i],
catVals[i]);
}
builtInSelectorCatPanel.add(catOperator);
final CategoryExplorerWidget catChooser = new CategoryExplorerWidget(new CategorySelectHandler() {
public void selected(String selectedPath) {
}
});
ScrollPanel catScroll = new ScrollPanel(catChooser);
catScroll.setAlwaysShowScrollBars(true);
catScroll.setSize("300px",
"130px");
builtInSelectorCatPanel.add(catScroll);
builtInSelectorLayout.addRow(builtInSelectorCatPanel);
layout.addRow(builtInSelectorLayout);
// Custom selector layout
customSelectorLayout.setVisible(false);
HorizontalPanel customSelectorPanel = new HorizontalPanel();
customSelectorPanel.add(new HTML(" <i>"
+ Constants.INSTANCE.BuildPackageUsingCustomSelectorSelector()
+ " </i>")); // NON-NLS
final ListBox customSelector = new ListBox();
customSelector.setTitle(Constants.INSTANCE.WildCardsSearchTip());
customSelectorPanel.add(customSelector);
loadCustomSelectorList(customSelector);
customSelectorLayout.addRow(customSelectorPanel);
layout.addRow(customSelectorLayout);
final Button b = new Button(Constants.INSTANCE.BuildPackage());
b.setTitle(Constants.INSTANCE.ThisWillValidateAndCompileAllTheAssetsInAPackage());
b.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
doBuild(buildResults,
statusOperator.getValue(statusOperator.getSelectedIndex()),
statusValue.getText(),
enableStatusCheckBox.getValue(),
catOperator.getValue(catOperator.getSelectedIndex()),
catChooser.getSelectedPath(),
enableCategoryCheckBox.getValue(),
customSelector.getSelectedIndex() != -1 ? customSelector.getValue(customSelector.getSelectedIndex()) : null);
}
});
HorizontalPanel buildStuff = new HorizontalPanel();
buildStuff.add(b);
layout.addAttribute(Constants.INSTANCE.BuildBinaryPackage(),
buildStuff);
layout.addRow(new HTML("<i><small>"
+ Constants.INSTANCE.BuildingPackageNote()
+ "</small></i>"));// NON-NLS
container.add(layout);
// The build results
container.add(buildResults);
// UI below the results table
layout = new FormStyleLayout();
Button snap = new Button(Constants.INSTANCE.CreateSnapshotForDeployment());
snap.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
showSnapshotDialog(conf.getName(),
null);
}
});
layout.addAttribute(Constants.INSTANCE.TakeSnapshot(),
snap);
container.add(layout);
initWidget(container);
}
private void loadCustomSelectorList(final ListBox customSelector) {
RepositoryServiceAsync repositoryService = GWT.create(RepositoryService.class);
repositoryService.getCustomSelectors(new GenericCallback<String[]>() {
public void onSuccess(String[] list) {
for (int i = 0; i < list.length; i++) {
customSelector.addItem(list[i],
list[i]);
}
}
});
}
private void doBuild(final Panel buildResults,
final String statusOperator,
final String statusValue,
final boolean enableStatusSelector,
final String categoryOperator,
final String category,
final boolean enableCategorySelector,
final String customSelector) {
buildResults.clear();
final HorizontalPanel busy = new HorizontalPanel();
busy.add(new Label(Constants.INSTANCE.ValidatingAndBuildingPackagePleaseWait()));
busy.add(new Image(DroolsGuvnorImageResources.INSTANCE.redAnime()));
buildResults.add(busy);
Scheduler scheduler = Scheduler.get();
scheduler.scheduleDeferred(new Command() {
public void execute() {
ModuleServiceAsync moduleService = GWT.create(ModuleService.class);
Path path = new PathImpl();
path.setUUID(conf.getUuid());
moduleService.buildPackage(path,
true,
buildMode,
statusOperator,
statusValue,
enableStatusSelector,
categoryOperator,
category,
enableCategorySelector,
customSelector,
new GenericCallback<BuilderResult>() {
public void onSuccess(BuilderResult result) {
LoadingPopup.close();
if (result == null || !result.hasLines()) {
showSuccessfulBuild(buildResults);
} else {
showBuilderErrors(result,
buildResults,
clientFactory);
}
}
public void onFailure(Throwable t) {
buildResults.clear();
super.onFailure(t);
}
});
}
});
}
/**
* Actually build the source, and display it.
*/
public static void doBuildSource(final String uuid,
final String name) {
LoadingPopup.showMessage(Constants.INSTANCE.AssemblingPackageSource());
Scheduler scheduler = Scheduler.get();
scheduler.scheduleDeferred(new Command() {
public void execute() {
ModuleServiceAsync moduleService = GWT.create(ModuleService.class);
Path path = new PathImpl();
path.setUUID(uuid);
moduleService.buildModuleSource(path,
new GenericCallback<java.lang.String>() {
public void onSuccess(String content) {
showSource(content,
name);
}
});
}
});
}
/**
* Popup the view source dialog, showing the given content.
*/
public static void showSource(final String content,
String name) {
int windowWidth = Window.getClientWidth() / 2;
int windowHeight = Window.getClientHeight() / 2;
Image image = new Image(DroolsGuvnorImageResources.INSTANCE.viewSource());
image.setAltText(Constants.INSTANCE.ViewSource());
final FormStylePopup pop = new FormStylePopup(image,
Constants.INSTANCE.ViewingSourceFor0( name ),
windowWidth );
String[] rows = content.split( "\n" );
FlexTable table = new FlexTable();
for ( int i = 0; i < rows.length; i++ ) {
table.setHTML( i,
0,
"<span style='color:grey;'>"
+ (i + 1)
+ ".</span>" );
table.setHTML( i,
1,
"<span style='color:green;' >|</span>" );
table.setHTML( i,
2,
addSyntaxHilights( rows[i] ) );
}
ScrollPanel scrollPanel = new ScrollPanel( table );
scrollPanel.setHeight( windowHeight + "px" );
scrollPanel.setWidth( windowWidth + "px" );
pop.addRow( scrollPanel );
LoadingPopup.close();
pop.show();
}
private static String addSyntaxHilights(String text) {
if (text.trim().startsWith("#")) {
text = "<span style='color:green'>"
+ text
+ "</span>";
} else {
String[] keywords = {"rule", "when", "then", "end", "accumulate", "collect", "from", "null", "over", "lock-on-active", "date-effective", "date-expires", "no-loop", "auto-focus", "activation-group", "agenda-group", "ruleflow-group",
"entry-point", "duration", "package", "import", "dialect", "salience", "enabled", "attributes", "extend", "template", "query", "declare", "function", "global", "eval", "exists", "forall", "action", "reverse", "result", "end",
"init"};
for (String keyword : keywords) {
if (text.contains(keyword)) {
text = text.replace(keyword,
"<span style='color:red;'>"
+ keyword
+ "</span>");
}
}
text = handleStrings("\"",
text);
}
text = text.replace("\t",
" ");
return text;
}
private static String handleStrings(String character,
String text) {
int stringStart = text.indexOf(character);
while (stringStart >= 0) {
int stringEnd = text.indexOf(character,
stringStart + 1);
if (stringEnd < 0) {
stringStart = -1;
break;
}
String oldString = text.substring(stringStart,
stringEnd + 1);
String newString = "<span style='color:green;'>"
+ oldString
+ "</span>";
String beginning = text.substring(0,
stringStart);
String end = text.substring(stringEnd + 1);
text = beginning
+ newString
+ end;
int searchStart = stringStart
+ newString.length()
+ 1;
if (searchStart < text.length()) {
stringStart = text.indexOf(character,
searchStart);
} else {
stringStart = -1;
}
}
return text;
}
/**
* This is called to display the success (and a download option).
*
* @param buildResults
*/
private void showSuccessfulBuild(Panel buildResults) {
buildResults.clear();
VerticalPanel vert = new VerticalPanel();
vert.add(new HTML(AbstractImagePrototype.create(DroolsGuvnorImageResources.INSTANCE.greenTick()).getHTML()
+ "<i>"
+ Constants.INSTANCE.PackageBuiltSuccessfully()
+ " "
+ conf.getLastModified()
+ "</i>"));
final String hyp = getDownloadLink(this.conf);
HTML html = new HTML("<a href='"
+ hyp
+ "' target='_blank'>"
+ Constants.INSTANCE.DownloadBinaryPackage()
+ "</a>");
vert.add(html);
buildResults.add(vert);
}
/**
* Get a download link for the binary package.
*/
public static String getDownloadLink(Module conf) {
String hurl = GWT.getModuleBaseURL()
+ "package/"
+ conf.getName(); // NON-NLS
if (!conf.isSnapshot()) {
hurl = hurl
+ "/"
+ SnapshotView.LATEST_SNAPSHOT;
} else {
hurl = hurl
+ "/"
+ conf.getSnapshotName();
}
final String uri = hurl;
return uri;
}
/**
* This is called in the unhappy event of there being errors.
*/
public static void showBuilderErrors(BuilderResult results,
Panel buildResults,
ClientFactory clientFactory) {
buildResults.clear();
BuildPackageErrorsSimpleTable errorsTable = new BuildPackageErrorsSimpleTable(clientFactory);
errorsTable.setRowData(results.getLines());
errorsTable.setRowCount(results.getLines().size());
buildResults.add(errorsTable);
}
/**
* This will display a dialog for creating a snapshot.
*/
public static void showSnapshotDialog(final String packageName,
final Command refreshCmd) {
LoadingPopup.showMessage(Constants.INSTANCE.LoadingExistingSnapshots());
final FormStylePopup form = new FormStylePopup(DroolsGuvnorImages.INSTANCE.Snapshot(),
Constants.INSTANCE.CreateASnapshotForDeployment());
form.addRow(new HTML(Constants.INSTANCE.SnapshotDescription()));
final VerticalPanel vert = new VerticalPanel();
form.addAttribute(Constants.INSTANCE.ChooseOrCreateSnapshotName(),
vert);
final List<RadioButton> radioList = new ArrayList<RadioButton>();
final TextBox newName = new TextBox();
final String newSnapshotText = Constants.INSTANCE.NEW()
+ ": ";
ModuleServiceAsync moduleService = GWT.create(ModuleService.class);
moduleService.listSnapshots(packageName,
new GenericCallback<SnapshotInfo[]>() {
public void onSuccess(SnapshotInfo[] result) {
for (int i = 0; i < result.length; i++) {
RadioButton existing = new RadioButton("snapshotNameGroup",
result[i].getName()); // NON-NLS
radioList.add(existing);
vert.add(existing);
}
HorizontalPanel newSnap = new HorizontalPanel();
final RadioButton newSnapRadio = new RadioButton("snapshotNameGroup",
newSnapshotText); // NON-NLS
newSnap.add(newSnapRadio);
newName.setEnabled(false);
newSnapRadio.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
newName.setEnabled(true);
}
});
newSnap.add(newName);
radioList.add(newSnapRadio);
vert.add(newSnap);
LoadingPopup.close();
}
});
final TextBox comment = new TextBox();
form.addAttribute(Constants.INSTANCE.Comment(),
comment);
Button create = new Button(Constants.INSTANCE.CreateNewSnapshot());
form.addAttribute("",
create);
create.addClickHandler(new ClickHandler() {
String name = "";
public void onClick(ClickEvent event) {
boolean replace = false;
for (RadioButton but : radioList) {
if (but.getValue()) {
name = but.getText();
if (!but.getText().equals(newSnapshotText)) {
replace = true;
}
break;
}
}
if (name.equals(newSnapshotText)) {
name = newName.getText();
}
if (name.equals("")) {
Window.alert(Constants.INSTANCE.YouHaveToEnterOrChoseALabelNameForTheSnapshot());
return;
}
LoadingPopup.showMessage(Constants.INSTANCE.PleaseWaitDotDotDot());
ModuleServiceAsync moduleService = GWT.create(ModuleService.class);
moduleService.createModuleSnapshot(packageName,
name,
replace,
comment.getText(),
true,
new GenericCallback<java.lang.Void>() {
public void onSuccess(Void v) {
Window.alert(Constants.INSTANCE.TheSnapshotCalled0WasSuccessfullyCreated(name));
form.hide();
if (refreshCmd != null) {
refreshCmd.execute();
}
LoadingPopup.close();
}
public void onFailure(Throwable t) {
LoadingPopup.close();
if (t instanceof SessionExpiredException) {
showSessionExpiry();
} else if (t instanceof DetailedSerializationException) {
if(((DetailedSerializationException)t).getMessage().contains("Your package has not been built since last change")) {
ErrorPopup.showMessage(Constants.INSTANCE.PackageHadNotBeenBuiltWarning());
} else {
ErrorPopup.showMessage( t.getMessage(),
((DetailedSerializationException)t).getLongDescription() );
}
} else {
String message = t.getMessage();
if (t.getMessage()!=null && t.getMessage().trim().equals("0")){
message = ((Constants) GWT.create(Constants.class)).CommunicationError();
}
ErrorPopup.showMessage(message);
}
}
});
}
});
form.show();
}
}
| 41.165877 | 245 | 0.551961 |
36abd204d088e514e962001a3f83d87654b5b0cc | 1,712 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settingslib.widget;
import static com.google.common.truth.Truth.assertThat;
import android.app.Activity;
import android.graphics.drawable.AnimatedRotateDrawable;
import android.view.View;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AnimatedImageViewTest {
private AnimatedImageView mAnimatedImageView;
@Before
public void setUp() {
Activity activity = Robolectric.setupActivity(Activity.class);
mAnimatedImageView = new AnimatedImageView(activity);
mAnimatedImageView.setImageDrawable(new AnimatedRotateDrawable());
}
@Test
public void testAnimation_ViewVisible_AnimationRunning() {
mAnimatedImageView.setVisibility(View.VISIBLE);
mAnimatedImageView.setAnimating(true);
AnimatedRotateDrawable drawable = (AnimatedRotateDrawable) mAnimatedImageView.getDrawable();
assertThat(drawable.isRunning()).isTrue();
}
}
| 33.568627 | 100 | 0.761098 |
10c4707b31a022d286d188d013984f05a5f3799b | 2,933 | package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_TOO_MANY_TAG_FIELDS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_CARDNUMBER;
import static seedu.address.logic.parser.CliSyntax.PREFIX_CVC;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EXPIRYDATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.Set;
import java.util.stream.Stream;
import seedu.address.logic.commands.AddCardCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.card.Card;
import seedu.address.model.card.CardNumber;
import seedu.address.model.card.Cvc;
import seedu.address.model.card.Description;
import seedu.address.model.card.ExpiryDate;
import seedu.address.model.tag.Tag;
/**
* Parses input arguments and creates a new AddCardCommand object
*/
public class AddCardCommandParser implements Parser<AddCardCommand> {
/**
* Parses the given {@code String} of arguments in the context of the AddCardCommand
* and returns an AddCardCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public AddCardCommand parse(String args) throws ParseException {
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_DESCRIPTION, PREFIX_CARDNUMBER, PREFIX_CVC,
PREFIX_EXPIRYDATE, PREFIX_TAG);
if (!arePrefixesPresent(argMultimap, PREFIX_DESCRIPTION, PREFIX_CARDNUMBER, PREFIX_CVC, PREFIX_EXPIRYDATE)
|| !argMultimap.getPreamble().isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCardCommand.MESSAGE_USAGE));
}
if (argMultimap.getAllValues(PREFIX_TAG).size() > 5) {
throw new ParseException(String.format(MESSAGE_TOO_MANY_TAG_FIELDS, AddCardCommand.MESSAGE_USAGE));
}
Description description = ParserUtil.parseCardDescription(argMultimap.getValue(PREFIX_DESCRIPTION).get());
CardNumber cardNumber = ParserUtil.parseCardNumber(argMultimap.getValue(PREFIX_CARDNUMBER).get());
Cvc cvc = ParserUtil.parseCvc(argMultimap.getValue(PREFIX_CVC).get());
ExpiryDate expiryDate = ParserUtil.parseExpiryDate(argMultimap.getValue(PREFIX_EXPIRYDATE).get());
Set<Tag> tagList = ParserUtil.parseTags(argMultimap.getAllValues(PREFIX_TAG));
Card card = new Card(description, cardNumber, cvc, expiryDate, tagList);
return new AddCardCommand(card);
}
private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
}
}
| 47.306452 | 114 | 0.765428 |
52f2817b2e25e3bb272579d99155a7930ca74940 | 7,872 | /* Copyright 2016 Sven van der Meer <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.skb.interfaces.transformers.textformat;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.StrBuilder;
import de.vandermeer.skb.interfaces.transformers.IsTransformer;
/**
* Converts a string to a justified string of given length.
* If the given string length is less than the required length, it will be stretched by inserting white spaces.
* The returned string will be of the required length, blank strings will have only blanks characters.
*
* The method can be further customized by
* - Setting an inner white space character - replace all white spaces in the text with that character
*
* The default length is {@link #DEFAULT_LENGTH}.
* The default inner white space character is {@link #DEFAULT_INNER_WHITESPACE_CHARACTER}.
*
* The actual return object is of type {@link StrBuilder} to minimize the creation of lots of strings for more complex transformations.
* An implementation can chose to provide a builder to append the padded string to as well.
*
* @author Sven van der Meer <[email protected]>
* @version v0.0.2 build 170502 (02-May-17) for Java 1.8
* @since v0.0.1
*/
public interface String_To_Justified extends IsTransformer<String, StrBuilder> {
/** The default width, set to 80. */
static int DEFAULT_LENGTH = 80;
/** Default white space replacement character, set to ' '. */
static char DEFAULT_INNER_WHITESPACE_CHARACTER = ' ';
/**
* Returns the required length for the conversion.
* @return length, default is {@link #DEFAULT_LENGTH}
*/
default int getLength(){
return DEFAULT_LENGTH;
}
/**
* Returns the white space replacement character.
* @return white space replacement character, default is {@link #DEFAULT_INNER_WHITESPACE_CHARACTER}
*/
default Character getInnerWsChar(){
return DEFAULT_INNER_WHITESPACE_CHARACTER;
}
/**
* Returns a builder to append the justified string to, rather than creating a new builder.
* @return builder, can be null, if not null the justified string will be appended to it
*/
default StrBuilder getBuilderForAppend(){
return null;
}
@Override
default StrBuilder transform(String s) {
IsTransformer.super.transform(s);
StrBuilder ret = (this.getBuilderForAppend()==null)?new StrBuilder(this.getLength()):this.getBuilderForAppend();
// set string and replace all inner ws with required character
String[] ar = StringUtils.split((s==null)?"":s);
int length = 0;
for(String str : ar){
length += str.length();
}
//first spaces to distributed (even)
//do that until all firsts have been consumed
int l = ((ar.length-1)==0)?1:(ar.length-1); // null safe dividend
int first = ((this.getLength() - length) / l) * (ar.length-1);
while(first>0){
for(int i=0; i<ar.length-1; i++){
if(first!=0){
ar[i] += this.getInnerWsChar();
first--;
}
}
}
//second space to distributed (leftovers, as many as there are)
//do seconds from the back to front, until all seconds have been consumed
//reverse means do not append to the last array element!
int second = (this.getLength() - length) % l;
while(second>0){
for(int i=ar.length-2; i>0; i--){
if(second!=0){
ar[i] += this.getInnerWsChar();
second--;
}
}
}
ret.append(StringUtils.join(ar));
while(ret.length()<this.getLength()){
ret.append(' ');
}
return ret;
}
/**
* Creates a transformer that converts a string to a justified string of given length.
* @param length the required length (must be >0)
* @param innerWsChar inner white space replacement character
* @param builder an optional builder to append the padded string to, used if set, ignored if null
* @return new transformer
* @see String_To_Justified interface description for how the converter works
* @throws NullPointerException if an argument was unexpectedly null
* @throws IllegalArgumentException if an argument was illegal
*/
static String_To_Justified create(int length, Character innerWsChar, StrBuilder builder){
Validate.validState(length>0, "cannot work with lenght of less than 1");
return new String_To_Justified() {
@Override
public int getLength(){
return (length<1)?String_To_Justified.super.getLength():length;
}
@Override
public StrBuilder getBuilderForAppend(){
return builder;
}
@Override
public Character getInnerWsChar() {
return (innerWsChar==null)?String_To_Justified.super.getInnerWsChar():innerWsChar;
}
};
}
/**
* Returns justified string of given length.
* @param s input string
* @param length the required length (must be >0)
* @return justified string
* @see String_To_Justified interface description for how the conversion works
* @throws NullPointerException if an argument was unexpectedly null
* @throws IllegalArgumentException if an argument was illegal
*/
static StrBuilder convert(String s, int length){
return String_To_Justified.create(length, null, null).transform(s);
}
/**
* Returns justified string of given length.
* @param s input string
* @param length the required length (must be >0)
* @param innerWsChar inner white space replacement character, default is used if null
* @return justified string
* @see String_To_Justified interface description for how the conversion works
* @throws NullPointerException if an argument was unexpectedly null
* @throws IllegalArgumentException if an argument was illegal
*/
static StrBuilder convert(String s, int length, Character innerWsChar){
return String_To_Justified.create(length, innerWsChar, null).transform(s);
}
/**
* Returns justified string of given length.
* @param s input string
* @param length the required length (must be >0)
* @param builder an optional builder to append the padded string to, used if set, ignored if null
* @return justified string
* @see String_To_Justified interface description for how the conversion works
* @throws NullPointerException if an argument was unexpectedly null
* @throws IllegalArgumentException if an argument was illegal
*/
static StrBuilder convert(String s, int length, StrBuilder builder){
return String_To_Justified.create(length, null, builder).transform(s);
}
/**
* Returns justified string of given length.
* @param s input string
* @param length the required length (must be >0)
* @param innerWsChar inner white space replacement character, default is used if null
* @param builder an optional builder to append the padded string to, used if set, ignored if null
* @return justified string
* @see String_To_Justified interface description for how the conversion works
* @throws NullPointerException if an argument was unexpectedly null
* @throws IllegalArgumentException if an argument was illegal
*/
static StrBuilder convert(String s, int length, Character innerWsChar, StrBuilder builder){
return String_To_Justified.create(length, innerWsChar, builder).transform(s);
}
}
| 38.588235 | 136 | 0.714812 |
60ee2c30a55f58e29ce59c9a0cf2e847a9955c5f | 2,516 | package com.gentics.cr.lucene.didyoumean;
import java.io.IOException;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.spell.CustomSpellChecker;
import org.apache.lucene.search.spell.LuceneDictionary;
import com.gentics.cr.CRConfig;
import com.gentics.cr.CRConfigUtil;
import com.gentics.cr.exceptions.CRException;
import com.gentics.cr.lucene.indexaccessor.IndexAccessor;
import com.gentics.cr.lucene.util.CRLuceneUtil;
import com.gentics.cr.monitoring.MonitorFactory;
import com.gentics.cr.monitoring.UseCase;
import com.gentics.cr.util.indexing.AbstractUpdateCheckerJob;
import com.gentics.cr.util.indexing.IndexLocation;
/**
* This job is used to re-index (or newly index) the didyoumean-index.
*/
public class DidyoumeanIndexJob extends AbstractUpdateCheckerJob {
private DidyoumeanIndexExtension didyoumean;
public DidyoumeanIndexJob(CRConfig updateCheckerConfig, IndexLocation indexLoc, DidyoumeanIndexExtension didyoumean) {
super(updateCheckerConfig, indexLoc, null);
this.identifyer = identifyer.concat(":reIndex");
log = Logger.getLogger(DidyoumeanIndexJob.class);
this.didyoumean = didyoumean;
}
/**
* starts the job - is called by the IndexJobQueue.
*/
@Override
protected void indexCR(IndexLocation indexLocation, CRConfigUtil config) throws CRException {
try {
reIndex();
} catch (IOException e) {
throw new CRException("Could not access the DidYouMean- index! " + e.getMessage());
}
}
private synchronized void reIndex() throws IOException {
UseCase ucReIndex = MonitorFactory.startUseCase("reIndex()");
// build a dictionary (from the spell package)
log.debug("Starting to reindex didyoumean index.");
IndexAccessor sourceAccessor = didyoumean.getSourceLocation().getAccessor();
IndexReader sourceReader = sourceAccessor.getReader(false);
CustomSpellChecker spellchecker = didyoumean.getSpellchecker();
Collection<String> fields = null;
if (didyoumean.isAll()) {
fields = CRLuceneUtil.getFieldNames(sourceReader);
} else {
fields = didyoumean.getDym_fields();
}
try {
for (String fieldname : fields) {
LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldname);
spellchecker.indexDictionary(dict);
}
} finally {
if (sourceAccessor != null && sourceReader != null) {
sourceAccessor.release(sourceReader, false);
}
}
log.debug("Finished reindexing didyoumean index.");
ucReIndex.stop();
}
}
| 32.25641 | 119 | 0.766693 |
feaa0943fb86a61f8206ad369e5e3ea764b1e50b | 1,133 | package problems.medium;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* Given an integer n and a list of integers l, write a function that randomly
* generates a number from 0 to n-1 that isn't in l (uniform).
*
* @author Andrew
*
*/
public class RandomPickBlacklist {
public static int pick(int N, int[] blacklist) {
Set<Integer> blackSet = new HashSet<>();
for (int i : blacklist) {
blackSet.add(i);
}
if (blacklist.length > N / 3) {
List<Integer> allowed = new ArrayList<>();
for (int i = 0; i < N; i++) {
if (!blackSet.contains(i)) {
allowed.add(i);
}
}
int idx = new Random().nextInt(allowed.size());
return allowed.get(idx);
} else {
while (true) {
int test = new Random().nextInt(N);
if (!blackSet.contains(test)) {
return test;
}
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(pick(9,new int[] {1,4,6,7}));
}
for (int i = 0; i < 10; i++) {
System.out.println(pick(21,new int[] {9,10,11}));
}
}
}
| 22.215686 | 78 | 0.60459 |
db49c7f593d479c55294decd86209bfb2c7625ce | 4,407 | import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
//setting variables used in multiple functions
int count;
int n;
boolean open[];
int grid[];
WeightedQuickUnionUF quickUnion;
//Creating the nxn grid, all sites blocked
public Percolation(int n) {
if(n <= 0) { //throwing an exception if the size of the array is invalid
throw new IllegalArgumentException("n must be > 0");
}
//setting each global variable to be unique for this specific object created
this.n= n;
this.count = 0;
this.grid = new int[this.n*this.n + 2];
this.open = new boolean[this.n*this.n + 2];
this.quickUnion = new WeightedQuickUnionUF(this.n*this.n + 2); //new WeightedQuickUnionUF object for this percolation object
//populating the grid and open (array for whether the site is open) with default values
//for grid, the default values are equal to that element number so each site is its own parent at the start
//for the open array, populating with false values to say they are closed
for(int i = 0; i < this.n*this.n + 2; i++) {
this.grid[i] = i;
this.open[i] = false;
}
}
//check whether a site is already open, open if not.
//site # consists of (row,col) coordinate
public void open(int row, int col) {
//new variables for the position of the site, and the sites around it excluding diagonals
int site = this.n*row + col;
int top = site - this.n;
int bot = site + this.n;
int left = site - 1;
int right = site + 1;
//throwing an exception if the site number or grid length are invalid
if(site > grid.length || site < 0) {
throw new IllegalArgumentException("index " + site + " is not between 0 and " + (n-1));
}
//checking if the site is already open, if not, opening it
if(!isOpen(row, col)) {
open[site] = true; //open the site by setting the element value to true
this.count ++; //increasing the count variable for the number of open sites
if(!(site < this.n) && open[top] == true) { //checking if the site is anywhere but the top row, if thats true, and the above site is open, union the above site to the site
quickUnion.union(top, site);
}
if(!(site > this.n*(this.n-1) - 1) && open[bot] == true) { //checking if the site is anywhere but the bottom row, same as above but for site under
quickUnion.union(bot, site);
}
if(site%this.n != 0 && open[left] == true) { //check if the site is anywhere but the left side, same as above but for the site to the left
quickUnion.union(left, site);
}
if((site + 1)%this.n != 0 && open[right] == true) { //check if the site is anywhere but the right side, same as above but for the site to the right
quickUnion.union(right, site);
}
if(site < this.n) { //checking if the site is in the first row, then union it to the first virtual site
quickUnion.union(site, grid[this.n*this.n]);
}
else if(site > this.n*(this.n-1) - 1) { //checking if the site is in the last row otherwise, then union it to the second virtual site
quickUnion.union(site, grid[this.n*this.n + 1]);
}
}
}
//check whether a site is open
public boolean isOpen(int row, int col) {
//calculating the site number from the given row and column
int site = n*row + col;
//throwing an exception if the site number is out of the grid length, or is negative
if(site > grid.length || site < 0) {
throw new IllegalArgumentException("index " + site + " is not between 0 and " + (n-1));
}
return open[n*row + col]; //return the state of the open array index of site.
}
//check whether the site being checked is full by checking whether the virtual site
//connected to the top open sites is connected to the site being called
public boolean isFull(int row, int col) {
int site = n*row + col;
if(site > grid.length || site < 0) {
throw new IllegalArgumentException("index " + site + " is not between 0 and " + (n-1));
}
if(quickUnion.connected(site,grid[n*n])){
return true;
}
else {
return false;
}
}
//returns the value counted as each site is opened - count
public int numberOfOpenSites() {
return this.count;
}
//checks whether the system percolates; i.e., the top virtual site is connected to the bottom virtual site., also, whether there is one path from the top to the bottom
public boolean percolates() {
return quickUnion.connected(grid[n*n], grid[n*n + 1]);
}
}
| 39 | 174 | 0.677332 |
480d773aaa7b6734bce78ee14b7c07cb266e2714 | 15,880 | package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.solver.state.State;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Insets;
import android.graphics.PointF;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowMetrics;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.lang.reflect.Array;
import java.util.ArrayList;
@SuppressLint("ClickableViewAccessibility")
public class playViewer extends AppCompatActivity {
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private String userType;
private int position;
private ArrayList<Play> currPlays;
protected Play currPlay;
private ConstraintLayout layoutAddPlayer;
private ArrayList<playObject> playObjectsClone;
protected ArrayList<playObject> playObjectsLearn;
private Button addPlayer;
private ConstraintLayout layoutAddNewPlayer;
private int counterPlayer;
private Boolean drawTrue=false;
private FieldMap field;
private ConstraintLayout layout;
private Button animateTrueFalse;
private Button learn;
private Button test;
private ArrayList<playObject> untouchedPure;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_viewer);
layoutAddNewPlayer= findViewById(R.id.layoutAddNewPlayer);
mAuth= FirebaseAuth.getInstance();
firebaseFirestore= FirebaseFirestore.getInstance();
userType=getIntent().getStringExtra("UserType");
String positionStr=getIntent().getStringExtra("Position");
position= (Integer) Integer.parseInt(positionStr);
getData();
addPlayer= findViewById(R.id.addPlayerView);
WindowMetrics windowMetrics = this.getWindowManager().getCurrentWindowMetrics();
Insets insets = windowMetrics.getWindowInsets().getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
int Width= windowMetrics.getBounds().width() - insets.left - insets.right;
int Height= windowMetrics.getBounds().height()- insets.top -insets.bottom;
playObjectsLearn= new ArrayList<>();
layoutAddPlayer= findViewById(R.id.layoutAddPlayer);
layout = findViewById(R.id.layoutPlayViewer);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(Width ,Height,300000);
field= new FieldMap(this);
field.setLayoutParams(params);
layout.addView(field,0);
animateTrueFalse= findViewById(R.id.animateTrueFalse);
learn= findViewById(R.id.Check);
test= findViewById(R.id.Test);
}
public void getData()
{
firebaseFirestore.collection("Users").document(mAuth.getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
DocumentSnapshot userSnapshot= task.getResult();
User currUser= userSnapshot.toObject(User.class);
userType= currUser.getType();
String club= currUser.getClub();
System.out.println("CLub"+ club);
System.out.println(mAuth.getUid());
firebaseFirestore.collection("Clubs").document(club).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
DocumentSnapshot clubSnapshot= task.getResult();
Club currClub= clubSnapshot.toObject(Club.class);
currPlays= currClub.getPlays();
currPlay=currPlays.get(position);
System.out.println(currPlay.getPlayName());
System.out.println(currPlays.size());
playObjectsClone= currPlay.getPlayObjects();
System.out.println(playObjectsClone.size()+" CHECKING SIZE");
playObjectsLearn= currPlay.getPlayObjects();
System.out.println(playObjectsLearn.size());
untouchedPure=currClub.getPlays().get(position).getPlayObjects();
fillScreen();
field.setStorage(currPlay.getPlayObjects());
}
}
});
}
}
});
}
public void addLearnedPlay()
{
firebaseFirestore.collection("Users").document(mAuth.getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
DocumentSnapshot userSnapshot= task.getResult();
User currUser= userSnapshot.toObject(User.class);
userType= currUser.getType();
String club= currUser.getClub();
firebaseFirestore.collection("Clubs").document(club).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
DocumentSnapshot clubSnapshot= task.getResult();
Club currClub= clubSnapshot.toObject(Club.class);
currClub.getPlays().get(position).getLearnedPlay().add(currUser);
firebaseFirestore.collection("Clubs").document(club).set(currClub);
}
}
});
}
}
});
}
public void fillScreen()
{
addPlayer();
ArrayList filler= currPlay.getPlayObjects();
field.setPlayObjects(filler);
field.setStorage(filler);
System.out.println(filler.size()+ "check tastic");
field.invalidate();
}
@SuppressLint("ClickableViewAccessibility")
public void addPlayer()
{
for (int i=0;i<currPlay.getPlayObjects().size();i++) {
playObject currPlayObject= currPlay.getPlayObjects().get(i);
ImageView template = new ImageView(playViewer.this);
template.setImageResource(R.drawable.ic_player);
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(75, 75);
layoutParams.setMargins(0, 10, 0, 10);
template.setLayoutParams(layoutParams);
template.setX(currPlayObject.getCurrPoint().x);
template.setY(currPlayObject.getCurrPoint().y);
layoutAddPlayer.addView(template);
}
}
public void getCorrectID(ArrayList<playObject> playObjects2,int thing,PointF currpoint)
{
for (int i=0;i<playObjects2.size();i++)
{
if(playObjects2.get(i).getPlayObjectID()==thing)
{
playObjects2.get(i).setCurrPoint(currpoint);
}
}
}
public void getCorrectIDFinalPoint(ArrayList<playObject> playObjects2,int thing,PointF currpoint,PointF finalPoint)
{
for (int i=0;i<playObjects2.size();i++)
{
if(playObjects2.get(i).getPlayObjectID()==thing)
{
playObjects2.get(i).setArrowDrawn(true);
playObjects2.get(i).setCurrPoint(currpoint);
playObjects2.get(i).setFinalPoint(finalPoint);
}
}
}
public void learnCheck(View v)
{
getData();
if(learnCheck2(playObjectsClone,field.getStorage()))
{
addLearnedPlay();
Toast.makeText(getBaseContext(),"You learned it good job", Toast.LENGTH_LONG).show();
learn.setBackgroundColor(Color.GREEN);
}
else
{
Toast.makeText(getBaseContext(),"You are trash", Toast.LENGTH_LONG).show();
learn.setBackgroundColor(Color.RED);
}
}
public Boolean learnCheck2(ArrayList<playObject> checking, ArrayList<playObject> original)
{
int counter=0;
System.out.println(checking.size()+"FUck"+original.size());
for(int i=0;i<checking.size();i++) {
if(checking.get(i).getArrowDrawn())
{
for (int k=0;k<original.size();k++){
System.out.println("checking");
if(distance(checking.get(i).getCurrPoint(),original.get(k).getCurrPoint())
&&distance(checking.get(i).getFinalPoint(),original.get(k).getFinalPoint()))
{
System.out.println(checking.get(i));
System.out.println(original.get(i));
counter+=1;
}
}
}
else if(!checking.get(i).getArrowDrawn())
{
for (int z=0;z<original.size();z++){
if(distance(checking.get(i).getCurrPoint(),original.get(z).getCurrPoint())&&!original.get(z).getArrowDrawn())
{
System.out.println(checking.get(i));
System.out.println(original.get(i));
counter+=1;
}
}
}
}
if(original.size()==counter)
{
System.out.println(counter+"Does this really work?");
return true;
}
else
{
System.out.println(counter+"Does this really work?+ False case");
return false;
}
}
public Boolean distance(PointF point1,PointF point2)
{
System.out.println("I have been called");
float distance1=(point1.x-point2.x)*(point1.x-point2.x);
float distance2=(point1.y-point2.y)*(point1.y-point2.y);
double distance3= Math.sqrt(Math.round(distance1+distance2));
if(distance3<50)
{
Log.d("distance","This is in range");
System.out.println("This is in range");
Log.d("distance","this is the distance "+distance3);
return true;
}
Log.d("distance","This is out of range");
System.out.println("This is out of range");
Log.d("distance","this is the distance"+distance3);
return false;
}
public void drawArrow(View v)
{
if(drawTrue)
{
drawTrue=false;
animateTrueFalse.setBackgroundColor(Color.RED);
animateTrueFalse.setText("Drag");
}
else
{
drawTrue=true;
animateTrueFalse.setBackgroundColor(Color.GREEN);
animateTrueFalse.setText("Arrow");
}
}
public void Test(View v)
{
layoutAddPlayer.removeAllViews();
layoutAddNewPlayer.removeAllViews();
addPlayer.setVisibility(View.VISIBLE);
counterPlayer=0;
System.out.println(currPlay.getPlayObjects().size()+" rando garb1");
playObjectsClone= new ArrayList<>();
System.out.println(currPlay.getPlayObjects().size()+" rando garb2");
field.reset();
System.out.println(currPlay.getPlayObjects().size()+" rando garb3");
System.out.println(playObjectsClone.size()+ " CHECKING SIZE V2");
System.out.println(currPlay.getPlayObjects().size()+" rando garb");
}
public void addView(ImageView imageView,int width,int height)
{
counterPlayer+=1;
ConstraintLayout.LayoutParams layoutParams= new ConstraintLayout.LayoutParams(width,height);
layoutParams.setMargins(0,10,0,10);
imageView.setLayoutParams(layoutParams);
imageView.setId(counterPlayer);
layoutAddNewPlayer.addView(imageView);
playObject playObjectTemplate= new playObject(false,"ball",counterPlayer);
PointF finalPoint= new PointF();
finalPoint.set(30,30);
playObjectTemplate.setFinalPoint(finalPoint);
playObjectsClone.add(playObjectTemplate);
System.out.println(playObjectsClone.size());
}
public void AddPlayer(View v)
{
ImageView template= new ImageView(playViewer.this);
template.setImageResource(R.drawable.ic_player);
addView(template,75,75);
template.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float xDown = 0, yDown = 0;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
xDown = event.getX();
yDown = event.getY();
break;
case MotionEvent.ACTION_UP:
float movedX, movedY;
movedX = event.getX();
movedY = event.getY();
float distanceX = movedX - xDown;
float distanceY = movedY - yDown;
if (!drawTrue) {
System.out.println(template.getX() + distanceX);
template.setX(template.getX() + distanceX);
template.setY(template.getY() + distanceY);
PointF currpoint= new PointF();
currpoint.set((template.getX() + distanceX),(template.getY() + distanceY));
getCorrectID(playObjectsClone,template.getId(),currpoint);
field.setPlayObjects(playObjectsClone);
field.invalidate();
} else {
System.out.println("I AM DRAWING");
System.out.println(playObjectsClone.toString());
System.out.println(playObjectsClone.toString());
PointF currPoint = new PointF();
currPoint.set(template.getX(), template.getY());
PointF finalPoint = new PointF();
finalPoint.set(template.getX() + distanceX, template.getY() + distanceY);
getCorrectIDFinalPoint(playObjectsClone,template.getId(),currPoint,finalPoint);
field.setPlayObjects(playObjectsClone);
field.invalidate();
}
break;
}
return true;
}
});
}
} | 33.361345 | 145 | 0.57097 |
a348870a81807c8b85e4231e1d8932575f66c244 | 4,373 | package org.markdownwriterfx.options;
import java.util.List;
import java.util.prefs.Preferences;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.text.Font;
import org.markdownwriterfx.util.PrefsBooleanProperty;
import org.markdownwriterfx.util.PrefsIntegerProperty;
import org.markdownwriterfx.util.PrefsStringProperty;
import org.markdownwriterfx.util.PrefsStringsProperty;
public class Options {
public static final String[] DEF_FONT_FAMILIES = {
//"Fira Code",
"Consolas",
"DejaVu Sans Mono",
"Lucida Sans Typewriter",
"Lucida Console"
};
public static final int DEF_FONT_SIZE = 12;
public static final int MIN_FONT_SIZE = 8;
public static final int MAX_FONT_SIZE = 36;
public static final String DEF_MARKDOWN_FILE_EXTENSIONS = "*.md,*.markdown,*.txt";
public static final String emphasisMarker = "_";
public static final String strongEmphasisMarker = "**";
public static final String bulletListMarker = "*";
public static void load(Preferences options) {
fontFamily.init(options, "fontFamily", null, value -> safeFontFamily(value));
fontSize.init(options, "fontSize", DEF_FONT_SIZE);
markdownExtensions.init(options, "markdownExtensions");
// TODO rewrite after add extension dialogs
setMarkdownExtensions(MarkdownExtensions.ids());
showLineNo.init(options, "showLineNo", true);
showWhitespace.init(options, "showWhitespace", false);
}
/**
* Check whether font family is null or invalid (family not available on
* system) and search for an available family.
*/
private static String safeFontFamily(String fontFamily) {
List<String> fontFamilies = Font.getFamilies();
if (fontFamily != null && fontFamilies.contains(fontFamily)) {
return fontFamily;
}
for (String family : DEF_FONT_FAMILIES) {
if (fontFamilies.contains(family)) {
return family;
}
}
return "Monospaced";
}
// 'fontFamily' property
private static final PrefsStringProperty fontFamily = new PrefsStringProperty();
public static String getFontFamily() {
return fontFamily.get();
}
public static void setFontFamily(String fontFamily) {
Options.fontFamily.set(fontFamily);
}
public static StringProperty fontFamilyProperty() {
return fontFamily;
}
// 'fontSize' property
private static final PrefsIntegerProperty fontSize = new PrefsIntegerProperty();
public static int getFontSize() {
return fontSize.get();
}
public static void setFontSize(int fontSize) {
Options.fontSize.set(Math.min(Math.max(fontSize, MIN_FONT_SIZE), MAX_FONT_SIZE));
}
public static IntegerProperty fontSizeProperty() {
return fontSize;
}
// 'markdownExtensions' property
private static final PrefsStringsProperty markdownExtensions = new PrefsStringsProperty();
public static String[] getMarkdownExtensions() {
return markdownExtensions.get();
}
public static void setMarkdownExtensions(String[] markdownExtensions) {
Options.markdownExtensions.set(markdownExtensions);
}
public static ObjectProperty<String[]> markdownExtensionsProperty() {
return markdownExtensions;
}
// 'showLineNo' property
private static final PrefsBooleanProperty showLineNo = new PrefsBooleanProperty();
public static boolean isShowLineNo() {
return showLineNo.get();
}
public static void setShowLineNo(boolean showLineNo) {
Options.showLineNo.set(showLineNo);
}
public static BooleanProperty showLineNoProperty() {
return showLineNo;
}
// 'showWhitespace' property
private static final PrefsBooleanProperty showWhitespace = new PrefsBooleanProperty();
public static boolean isShowWhitespace() {
return showWhitespace.get();
}
public static void setShowWhitespace(boolean showWhitespace) {
Options.showWhitespace.set(showWhitespace);
}
public static BooleanProperty showWhitespaceProperty() {
return showWhitespace;
}
}
| 31.460432 | 94 | 0.697233 |
5d10b41271e6c78054f53f152fb796bcc733f740 | 2,399 | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.common;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.infra.Blackhole;
/**
* Microbenchmarks for matching media types.
*/
public class MediaTypesBenchmark {
private static final MediaTypeSet MEDIA_TYPES = new MediaTypeSet(
MediaType.create("application", "grpc"), MediaType.create("application", "grpc+proto"));
private static final MediaType GRPC_MEDIA_TYPE = MediaType.create("application", "grpc");
private static final MediaType NOT_GRPC_MEDIA_TYPE = MediaType.create("application", "json");
private static final MediaType GRPC_MEDIA_TYPE_WITH_PARAMS =
MediaType.parse("application/grpc; charset=utf-8; q=0.9");
private static final MediaType NOT_GRPC_MEDIA_TYPE_WITH_PARAMS =
MediaType.parse("application/json; charset=utf-8; q=0.9");
@Benchmark
public void simpleMatch(Blackhole bh) {
bh.consume(MEDIA_TYPES.match(GRPC_MEDIA_TYPE));
}
@Benchmark
public void simpleNotMatch(Blackhole bh) {
bh.consume(MEDIA_TYPES.match(NOT_GRPC_MEDIA_TYPE));
}
@Benchmark
public void complexMatch(Blackhole bh) {
bh.consume(MEDIA_TYPES.match(GRPC_MEDIA_TYPE_WITH_PARAMS));
}
@Benchmark
public void complexNotMatch(Blackhole bh) {
bh.consume(MEDIA_TYPES.match(NOT_GRPC_MEDIA_TYPE_WITH_PARAMS));
}
@Benchmark
public void all(Blackhole bh) {
// Do all matches to reduce branch predictor accuracy.
bh.consume(MEDIA_TYPES.match(GRPC_MEDIA_TYPE));
bh.consume(MEDIA_TYPES.match(NOT_GRPC_MEDIA_TYPE));
bh.consume(MEDIA_TYPES.match(GRPC_MEDIA_TYPE_WITH_PARAMS));
bh.consume(MEDIA_TYPES.match(NOT_GRPC_MEDIA_TYPE_WITH_PARAMS));
}
}
| 34.768116 | 100 | 0.725719 |
a73c56cf6a2a6a586370f73030c14b3e861f1471 | 8,025 | /*
* ==========================================================================
* Copyright (C) 2019-2021 HCL America, Inc. ( http://www.hcl.com/ )
* 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.hcl.domino.misc;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Optional;
/**
* This class contains utility methods for dealing with {@link INumberEnum}
* Domino enums.
*
* @author Jesse Gallagher
*/
public enum DominoEnumUtil {
;
/**
* Converts the provided collection of number-backed enum values to a bitfield
* numerical value.
*
* @param <N> the boxed primitive type that backs the enum
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param values a collection of enum values to convert to a bitfield
* @return a boxed primitive value containing the bitfield
*/
@SuppressWarnings("unchecked")
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> N toBitField(final Class<T> clazz,
final Collection<T> values) {
Long result = Long.valueOf(0);
if (values != null) {
for (final T enumVal : values) {
result |= enumVal.getLongValue();
}
}
// Boil the value down to the right size
final Class<N> numberClass = (Class<N>) clazz.getEnumConstants()[0].getValue().getClass();
if (numberClass.equals(Byte.class)) {
return (N) Byte.valueOf(result.byteValue());
} else if (numberClass.equals(Short.class)) {
return (N) Short.valueOf(result.shortValue());
} else if (numberClass.equals(Integer.class)) {
return (N) Integer.valueOf(result.intValue());
} else {
return (N) result;
}
}
/**
* Given a Domino number-style enum, returns the enum constant for the provided
* <code>int</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link Optional} describing the corresponding enum value, or an
* empty one if none match
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> Optional<T> valueOf(final Class<T> clazz, final int value) {
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if (enumValue == value) {
return Optional.of(enumVal);
}
}
return Optional.empty();
}
/**
* Given a Domino number-style enum, returns the enum constant for the provided
* <code>long</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link Optional} describing the corresponding enum value, or an
* empty one if none match
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> Optional<T> valueOf(final Class<T> clazz, final long value) {
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if (enumValue == value) {
return Optional.of(enumVal);
}
}
return Optional.empty();
}
/**
* Given a Domino number-style enum, returns the enum constant for the provided
* <code>Number</code>
*
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link Optional} describing the corresponding enum value, or an
* empty one if none match
*/
public static <T extends INumberEnum<?>> Optional<T> valueOf(final Class<T> clazz, final Number value) {
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if (enumValue == value.longValue()) {
return Optional.of(enumVal);
}
}
return Optional.empty();
}
/**
* Given a Domino number-style enum, returns the enum constant for the provided
* <code>short</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link Optional} describing the corresponding enum value, or an
* empty one if none match
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> Optional<T> valueOf(final Class<T> clazz,
final short value) {
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if (enumValue == value) {
return Optional.of(enumVal);
}
}
return Optional.empty();
}
/**
* Given a Domino number-style bitfield enum, returns the matching enum
* constants for the provided
* <code>int</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link EnumSet} of matching enum values
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> EnumSet<T> valuesOf(final Class<T> clazz, final int value) {
final EnumSet<T> result = EnumSet.noneOf(clazz);
final long val = value;
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if ((val & enumValue) == enumValue) {
result.add(enumVal);
}
}
return result;
}
/**
* Given a Domino number-style bitfield enum, returns the matching enum
* constants for the provided
* <code>long</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link EnumSet} of matching enum values
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> EnumSet<T> valuesOf(final Class<T> clazz, final long value) {
final EnumSet<T> result = EnumSet.noneOf(clazz);
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if ((value & enumValue) == enumValue) {
result.add(enumVal);
}
}
return result;
}
/**
* Given a Domino number-style bitfield enum, returns the matching enum
* constants for the provided
* <code>short</code>
*
* @param <N> subclass of {@link Number} to store enum values
* @param <T> the number-backed enum type
* @param clazz the number-backed enum class
* @param value the value to convert
* @return an {@link EnumSet} of matching enum values
*/
public static <N extends Number, T extends Enum<T> & INumberEnum<N>> EnumSet<T> valuesOf(final Class<T> clazz,
final short value) {
final EnumSet<T> result = EnumSet.noneOf(clazz);
final long val = value;
for (final T enumVal : clazz.getEnumConstants()) {
final long enumValue = enumVal.getLongValue();
if ((val & enumValue) == enumValue) {
result.add(enumVal);
}
}
return result;
}
} | 36.981567 | 132 | 0.635514 |
cc8e64e6cfd84653ba1f6680fea05da05cf61d25 | 220 | /**
* Author: markliu
* Time : 16-9-3 下午4:43
*/
public class ClientTest {
public static void main(String[] args) {
Account account = new CurrentAccount();
account.handlerTemplate("test", "111111", 12000);
}
}
| 18.333333 | 51 | 0.659091 |
6d7f5d877a00e2802a467dceabb942ffe213a041 | 3,446 | /*
* __ .__ .__ ._____.
* _/ |_ _______ __|__| ____ | | |__\_ |__ ______
* \ __\/ _ \ \/ / |/ ___\| | | || __ \ / ___/
* | | ( <_> > <| \ \___| |_| || \_\ \\___ \
* |__| \____/__/\_ \__|\___ >____/__||___ /____ >
* \/ \/ \/ \/
*
* Copyright (c) 2006-2011 Karsten Schmidt
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
package toxi.physics3d.behaviors;
import toxi.geom.Vec3D;
import toxi.physics3d.VerletParticle3D;
public class AttractionBehavior3D implements ParticleBehavior3D {
protected Vec3D attractor;
protected float attrStrength;
protected float radius, radiusSquared;
protected float strength;
protected float jitter;
protected float timeStep;
public AttractionBehavior3D(Vec3D attractor, float radius, float strength) {
this(attractor, radius, strength, 0);
}
public AttractionBehavior3D(Vec3D attractor, float radius, float strength,
float jitter) {
this.attractor = attractor;
this.strength = strength;
this.jitter = jitter;
setRadius(radius);
}
public void apply(VerletParticle3D p) {
Vec3D delta = attractor.sub(p);
float dist = delta.magSquared();
if (dist < radiusSquared) {
Vec3D f = delta.normalizeTo((1.0f - dist / radiusSquared))
.jitter(jitter).scaleSelf(attrStrength);
p.addForce(f);
}
}
public void configure(float timeStep) {
this.timeStep = timeStep;
setStrength(strength);
}
/**
* @return the attractor
*/
public Vec3D getAttractor() {
return attractor;
}
/**
* @return the jitter
*/
public float getJitter() {
return jitter;
}
/**
* @return the radius
*/
public float getRadius() {
return radius;
}
/**
* @return the strength
*/
public float getStrength() {
return strength;
}
/**
* @param attractor
* the attractor to set
*/
public void setAttractor(Vec3D attractor) {
this.attractor = attractor;
}
/**
* @param jitter
* the jitter to set
*/
public void setJitter(float jitter) {
this.jitter = jitter;
}
public void setRadius(float r) {
this.radius = r;
this.radiusSquared = r * r;
}
/**
* @param strength
* the strength to set
*/
public void setStrength(float strength) {
this.strength = strength;
this.attrStrength = strength * timeStep;
}
}
| 26.921875 | 80 | 0.588218 |
7c3e3300243e0bfe7475ea226b7e0cb49078cd37 | 17,325 | /*
* Copyright 2011 University of Southern California
*
* 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 tratz.pos.featgen;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import tratz.featgen.InitException;
import tratz.featgen.fer.ClosedClassFER;
import tratz.featgen.fer.WordNetPosTypesFER;
import tratz.parse.types.Token;
import tratz.types.ChecksumMap;
/**
* Default feature generator for English POS tagging.
* This isn't implemented in a very efficient manner.
* In the future it will make sense to cache things. Also there could be some room for generalization, though that will likely hurt running time
*
*/
public class DefaultEnglishPosFeatureGenerator implements PosFeatureGenerator, Serializable {
public static final long serialVersionUID = 1;
private transient WordNetPosTypesFER mDerived;
private transient ClosedClassFER mClosedClass;
//private Map<String, String> mFeatMap = new HashMap<String, String>();
private ChecksumMap<String> mFeatMap = new ChecksumMap<String>();//HashMap<String, String>();
//private ObjectIntHashMap mFeatMap = new ObjectIntHashMap();
public DefaultEnglishPosFeatureGenerator() throws Exception {
int minOccurrence = 1;//minOccurrenceS == null ? 1 : Integer.parseInt(minOccurrenceS);
int maxDepth = Integer.MAX_VALUE;//maxDepthS == null ? Integer.MAX_VALUE : Integer.parseInt(maxDepthS);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("data/brownClusters200.gz"))));
String line = null;
byte lastByte = 0;
String lastByteString = "";
String lastOne = null;
while((line = reader.readLine()) != null) {
String[] split = line.split("\\t+");
String path = split[0];
String token = split[1];
int occurrences = Integer.parseInt(split[2]);
if(occurrences >= minOccurrence) {
String blarg = path.substring(0, Math.min(path.length(), maxDepth));
if(!blarg.equals(lastOne)) {
lastOne = blarg;
lastByte++;
lastByteString = Byte.toString(lastByte);
}
//mFeatMap.put(token, lastByteString);
mFeatMap.put(token, lastByte);
}
}
reader.close();
}
catch(IOException ioe) {
throw new InitException(ioe);
}
mDerived = new WordNetPosTypesFER();
mClosedClass = new ClosedClassFER();
}
@Override
public void init() {
}
private String getPos(List<Token> tokens, int location) {
return (location >= 0) ? tokens.get(location).getPos() : "Þ";
}
private String getBC(String s) {
String bc;
if(s=="Þ") {
bc = "-2";
}
else {
String numericized = DIGITS.reset(s).replaceAll("ƞ");
if(!mFeatMap.containsKey(numericized)) {
String lower = numericized.toLowerCase();
if(!mFeatMap.containsKey(lower)) {
bc = "-1";
}
else {
int val = mFeatMap.get(lower);
bc = Integer.toString(val);
}
}
else {
int val = mFeatMap.get(numericized);
bc = Integer.toString(val);
}
}
return bc;
}
private String getForm(List<Token> tokens, int index) {
return tokens.get(index).getText();
}
private transient Matcher NUM_DASH_NUM = null;
private transient Matcher HAS_DIGIT = null;
private transient Matcher NUMBER_COMMA_ETC = null;
private transient Matcher DIGITS = null;
private transient Matcher HAVE_VERB = null;
// Don't be square ⽅
// ⼾⼿⽀⽁⽂
@Override
public Set<String> getFeats(final List<Token> tokens, final int index) {
if(NUM_DASH_NUM == null) {
mDerived = new WordNetPosTypesFER();
mClosedClass = new ClosedClassFER();
NUM_DASH_NUM = Pattern.compile("[0-9]+\\-[0-9]+").matcher("");
HAS_DIGIT = Pattern.compile(".*[0-9].*").matcher("");
NUMBER_COMMA_ETC = Pattern.compile("[0-9,\\.:]+").matcher("");
DIGITS = Pattern.compile("[0-9]").matcher("");
HAVE_VERB = Pattern.compile("having|have|had|has|'ve|'d").matcher("");
}
Set<String> f = new HashSet<String>();
synchronized(this) {
int numTokens = tokens.size();
String wl4 = (index > 3) ? getForm(tokens,index-4) : "Þ";
String wl3 = (index > 2) ? getForm(tokens,index-3) : "Þ";
String wl2 = (index > 1) ? getForm(tokens,index-2) : "Þ";
String wl1 = (index > 0) ? getForm(tokens,index-1) : "Þ";
String w0 = getForm(tokens,index);
String wr1 = (index < numTokens-1) ? getForm(tokens,index+1) : "Þ";
String wr2 = (index < numTokens-2) ? getForm(tokens,index+2) : "Þ";
String wr3 = (index < numTokens-3) ? getForm(tokens,index+3) : "Þ";
String wr4 = (index < numTokens-4) ? getForm(tokens,index+4) : "Þ";
/*if(index <= 0) w0 = w0.toLowerCase();*/
if(index == 0) w0 = w0.toLowerCase();
if(index == 1) wl1 = wl1.toLowerCase();
if(index == 2) wl2 = wl2.toLowerCase();
if(index == 3) wl3 = wl3.toLowerCase();
if(index == 4) wl4 = wl4.toLowerCase();
boolean es0 = (w0.endsWith("s")||w0.endsWith("S"));
String bcl4, bcl3, bcl2, bcl1, bc0, bcr1, bcr2, bcr3, bcr4;
bcl4 = getBC(wl4);bcl3 = getBC(wl3);bcl2 = getBC(wl2);bcl1 = getBC(wl1);
bc0 = getBC(w0);
bcr1 = getBC(wr1);bcr2 = getBC(wr2);bcr3 = getBC(wr3);bcr4 = getBC(wr4);
//if(allUpperCase(w0)) {f.add("⻑"); f.add("⻑"+bc0);};
String pl4 = (index > 3) ? getPos(tokens, index-4) : "Þ";
String pl3 = (index > 2) ? getPos(tokens, index-3) : "Þ";
String pl2 = (index > 1) ? getPos(tokens, index-2) : "Þ";
String pl1 = (index > 0) ? getPos(tokens, index-1) : "Þ";
Token pv = null;
Token preIN = null;
//boolean hasPreThat = false;
for(int i = index-1; i >= 0; i--) {
Token t = tokens.get(i);
if(t.getPos().startsWith("VB") || t.getPos().equals("MD")) {
pv = t; break;
}
else if(t.getPos().equals("IN")) {
preIN = t;
//if(t.getText().equalsIgnoreCase("that")) {
//hasPreThat = true;
//}
}
}
if(wr1.equals(".") || wr1.equals(",") || wr1.equals(";") || wr1.equals(":")) {
// uninterrupted (verbwise) WH-term or IN
Token whOrIn = null;
for(int i = index-1; i >= 0; i--) {
Token t = tokens.get(i);
String pos = t.getPos();
if(pos.startsWith("VB")) {
break;
}
else if(pos.equals("IN") || pos.startsWith("W")) {
whOrIn = t;
break; // search interrupted
}
}
if(whOrIn != null){
f.add("preWhOrIn");
f.add("⺺⺺"+whOrIn.getText().toLowerCase());
f.add("⺺⺺"+whOrIn.getText().toLowerCase()+"⺺" + wr1);
}
}
// f.add("⻟"+(preWRB==null?"null":"WRB+"+bc0));
f.add((preIN==null?"null":preIN.getText().toLowerCase())+"⻠"+bc0);
Token preTwoCommas = null;
Token postTwoCommas = null;
if(index > 1) {
Token prev = tokens.get(index-2);
if(prev.getText().equals(",")) {
for(int i = index-3; i >= 1; i--) {
Token t = tokens.get(i);
if(t.getText().equals(",")) {
preTwoCommas = tokens.get(i-1);
postTwoCommas = tokens.get(i+1);
break;
}
}
}
}
if(preTwoCommas != null) {
f.add(getBC(preTwoCommas.getText())+"⼗"+bc0);
f.add(postTwoCommas.getText().startsWith("wh")+"⼕"+bc0);
}
boolean pnull = pv==null;
String pvText = pnull ? "ƥ" : pv.getText().toLowerCase();
String pvPos = pnull ? "ƥ": pv.getPos();
f.add(pvText+"⼔"+bc0);
f.add(pvText+"⼓"+w0);
f.add(pvPos+"⼒"+bc0);
f.add(pvPos+"⼑"+bc0+"+"+bcr1);
// this is not exactly what was intended
f.add("⼐"+(pnull?"ƥ":HAVE_VERB.reset(pvText).matches()+"+"+bc0));
f.add(pvPos+"⼏"+pl1+"+"+bc0);
Token prevVerb2 = null;
if(pv != null) {
for(int i = pv.getIndex()-2; i >= 0; i--) {
Token t = tokens.get(i);
if(t.getPos().startsWith("VB") || t.getPos().equals("MD")) {
prevVerb2 = t; break;
}
}
//f.add("⽅"+(prevVerb2==null?"null":prevVerb2.getPos()+","+pv.getPos())+"+"+bc0);
//f.add("⽄"+(prevVerb2==null?"null":prevVerb2.getText()+","+pv.getPos())+"+"+bc0);
f.add("⼌"+(prevVerb2==null?"null":prevVerb2.getPos())+"+"+bc0);
//f.add("⼋"+(prevVerb2==null?"null":prevVerb2.getText().toLowerCase())+"+"+bc0);
}
if(pv != null && (pl1.equals("CC") || pl1.equals(","))) {
f.add(pvPos+"⼜"+bc0); // allow help from both CC and , s... probably not too useful
}
// Ends in s combinations
f.add("⻚"+bc0+es0+bcr1);
f.add("⻛"+bc0+es0+pl1);
f.add("⻜"+bc0+es0+wl1);
f.add("⻝"+bc0+es0+wr1);
f.add("⻡"+es0+bcr1);
f.add("⻣"+pl1+es0+bcr1);
f.add(es0+"⻢"+wr1);
f.add(wl1+"⻤"+es0+"+"+wr1);
// for 54
if(es0) {
// NNS to left should make NNS unlikely
//f.add(wl1+"⻤⻤"+bcr1);
//f.add(pl1+"⻢⻢"+pl2);
//f.add(pl1+"⻢"+pl2 + "⻢"+pl3);
//f.add(bcr1+"⻚⻚"+bcr2);
Token pdt = null; // previous uninterrupted determiner
for(int i = index-1; i >= 0; i--) {
Token t = tokens.get(i);
String pos = t.getPos();
if(pos.equals("DT")) {
pdt = t;
break;
}
else if(!(pos.startsWith("N") || pos.startsWith("J") || pos.startsWith("R") || pos.startsWith("C"))) {
break; // search interrupted
}
}
String pdt_text = pdt == null ? "n" : pdt.getText().toLowerCase();
f.add(pdt_text+"⻚");
// check out the previous determiner and intermediate words, may preclude plural word
if(pdt_text.equals("a") || pdt_text.equals("an") || pdt_text.equals("this") || pdt_text.equals("that")) {
f.add("singpdt⻚");
}
f.add("⻢"+pvPos);
f.add("⻢⻢"+(prevVerb2==null?"null":prevVerb2.getPos()));
f.add("⻢⻢⻢"+pl1);
// followed by a comma & ambiguous over prev 3 words
// similar if followed by period
// next word also ends with 's'
// preceded by 'and' + prev verb POS
if(preTwoCommas != null) {
f.add(getBC(preTwoCommas.getText())+"⼗⻢"+bc0);
f.add(postTwoCommas.getText().startsWith("wh")+"⼕⻢"+bc0);
}
}
f.add(wl1+"⻬"+bc0);
f.add(pl1+"⻭"+bc0+"+"+bcr1);
f.add(pl2+"⻮"+bc0+"+"+bcr1);
f.add(pl3+"⻯"+bc0+"+"+bcr1);
f.add(pl2+"⻰"+pl1+"+"+bc0);
// useful methinks...
f.add(wl2+"⻱"+pl1);
f.add(wl2+"⻲"+pl1+"+"+bc0);
// For 13
f.add(w0+"⻳"+bcr1); // about six
f.add(wl2+"⼈"+bcl1+"+"+bc0);
f.add(wl1+"⼉"+bc0+"+"+wr1);
f.add(wl1+"⼊"+bc0+"+"+bcr1);
// For 12
f.add(wl2+"⼙"+wl1+"+"+bc0);
// what about wl2+pl1+bc0 ?
f.add(wl2+"⼚"+wl1+"+"+bc0+"+"+bcr1);
f.add(wl2+"⼛"+pl1+"+"+bc0+"+"+bcr1);
if((pl1.equals("MD") || pl2.equals("MD") || pl3.equals("MD") || pl4.equals("MD"))
&& (!pl1.startsWith("VB") && !pl2.startsWith("VB") && !pl3.startsWith("VB") && !pl4.startsWith("VB"))) {
f.add("⺺"+bc0); //
f.add("⺺t"); //
}
Set<String> wl1ders = mDerived.getProductions(wl1, "", new HashSet<String>());
Set<String> w0ders = mDerived.getProductions(w0, "", new HashSet<String>());
Set<String> wr1ders = mDerived.getProductions(wr1, "", new HashSet<String>());
Set<String> wr2ders = mDerived.getProductions(wr2, "", new HashSet<String>());
Set<String> wr3ders = mDerived.getProductions(wr3, "", new HashSet<String>());
mClosedClass.getProductions(wl1, "", wl1ders);
mClosedClass.getProductions(w0, "", w0ders);
mClosedClass.getProductions(wr1, "", wr1ders);
mClosedClass.getProductions(wr2, "", wr2ders);
mClosedClass.getProductions(wr3, "", wr3ders);
List<String> dev = new ArrayList<String>(w0ders);
Collections.sort(dev);
int devSize = dev.size();
for(int i = 0; i < devSize; i++) {
String s1 = dev.get(i);
for(int j = i+1; j < devSize; j++) {
f.add("⺶"+s1+","+dev.get(j));
}
}
//⺸⺹⼦⼧⼨⼩⼪⼫⼬⼭⼮⼯
for(String wl1d : wl1ders) f.add("⺷"+wl1d);
for(String w0d : w0ders) f.add("⺶"+w0d);
for(String wr1d : wr1ders) f.add("⺵"+wr1d);
for(String wr2d : wr2ders) f.add("⺴"+wr2d);
for(String wr3d : wr3ders) f.add("⺴⺵"+wr3d);
// AFFIX FEATURES
final int w0length = w0.length();
final int prefixDepth = Math.min(5, w0length);
for(int i = 1; i < prefixDepth; i++) {
f.add("⺭"+w0.substring(0, i));
}
final int suffixDepth = Math.min(9, w0length);
for(int i = suffixDepth; i >= 0; i--) {
f.add("⺬"+w0.substring(w0length-i, w0length));
}
f.add(Boolean.toString(w0.endsWith("ed") || w0.endsWith("n")));
char firstChar = ' ';
firstChar = w0.length() > 0 ? w0.charAt(0) : ' ';
boolean isUppercase = Character.isUpperCase(firstChar);
f.add("⺫"+isUppercase); //
f.add("⺪"+allLowerCase(w0)); //
f.add("⺩"+allUpperCase(w0)); //
int dashIndex = w0.lastIndexOf("-");
f.add("⺦"+(dashIndex > -1));
f.add("⺢"+w0.contains("."));
f.add("⺨"+NUM_DASH_NUM.reset(w0).matches());
f.add("⺡"+HAS_DIGIT.reset(w0).matches());
f.add("⺠"+(isUppercase&&es0));
f.add("⺟"+NUMBER_COMMA_ETC.reset(wr1).matches());
f.add("⺞"+NUMBER_COMMA_ETC.reset(wr2).matches());
f.add("⺝"+Character.isUpperCase(wl1.length() > 0 ? wl1.charAt(0) : 'n'));
if(dashIndex > -1) {
f.add("⺜"+w0.substring(0, dashIndex));
if(dashIndex < w0.length()-1) {
String dashString = w0.substring(dashIndex+1);
String endDashBC = getBC(dashString);
f.add(endDashBC+"⺛"+bc0);
f.add(endDashBC+"⺛"+bc0+"+"+bcr1);
}
int firstDash = w0.indexOf('-');
if(firstDash > -1 && firstDash < w0.length()-1) {
String preDash = w0.substring(0, dashIndex);
f.add("⼥"+preDash); // duplicate feat! should delete!
}
if(firstDash != dashIndex) {
int secondDash = w0.indexOf('-',firstDash+1);
//feats.add("inDash:"+secondDash);
}
}
Token lastToken = tokens.get(numTokens-1);
if(lastToken.getText().equals(".")) f.add("l.");
if(lastToken.getText().equals("!")) f.add("l!");
if(lastToken.getText().equals("?")) f.add("l?");
// Unigram POSes
f.add("⺼"+pl4);f.add("⺻"+pl3);f.add("⺽"+pl2);f.add("⻁"+pl1);
// Ambiguous to left POS
f.add("⼝"+pl1); f.add("⼝"+pl2);
// Bigram POS
f.add("⺮"+pl2+"|"+pl1);
// new!
//f.add("⺮"+pl3+"|"+pl2+"|"+pl1);
// What about pl2+pl3?, what about pl3+pl2+pl1???
if(w0.equalsIgnoreCase("that")) {
//f.add("⻄⻄"+wl4);f.add("⻄⻄"+wl3);f.add("⻄⻄"+wl2);f.add("⻄⻄"+wl1);
}
// Unigram Words
f.add("⻄"+wl3);f.add("⻅"+wl2);f.add("⻆"+wl1);
f.add("⻇"+w0);
f.add("⻉"+wr3);f.add("⻊"+wr2);f.add("⻋"+wr1);
// ambiguous unigram words (new.. may be a bad thing)
//f.add("⻉⻋"+wr1);f.add("⻉⻋"+wr2);f.add("⻉⻋"+wr3);
// Unigram BCs
f.add("⻏"+bcl4);f.add("⻓"+bcl3);f.add("⻔"+bcl2);f.add("⻙"+bcl1);
f.add("⻑"+bc0);
f.add("⻒"+bcr4);f.add("⻘"+bcr3);f.add("⻕"+bcr2);f.add("⻗"+bcr1);
// Ambiguous (2 in front, 2 in back)
f.add("⻩"+bcr1);f.add("⻩"+bcr2);
f.add("⻪"+bcl2);f.add("⻪"+bcl1);
// Ambiguous (3 in front, 3 in back)
f.add("⻌"+bcr1);f.add("⻌"+bcr2);f.add("⻌"+bcr3);
f.add("⻍"+bcl1);f.add("⻍"+bcl2);f.add("⻍"+bcl3);
// Ambiguous (4 in front, 4 in back) had no impact
// Bigram Words
// Consecutive
f.add(wl2+"⺎"+wl1);
f.add(wl1+"⺏"+w0);
f.add(w0+"⺑"+wr1);
f.add(wr1+"⺒"+wr2);
// Sandwich
f.add(wl1+"⺐"+wr1);
// Bigram BCs
// Consecutive
f.add(bcl2+"⻥"+bcl1);
f.add(bcl1+"⻦"+bc0);
f.add(bc0+"⻧"+bcr1);
f.add(bcr1+"⻨"+bcr2);
// Sandwich
f.add(bcl1+"⻫"+bcr1);
// Ambiguous (window=2)
// Readded as a test
//f.add("⻩"+bc0+"+"+bcr1);f.add("⻩"+bc0+"+"+bcr2);
//f.add("⻪"+bcl2+"+"+bc0);f.add("⻪"+bcl1+"+"+bc0);
// Ambiguous (window=3) (noticeable slowdown in training time)
//f.add("⻌"+bc0+"+"+bcr1);f.add("⻌"+bc0+"+"+bcr2);f.add("⻌"+bc0+"+"+bcr3);
//f.add("⻍"+bc0+"+"+bcl1);f.add("⻍"+bc0+"+"+bcl2);f.add("⻍"+bc0+"+"+bcl3);
// Trigram Words
// Consective
f.add(wl2+"⺓"+wl1+"|"+w0);
f.add(wl1+"⺕"+w0+"|"+wr1);
f.add(w0+"⺙"+wr1+"|"+wr2);
// Skips
f.add(wl2+"⺔"+wl1+"|"+wr1);
f.add(wl1+"⺘"+wr1+"|"+wr2);
// Trigram BCs
// Consective
f.add(bcl2+"⼟"+bcl1+"+"+bc0);
f.add(bcl1+"⼡"+bc0+"+"+bcr1);
f.add(bc0+"⼢"+bcr1+"+"+bcr2);
// Skips
f.add(bcl2+"⼣"+bcl1+"+"+bcr1);
f.add(bcl1+"⼤"+bcr1+"+"+bcr2);
// TEST
//f.add("⼤"+bcl2+"+"+bcl1+"+"+bcr1+"+"+bcr2);
//f.add("⼢⼢"+bcr1+"+"+bcr2+"+"+bcr3);
// for 53
//f.add(wr1+"⺒⺒"+wr2.substring(wr2.length()-Math.min(wr2.length(), 3)));
//f.add(wr1+"⺒⼤"+wr2.substring(0, Math.min(wr2.length(), 3)));
}
return f;
}
private boolean allUpperCase(String s) {
final int len = s.length();
boolean allUpper = true;
for(int i = 0; i < len; i++) {
boolean isUpper = Character.isUpperCase(s.charAt(i));
if(!isUpper) {
allUpper = false;
break;
}
}
return allUpper;
}
private boolean allLowerCase(String s) {
final int len = s.length();
boolean allLower = true;
for(int i = 0; i < len; i++) {
boolean isLower = Character.isLowerCase(s.charAt(i));
if(!isLower) {
allLower = false;
break;
}
}
return allLower;
}
} | 31.272563 | 144 | 0.593131 |
52601a719060cc4398cd9e8f50b02796f3da23bd | 1,480 | /*
* Copyright (c) 2019, 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.micro.integrator.dataservices.core.test.util;
import org.wso2.micro.integrator.dataservices.core.engine.ParamValue;
import org.wso2.micro.integrator.dataservices.core.validation.ValidationContext;
import org.wso2.micro.integrator.dataservices.core.validation.ValidationException;
import org.wso2.micro.integrator.dataservices.core.validation.Validator;
/**
* Custom validator for checking if a given string length is odd.
*/
public class OddLengthValidator implements Validator {
public OddLengthValidator() { }
public void validate(ValidationContext context, String name,
ParamValue value) throws ValidationException {
if (value.getScalarValue().length() % 2 == 0) {
throw new ValidationException("The string length is not odd", name, value);
}
}
}
| 37 | 82 | 0.750676 |
bd67b220885c1aea2b5890f11df7543c48e87706 | 6,785 | /*
* (C) Copyright 2010-2018 Nuxeo (http://nuxeo.com/) 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.
* Contributors:
* Nuxeo - initial API and implementation
*/
package org.nuxeo.ecm.platform.types.localconfiguration;
import static org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfigurationConstants.UI_TYPES_CONFIGURATION_ALLOWED_TYPES_PROPERTY;
import static org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfigurationConstants.UI_TYPES_CONFIGURATION_DEFAULT_TYPE;
import static org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfigurationConstants.UI_TYPES_CONFIGURATION_DENIED_TYPES_PROPERTY;
import static org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfigurationConstants.UI_TYPES_CONFIGURATION_DENY_ALL_TYPES_PROPERTY;
import static org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfigurationConstants.UI_TYPES_DEFAULT_TYPE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.PropertyException;
import org.nuxeo.ecm.core.api.localconfiguration.AbstractLocalConfiguration;
import org.nuxeo.ecm.platform.types.SubType;
/**
* Default implementation of {@code UITypesConfiguration}.
*
* @author <a href="mailto:[email protected]">Thomas Roger</a>
*/
public class UITypesConfigurationAdapter extends AbstractLocalConfiguration<UITypesConfiguration>
implements UITypesConfiguration {
private static final Log log = LogFactory.getLog(UITypesConfigurationAdapter.class);
protected DocumentRef documentRef;
protected List<String> allowedTypes;
protected List<String> deniedTypes;
protected boolean denyAllTypes;
protected boolean canMerge = true;
protected String defaultType;
public UITypesConfigurationAdapter(DocumentModel doc) {
documentRef = doc.getRef();
allowedTypes = getTypesList(doc, UI_TYPES_CONFIGURATION_ALLOWED_TYPES_PROPERTY);
deniedTypes = getTypesList(doc, UI_TYPES_CONFIGURATION_DENIED_TYPES_PROPERTY);
defaultType = getDefaultType(doc);
denyAllTypes = getDenyAllTypesProperty(doc);
if (denyAllTypes) {
canMerge = false;
}
}
protected List<String> getTypesList(DocumentModel doc, String property) {
String[] types;
try {
types = (String[]) doc.getPropertyValue(property);
} catch (PropertyException e) {
return Collections.emptyList();
}
if (types == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(Arrays.asList(types));
}
protected boolean getDenyAllTypesProperty(DocumentModel doc) {
try {
Boolean value = (Boolean) doc.getPropertyValue(UI_TYPES_CONFIGURATION_DENY_ALL_TYPES_PROPERTY);
return Boolean.TRUE.equals(value);
} catch (PropertyException e) {
return false;
}
}
protected String getDefaultType(DocumentModel doc) {
String value = UI_TYPES_DEFAULT_TYPE;
try {
value = (String) doc.getPropertyValue(UI_TYPES_CONFIGURATION_DEFAULT_TYPE);
} catch (PropertyException e) {
log.debug("can't get default type for:" + doc.getPathAsString(), e);
}
return value;
}
@Override
public List<String> getAllowedTypes() {
return allowedTypes;
}
@Override
public List<String> getDeniedTypes() {
return deniedTypes;
}
@Override
public boolean denyAllTypes() {
return denyAllTypes;
}
@Override
public DocumentRef getDocumentRef() {
return documentRef;
}
@Override
public boolean canMerge() {
return canMerge;
}
@Override
public UITypesConfiguration merge(UITypesConfiguration other) {
if (other == null) {
return this;
}
// set the documentRef to the other UITypesConfiguration to continue
// merging, if needed
documentRef = other.getDocumentRef();
if (allowedTypes.isEmpty()) {
allowedTypes = Collections.unmodifiableList(new ArrayList<>(other.getAllowedTypes()));
}
List<String> dTypes = new ArrayList<>(this.deniedTypes);
dTypes.addAll(other.getDeniedTypes());
this.deniedTypes = Collections.unmodifiableList(dTypes);
denyAllTypes = other.denyAllTypes();
if (denyAllTypes) {
canMerge = false;
}
return this;
}
@Override
public Map<String, SubType> filterSubTypes(Map<String, SubType> allowedSubTypes) {
if (denyAllTypes) {
return Collections.emptyMap();
}
if (allowedTypes.isEmpty() && deniedTypes.isEmpty()) {
return allowedSubTypes;
}
Map<String, SubType> filteredAllowedSubTypes = new HashMap<>(allowedSubTypes);
filteredAllowedSubTypes.keySet()
.removeIf(subTypeName -> deniedTypes.contains(subTypeName)
|| !allowedTypes.isEmpty() && !allowedTypes.contains(subTypeName));
return filteredAllowedSubTypes;
}
@Override
public Collection<String> filterSubTypes(Collection<String> allowedSubTypes) {
if (denyAllTypes) {
return Collections.emptyList();
}
if (allowedTypes.isEmpty() && deniedTypes.isEmpty()) {
return allowedSubTypes;
}
List<String> filteredAllowedSubTypes = new ArrayList<>(allowedSubTypes);
filteredAllowedSubTypes.removeIf(subTypeName -> deniedTypes.contains(subTypeName)
|| !allowedTypes.isEmpty() && !allowedTypes.contains(subTypeName));
return filteredAllowedSubTypes;
}
/*
* (non-Javadoc)
* @see org.nuxeo.ecm.platform.types.localconfiguration.UITypesConfiguration# getDefaultType()
*/
@Override
public String getDefaultType() {
return defaultType;
}
}
| 33.423645 | 139 | 0.690789 |
64b3edc95c7a13d57bd3e2bf843a32f41ec7e7c4 | 1,747 | package nc.unc.cs.services.communal.controllers.mock.price.tax.correct;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import nc.unc.cs.services.communal.controllers.mock.price.tax.PropertyTaxValueParent;
import nc.unc.cs.services.communal.controllers.payloads.CreationPropertyTaxValue;
import nc.unc.cs.services.communal.entities.PropertyTaxValue;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
class AddPropertyTaxValueTest extends PropertyTaxValueParent {
@Test
void addPropertyTaxValue() throws Exception {
final CreationPropertyTaxValue creationPropertyTaxValue = this.createCreationPropertyTaxValue();
final PropertyTaxValue propertyTaxValue = this.createPropertyTaxValue();
System.out.println(creationPropertyTaxValue);
when(propertyTaxService.addPropertyTaxValue(creationPropertyTaxValue))
.thenReturn(ResponseEntity.ok(propertyTaxValue));
this.mockMvc
.perform(
post(PROPERTY_TAX_VALUE_CONTROLLER_MAPPING)
.contentType("application/json")
.content(objectMapper.writeValueAsString(creationPropertyTaxValue)))
.andDo(print())
.andExpect(status().isOk())
.andExpect(
content()
.string(containsString(this.objectMapper.writeValueAsString(propertyTaxValue))));
}
}
| 43.675 | 100 | 0.785346 |
70fcd5f37fa316a33f768b9de76b1ab7c3701b27 | 6,759 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.api.module.rtp;
import io.github.nucleuspowered.nucleus.api.module.rtp.kernel.RTPKernel;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Allows for the customisation of RTP selection routines.
*/
public interface NucleusRTPService {
/**
* Gets the {@link RTPOptions} that contains the current
* rtp configuration for a default world.
*
* @return The {@link RTPOptions}
*/
default RTPOptions options() {
return options(null);
}
/**
* Gets the {@link RTPOptions} that contains the current
* rtp configuration for the specified world.
*
* @param world The {@link WorldProperties}, or {@code null} for defaults.
* @return The {@link RTPOptions}
*/
RTPOptions options(@Nullable WorldProperties world);
/**
* Gets the {@link RTPOptions} that contains the current
* rtp configuration, but in builder format.
*
* <p>Changes in the builder do not affect the configuration,
* this is for overriding in specific circumstances.</p>
*
* @return The {@link RTPOptions}
*/
RTPOptions.Builder optionsBuilder();
/**
* Gets the {@link RTPKernel} that Nucleus' RTP will use.
*
* <p>This is set by the rtp config, using the kernel's ID.</p>
*
* @return The {@link RTPKernel}
*/
RTPKernel getDefaultKernel();
/**
* Uses the default RTP kernel (from {@link #getDefaultKernel()} to find a
* random location, given the provided {@link RTPOptions}.
*
* <p>Note that this may fail if the search times out. This does not
* indicate a failing routine.</p>
*
* <p>A source of confusion is that this method works in exactly the same
* way as the rtp command. <strong>It does not.</strong> The RTP command
* makes attempts over multiple ticks to keep the server running while
* increasing the chance of finding a suitable spot.</p>
*
* <p>This method makes <strong>one</strong> attempt at finding a
* suitable location. You may need to run this more than once.</p>
*
* @param currentLocation The current location to base the RTP off.
* @param world The world to warp to
* @param options The RTP options to use
* @return The location if one was found.
*/
default Optional<Location<World>> getLocation(@Nullable Location<World> currentLocation, World world, RTPOptions options) {
return getDefaultKernel().getLocation(currentLocation, world, options);
}
/**
* Gets the default {@link RTPKernel} used when executing
* a random teleport
*
* @param world The world to get the kernel for
* @return The kernel
*/
RTPKernel getKernel(WorldProperties world);
/**
* Gets the default {@link RTPKernel} used when executing
* a random teleport
*
* @param world The name of the world to get the kernel for
* @return The kernel
*/
RTPKernel getKernel(String world);
/**
* Registers a kernel for use in Nucleus.
*
* @param kernel The kernel.
*/
void registerKernel(RTPKernel kernel);
/**
* The RTP options to pass to the routines
*/
interface RTPOptions {
/**
* The maximum radius for the RTP.
*
* @return the max radius
*/
int maxRadius();
/**
* The minimum radius for the RTP.
*
* @return the min radius
*/
int minRadius();
/**
* The minimum height for the RTP. Must be greater than zero.
*
* @return The minimum height
*/
int minHeight();
/**
* The maximum height for the RTP. Must be greater than the min height.
*
* @return The maximum height.
*/
int maxHeight();
/**
* A set of biomes that RTP should not teleport a player into.
*
* @return The set of biomes
*/
Set<BiomeType> prohibitedBiomes();
interface Builder {
/**
* Sets the maximum radius for the RTP.
*
* @param max the max radius
* @return This builder, for chaining
*/
Builder setMaxRadius(int max);
/**
* Sets the minimum radius for the RTP.
*
* @param min the min radius
* @return This builder, for chaining
*/
Builder setMinRadius(int min);
/**
* Sets the minimum height for the RTP. Must be greater than zero.
*
* @param max the minimum height
* @throws IllegalArgumentException if the height is not acceptable
* @return This builder, for chaining
*/
Builder setMinHeight(int max) throws IllegalArgumentException;
/**
* Sets the maximum height for the RTP. Must be greater than zero.
*
* @param min the max height
* @throws IllegalArgumentException if the height to too high
* @return This builder, for chaining
*/
Builder setMaxHeight(int min) throws IllegalArgumentException;
/**
* Adds a {@link BiomeType} to the prohibited biomes set.
*
* @param biomeType The {@link BiomeType} to add.
* @return This builder, for chaining.
*/
Builder prohibitedBiome(BiomeType biomeType);
/**
* Sets this builder state from the specified {@link RTPOptions}
* @param options The optiosn
* @return This builder, for chaining
*/
Builder from(RTPOptions options);
/**
* Creates a {@link RTPOptions} from the state of this builder.
*
* @throws IllegalStateException if the builder is not in the correct state
* @return The {@link RTPOptions}
*/
RTPOptions build() throws IllegalStateException;
/**
* Resets this builder to the default state.
* @return This builder, for chaining
*/
Builder reset();
}
}
}
| 31.004587 | 127 | 0.58559 |
17da1fcacf976795a4f74a6012d6a5f033933170 | 5,338 | /**
* Copyright (c) 2021, OSChina ([email protected]).
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.gitee.kooder.gitee;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.gitee.kooder.core.Constants;
import com.gitee.kooder.models.Relation;
import java.util.Collections;
import java.util.Date;
/**
* @author zhanggx
*/
public class Repository {
private Integer id;
private String name;
private String url;
private String htmlUrl;
private String gitHttpUrl;
private String description;
/**
* 私有仓库
*/
@JsonProperty("private")
private Boolean isPrivate;
/**
* 内源仓库
*/
@JsonProperty("internal")
private Boolean isInternal;
/**
* 公开仓库
*/
@JsonProperty("public")
private Boolean isPublic;
private String license;
private String language;
private Integer stargazersCount;
private Integer forksCount;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssX")
private Date createdAt;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssX")
private Date updatedAt;
private User owner;
/**
* Turn to kooder repository
* @return
*/
public com.gitee.kooder.models.Repository toKooderRepository() {
com.gitee.kooder.models.Repository repo = new com.gitee.kooder.models.Repository();
repo.setId(this.getId());
repo.setName(this.getName());
repo.setDescription(this.getDescription());
repo.setUrl(this.getGitHttpUrl() == null ? this.getHtmlUrl() : this.getGitHttpUrl());
repo.setOwner(new Relation(this.getOwner().getId(), this.getOwner().getName(), this.getOwner().getHtmlUrl()));
repo.setVisibility(this.getPrivate() ? Constants.VISIBILITY_PRIVATE : this.getInternal() ? Constants.VISIBILITY_INTERNAL : Constants.VISIBILITY_PUBLIC);
repo.setLicense(this.getLicense());
repo.setLang(this.getLanguage());
repo.setReadme(null);
repo.setFork(0);
repo.setTags(Collections.emptyList());
repo.setStarsCount(this.getStargazersCount());
repo.setForksCount(this.getForksCount());
repo.setCreatedAt(this.getCreatedAt().getTime());
repo.setUpdatedAt(this.getUpdatedAt().getTime());
repo.setBlock(Constants.REPO_BLOCK_NO);
return repo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHtmlUrl() {
return htmlUrl;
}
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
public String getGitHttpUrl() {
return gitHttpUrl;
}
public void setGitHttpUrl(String gitHttpUrl) {
this.gitHttpUrl = gitHttpUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getPrivate() {
return isPrivate;
}
public void setPrivate(Boolean aPrivate) {
isPrivate = aPrivate;
}
public Boolean getInternal() {
return isInternal;
}
public void setInternal(Boolean internal) {
isInternal = internal;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Integer getStargazersCount() {
return stargazersCount;
}
public void setStargazersCount(Integer stargazersCount) {
this.stargazersCount = stargazersCount;
}
public Integer getForksCount() {
return forksCount;
}
public void setForksCount(Integer forksCount) {
this.forksCount = forksCount;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
| 23.93722 | 160 | 0.642188 |
78b6813b3411d4ece0dc13146e642ccb52877d74 | 30,553 | package ekraft.verysimplerest.annotation;
import ekraft.verysimplerest.RestClient;
import ekraft.verysimplerest.RestServer;
import ekraft.verysimplerest.examples.AsyncAnnotationTodoService;
import ekraft.verysimplerest.examples.AnnotationTodoRestService;
import ekraft.verysimplerest.utils.RestException;
import ekraft.verysimplerest.utils.RestUrlParameters;
import ekraft.verysimplerest.utils.TestUtils;
import org.junit.After;
import org.junit.Test;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.Assert.*;
public class AnnotationHttpHandlerTest {
private static final int TEST_PORT = 8884;
private RestServer server = new RestServer(TEST_PORT);
private RestClient client = new RestClient("localhost", TEST_PORT);
private AnnotationTestService service = new AnnotationTestService();
@After
public void cleanup()
throws Exception {
RestException.setHandler(null);
server.shutdown();
while (TestUtils.serverIsUp(TEST_PORT)) {
Thread.sleep(1);
}
}
@Test
public void serverStartsAndStops()
throws Exception {
AnnotationTodoRestService annotationTodoRestService = new AnnotationTodoRestService();
AsyncAnnotationTodoService asyncAnnotationTodoService = new AsyncAnnotationTodoService();
assertFalse(TestUtils.serverIsUp(TEST_PORT));
server.addService(annotationTodoRestService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(annotationTodoRestService);
assertFalse(TestUtils.serverIsUp(TEST_PORT));
assertFalse(TestUtils.serverIsUp(TEST_PORT));
server.addService(annotationTodoRestService);
server.addService(asyncAnnotationTodoService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(annotationTodoRestService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(asyncAnnotationTodoService);
assertFalse(TestUtils.serverIsUp(TEST_PORT));
assertFalse(TestUtils.serverIsUp(TEST_PORT));
server.addService(annotationTodoRestService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.addService(annotationTodoRestService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(annotationTodoRestService);
assertFalse(TestUtils.serverIsUp(TEST_PORT));
}
@Test
public void pathsAreCalculatedRight()
throws Exception {
assertEquals("/services/get1", AnnotationUtils.getPath(AnnotationTestService.GET1));
assertEquals("/services/put1", AnnotationUtils.getPath(AnnotationTestService.PUT1));
assertEquals("/services/post1", AnnotationUtils.getPath(AnnotationTestService.POST1));
assertEquals("/services/delete1", AnnotationUtils.getPath(AnnotationTestService.DELETE1));
assertEquals("/services/all1", AnnotationUtils.getPath(AnnotationTestService.ALL1));
assertEquals("/services/get2", AnnotationUtils.getPath(AnnotationTestService.GET2));
assertEquals("/services/put2", AnnotationUtils.getPath(AnnotationTestService.PUT2));
assertEquals("/services/post2", AnnotationUtils.getPath(AnnotationTestService.POST2));
assertEquals("/services/delete2", AnnotationUtils.getPath(AnnotationTestService.DELETE2));
assertEquals("/services/all2", AnnotationUtils.getPath(AnnotationTestService.ALL2));
assertEquals("/services/get3/*", AnnotationUtils.getPath(AnnotationTestService.GET3));
assertEquals("/services/put3", AnnotationUtils.getPath(AnnotationTestService.PUT3));
assertEquals("/services/post3", AnnotationUtils.getPath(AnnotationTestService.POST3));
assertEquals("/services/delete3", AnnotationUtils.getPath(AnnotationTestService.DELETE3));
assertEquals("/services/all3/*", AnnotationUtils.getPath(AnnotationTestService.ALL3));
assertEquals("/services/todo", AnnotationUtils.getPath(AnnotationTodoRestService.GET));
assertEquals("/services/todo", AnnotationUtils.getPath(AnnotationTodoRestService.PUT));
assertEquals("/services/todo", AnnotationUtils.getPath(AnnotationTodoRestService.POST));
assertEquals("/services/todo", AnnotationUtils.getPath(AnnotationTodoRestService.DELETE));
assertEquals("/services/todo/*", AnnotationUtils.getPath(AnnotationTodoRestService.GET_ID));
assertEquals("/services/todo/*", AnnotationUtils.getPath(AnnotationTodoRestService.PUT_ID));
assertEquals("/services/todo/*", AnnotationUtils.getPath(AnnotationTodoRestService.DELETE_ID));
assertEquals("/services/async", AnnotationUtils.getPath(AsyncAnnotationTodoService.GET));
assertEquals("/services/async", AnnotationUtils.getPath(AsyncAnnotationTodoService.PUT));
assertEquals("/services/async", AnnotationUtils.getPath(AsyncAnnotationTodoService.POST));
assertEquals("/services/async", AnnotationUtils.getPath(AsyncAnnotationTodoService.DELETE));
assertEquals("/services/async/{id}", AnnotationUtils.getPath(AsyncAnnotationTodoService.GET_ID));
assertEquals("/services/async/{id}", AnnotationUtils.getPath(AsyncAnnotationTodoService.PUT_ID));
assertEquals("/services/async/{id}", AnnotationUtils.getPath(AsyncAnnotationTodoService.DELETE_ID));
}
@Test
public void handlesRemovingNonexistentServices()
throws Exception {
AnnotationTodoRestService annotationTodoRestService = new AnnotationTodoRestService();
AsyncAnnotationTodoService asyncAnnotationTodoService = new AsyncAnnotationTodoService();
assertFalse(TestUtils.serverIsUp(TEST_PORT));
server.addService(annotationTodoRestService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(asyncAnnotationTodoService);
assertTrue(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(annotationTodoRestService);
assertFalse(TestUtils.serverIsUp(TEST_PORT));
server.shutdownService(annotationTodoRestService);
assertFalse(TestUtils.serverIsUp(TEST_PORT));
}
@Test
public void testVoidNoParameters() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.get(AnnotationTestService.GET1, Boolean.class));
assertArrayEquals(new String[]{"getVoid"}, service.getCalled());
assertNull(client.put(AnnotationTestService.GET1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.GET1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.GET1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.PUT1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.put(AnnotationTestService.PUT1, Boolean.class));
assertArrayEquals(new String[]{"putVoid"}, service.getCalled());
assertNull(client.post(AnnotationTestService.PUT1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.PUT1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.POST1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.POST1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.post(AnnotationTestService.POST1, Boolean.class));
assertArrayEquals(new String[]{"postVoid"}, service.getCalled());
assertNull(client.delete(AnnotationTestService.POST1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.DELETE1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.DELETE1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.DELETE1, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.delete(AnnotationTestService.DELETE1, Boolean.class));
assertArrayEquals(new String[]{"deleteVoid"}, service.getCalled());
assertTrue(client.get(AnnotationTestService.ALL1, Boolean.class));
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
assertTrue(client.put(AnnotationTestService.ALL1, Boolean.class));
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
assertTrue(client.post(AnnotationTestService.ALL1, Boolean.class));
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
assertTrue(client.delete(AnnotationTestService.ALL1, Boolean.class));
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
}
@Test
public void testVoidNoParametersNoReturnTypes() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.GET1);
assertArrayEquals(new String[]{"getVoid"}, service.getCalled());
client.put(AnnotationTestService.GET1);
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.GET1);
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.GET1);
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.PUT1);
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.PUT1);
assertArrayEquals(new String[]{"putVoid"}, service.getCalled());
client.post(AnnotationTestService.PUT1);
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.PUT1);
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.POST1);
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.POST1);
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.POST1);
assertArrayEquals(new String[]{"postVoid"}, service.getCalled());
client.delete(AnnotationTestService.POST1);
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.DELETE1);
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.DELETE1);
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.DELETE1);
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.DELETE1);
assertArrayEquals(new String[]{"deleteVoid"}, service.getCalled());
client.get(AnnotationTestService.ALL1);
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
client.put(AnnotationTestService.ALL1);
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
client.post(AnnotationTestService.ALL1);
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
client.delete(AnnotationTestService.ALL1);
assertArrayEquals(new String[]{"allVoid"}, service.getCalled());
}
@Test
public void testStringReturnType() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
assertEquals("get2", client.get(AnnotationTestService.GET2, String.class));
assertArrayEquals(new String[]{"getString"}, service.getCalled());
assertNull(client.put(AnnotationTestService.GET2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.GET2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.GET2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.PUT2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertEquals("put2", client.put(AnnotationTestService.PUT2, String.class));
assertArrayEquals(new String[]{"putString"}, service.getCalled());
assertNull(client.post(AnnotationTestService.PUT2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.PUT2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.POST2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.POST2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertEquals("post2", client.post(AnnotationTestService.POST2, String.class));
assertArrayEquals(new String[]{"postString"}, service.getCalled());
assertNull(client.delete(AnnotationTestService.POST2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.DELETE2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.DELETE2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.DELETE2, String.class));
assertArrayEquals(new String[0], service.getCalled());
assertEquals("delete2", client.delete(AnnotationTestService.DELETE2, String.class));
assertArrayEquals(new String[]{"deleteString"}, service.getCalled());
assertEquals("all2", client.get(AnnotationTestService.ALL2, String.class));
assertArrayEquals(new String[]{"allString"}, service.getCalled());
assertEquals("all2", client.put(AnnotationTestService.ALL2, String.class));
assertArrayEquals(new String[]{"allString"}, service.getCalled());
assertEquals("all2", client.post(AnnotationTestService.ALL2, String.class));
assertArrayEquals(new String[]{"allString"}, service.getCalled());
assertEquals("all2", client.delete(AnnotationTestService.ALL2, String.class));
assertArrayEquals(new String[]{"allString"}, service.getCalled());
}
@Test
public void testVoidStringParameter() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.get(AnnotationTestService.GET3, Boolean.class, "name"));
assertArrayEquals(new String[]{"getVoid,name"}, service.getCalled());
assertNull(client.put(AnnotationTestService.GET3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.GET3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.GET3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.PUT3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.put(AnnotationTestService.PUT3, Boolean.class, "name"));
assertArrayEquals(new String[]{"putVoid,name"}, service.getCalled());
assertNull(client.post(AnnotationTestService.PUT3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.PUT3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.POST3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.POST3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.post(AnnotationTestService.POST3, Boolean.class, "name"));
assertArrayEquals(new String[]{"postVoid,name"}, service.getCalled());
assertNull(client.delete(AnnotationTestService.POST3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.DELETE3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.DELETE3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.DELETE3, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.delete(AnnotationTestService.DELETE3, Boolean.class, "name"));
assertArrayEquals(new String[]{"deleteVoid,name"}, service.getCalled());
assertTrue(client.get(AnnotationTestService.ALL3, Boolean.class, "name"));
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
assertTrue(client.put(AnnotationTestService.ALL3, Boolean.class, "name"));
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
assertTrue(client.post(AnnotationTestService.ALL3, Boolean.class, "name"));
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
assertTrue(client.delete(AnnotationTestService.ALL3, Boolean.class, "name"));
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
}
@Test
public void testVoidStringParameterNoReturnTypes() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.GET3, "name");
assertArrayEquals(new String[]{"getVoid,name"}, service.getCalled());
client.put(AnnotationTestService.GET3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.GET3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.GET3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.PUT3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.PUT3, "name");
assertArrayEquals(new String[]{"putVoid,name"}, service.getCalled());
client.post(AnnotationTestService.PUT3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.PUT3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.POST3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.POST3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.POST3, "name");
assertArrayEquals(new String[]{"postVoid,name"}, service.getCalled());
client.delete(AnnotationTestService.POST3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.get(AnnotationTestService.DELETE3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.put(AnnotationTestService.DELETE3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.post(AnnotationTestService.DELETE3, "name");
assertArrayEquals(new String[0], service.getCalled());
client.delete(AnnotationTestService.DELETE3, "name");
assertArrayEquals(new String[]{"deleteVoid,name"}, service.getCalled());
client.get(AnnotationTestService.ALL3, "name");
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
client.put(AnnotationTestService.ALL3, "name");
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
client.post(AnnotationTestService.ALL3, "name");
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
client.delete(AnnotationTestService.ALL3, "name");
assertArrayEquals(new String[]{"allVoid,name"}, service.getCalled());
}
@Test
public void testAsynchronousNoParameters() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.get(AnnotationTestService.GET4, Boolean.class));
assertArrayEquals(new String[]{"getCallback"}, service.getCalled());
assertNull(client.put(AnnotationTestService.GET4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.GET4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.GET4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.PUT4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.put(AnnotationTestService.PUT4, Boolean.class));
assertArrayEquals(new String[]{"putCallback"}, service.getCalled());
assertNull(client.post(AnnotationTestService.PUT4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.PUT4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.POST4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.POST4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.post(AnnotationTestService.POST4, Boolean.class));
assertArrayEquals(new String[]{"postCallback"}, service.getCalled());
assertNull(client.delete(AnnotationTestService.POST4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.DELETE4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.DELETE4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.DELETE4, Boolean.class));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.delete(AnnotationTestService.DELETE4, Boolean.class));
assertArrayEquals(new String[]{"deleteCallback"}, service.getCalled());
assertTrue(client.get(AnnotationTestService.ALL4, Boolean.class));
assertArrayEquals(new String[]{"allCallback"}, service.getCalled());
assertTrue(client.put(AnnotationTestService.ALL4, Boolean.class));
assertArrayEquals(new String[]{"allCallback"}, service.getCalled());
assertTrue(client.post(AnnotationTestService.ALL4, Boolean.class));
assertArrayEquals(new String[]{"allCallback"}, service.getCalled());
assertTrue(client.delete(AnnotationTestService.ALL4, Boolean.class));
assertArrayEquals(new String[]{"allCallback"}, service.getCalled());
}
@Test
public void testAsynchronousWithParameter() {
server.addService(service);
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.get(AnnotationTestService.GET5, Boolean.class, "name"));
assertArrayEquals(new String[]{"getCallback,name"}, service.getCalled());
assertNull(client.put(AnnotationTestService.GET5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.GET5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.GET5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.PUT5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.put(AnnotationTestService.PUT5, Boolean.class, "name"));
assertArrayEquals(new String[]{"putCallback,name"}, service.getCalled());
assertNull(client.post(AnnotationTestService.PUT5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.delete(AnnotationTestService.PUT5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.POST5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.POST5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.post(AnnotationTestService.POST5, Boolean.class, "name"));
assertArrayEquals(new String[]{"postCallback,name"}, service.getCalled());
assertNull(client.delete(AnnotationTestService.POST5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.get(AnnotationTestService.DELETE5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.put(AnnotationTestService.DELETE5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertNull(client.post(AnnotationTestService.DELETE5, Boolean.class, "name"));
assertArrayEquals(new String[0], service.getCalled());
assertTrue(client.delete(AnnotationTestService.DELETE5, Boolean.class, "name"));
assertArrayEquals(new String[]{"deleteCallback,name"}, service.getCalled());
assertTrue(client.get(AnnotationTestService.ALL5, Boolean.class, "name"));
assertArrayEquals(new String[]{"allCallback,name"}, service.getCalled());
assertTrue(client.put(AnnotationTestService.ALL5, Boolean.class, "name"));
assertArrayEquals(new String[]{"allCallback,name"}, service.getCalled());
assertTrue(client.post(AnnotationTestService.ALL5, Boolean.class, "name"));
assertArrayEquals(new String[]{"allCallback,name"}, service.getCalled());
assertTrue(client.delete(AnnotationTestService.ALL5, Boolean.class, "name"));
assertArrayEquals(new String[]{"allCallback,name"}, service.getCalled());
}
@Test
public void testRestUrlParametersAsParameter()
throws Exception {
List<String> myId = new ArrayList<>();
List<RestUrlParameters> myParameters = new ArrayList<>();
List<Integer> myValue = new ArrayList<>();
List<String> myWorld = new ArrayList<>();
@Path("test")
class Test {
@PUT
@Path("{id}/*/*")
public void test(String id,
int value,
RestUrlParameters parameters) {
myId.add(id);
myParameters.add(parameters);
myValue.add(value);
}
@POST
@Path("{id}/*")
public void test2(String id,
int value,
RestUrlParameters parameters,
String world) {
myId.add(id);
myParameters.add(parameters);
myValue.add(value);
myWorld.add(world);
}
@DELETE
@Path("{id}/*")
public void test3(String id,
RestUrlParameters parameters,
int value,
String world) {
myId.add(id);
myParameters.add(parameters);
myValue.add(value);
myWorld.add(world);
}
}
Method method = Test.class.getMethod("test", String.class, int.class, RestUrlParameters.class);
Method method2 = Test.class.getMethod("test2", String.class, int.class, RestUrlParameters.class, String.class);
Method method3 = Test.class.getMethod("test3", String.class, RestUrlParameters.class, int.class, String.class);
server.addService(new Test());
client.put(method, "name", 12345, "Hello World");
assertEquals("name", myId.get(0));
assertEquals(new Integer(12345), myValue.get(0));
RestUrlParameters parameters = myParameters.get(0);
assertEquals(3, parameters.size());
assertEquals("name", parameters.get(0));
assertEquals("name", parameters.get("id"));
assertEquals(new Integer(12345), parameters.get(1, int.class));
// The space should be broken off since it's in the URL.
assertEquals("Hello", parameters.get(2));
assertEquals(0, myWorld.size());
myId.clear();
myParameters.clear();
myValue.clear();
myWorld.clear();
client.post(method2, "name", 12345, "Hello World");
assertEquals("name", myId.get(0));
assertEquals(new Integer(12345), myValue.get(0));
parameters = myParameters.get(0);
assertEquals(2, parameters.size());
assertEquals("name", parameters.get(0));
assertEquals("name", parameters.get("id"));
assertEquals(new Integer(12345), parameters.get(1, int.class));
// The space should not be broken off since it's in the request body.
assertEquals("Hello World", myWorld.get(0));
try {
client.delete(method3, "name", 12345, "Hello World");
fail("Should not be able to put RestUrlParameters before parameter variables.");
} catch (Exception e) {
// Expected behavior.
}
}
@Test
public void rejectAsynchronousFunctionsWithReturnValue() {
@Path("path")
class RejectClass {
@GET
public boolean rejectMethod(Consumer<String> callback) {
callback.accept(null);
return true;
}
}
try {
server.addService(new RejectClass());
fail("Should have rejected service.");
} catch (IllegalArgumentException e) {
String expected = "Asynchronous methods are not allowed to have a return type: " +
AnnotationHttpHandlerTest.class.getName() + "$1" +
"RejectClass.rejectMethod()";
assertEquals(expected, e.getMessage());
}
}
@Test
public void exceptionWhenNotEnoughData() {
server.addService(service);
client.put(AnnotationTestService.PUT3, "name");
assertArrayEquals(new String[]{"putVoid,name"}, service.getCalled());
String path = AnnotationUtils.getPath(AnnotationTestService.PUT3);
String result = RestClient.communicate("localhost", TEST_PORT, "PUT", path, "", true);
assertEquals("Ran out of parameters and had empty method body!", result);
}
@Test
public void annotationTimeoutTest()
throws Exception {
List<Throwable> list = new ArrayList<>();
RestException.setHandler(list::add);
server.addService(new AnnotationTestService());
String response = RestClient.communicate("localhost", TEST_PORT, "GET", "/services/timeout", null, true);
assertEquals("Timed Out.", response);
Thread.sleep(2000);
assertEquals(1, list.size());
Throwable throwable = list.get(0);
assertEquals(IOException.class, throwable.getClass());
assertEquals("headers already sent", throwable.getMessage());
}
}
| 44.864905 | 115 | 0.738618 |
fc0a109f95fae512e3f1302683c055a713ca93b5 | 2,508 | package com.packt.quarkus.chapter6;
import org.eclipse.microprofile.faulttolerance.Asynchronous;
import org.eclipse.microprofile.faulttolerance.Bulkhead;
import org.eclipse.microprofile.faulttolerance.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.ws.rs.WebApplicationException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
@ApplicationScoped
public class OrderRepository {
@Inject
EntityManager entityManager;
private static final Logger LOGGER = LoggerFactory.getLogger("CustomerRepository");
@CircuitBreaker(successThreshold = 5, requestVolumeThreshold = 4, failureRatio=0.75,
delay = 1000)
public List<Orders> findAll(Long customerId) {
possibleFailure();
return (List<Orders>) entityManager.createNamedQuery("Orders.findAll")
.setParameter("customerId", customerId)
.getResultList();
}
private void possibleFailure() {
if (new Random().nextFloat() < 0.5f)
throw new RuntimeException("I have generated a Random Resource failure! Try again accessing the service.");
}
public Orders findOrderById(Long id) {
Orders order = entityManager.find(Orders.class, id);
if (order == null) {
throw new WebApplicationException("Order with id of " + id + " does not exist.", 404);
}
return order;
}
@Transactional
public void updateOrder(Orders order) {
Orders orderToUpdate = findOrderById(order.getId());
orderToUpdate.setItem(order.getItem());
orderToUpdate.setPrice(order.getPrice());
}
@Transactional
public void createOrder(Orders order, Customer c) {
order.setCustomer(c);
entityManager.persist(order);
writeSomeLogging(order.getItem());
}
@Asynchronous
@Bulkhead(value = 5, waitingTaskQueue = 10)
private Future writeSomeLogging(String item) {
LOGGER.info("New Customer order at: "+new java.util.Date());
LOGGER.info("Item: {}", item);
return CompletableFuture.completedFuture("ok");
}
@Transactional
public void deleteOrder(Long orderId) {
Orders o = findOrderById(orderId);
entityManager.remove(o);
}
}
| 34.356164 | 115 | 0.695375 |
4431d0ab75ef83fe64234b3c1385560e911d10aa | 1,207 | class Student extends Person{
private int[] testScores;
/*
* Class Constructor
*
* @param firstName - A string denoting the Person's first name.
* @param lastName - A string denoting the Person's last name.
* @param id - An integer denoting the Person's ID number.
* @param scores - An array of integers denoting the Person's test scores.
*/
// Write your constructor here
Student(String fName, String lName, int id,int[] scores){
super(fName,lName,id);
this.testScores=scores;
}
/*
* Method Name: calculate
* @return A character denoting the grade.
*/
public char calculate(){
int sum=0;
int n=testScores.length;
for(int k=0;k<n;k++){
sum+=testScores[k];
}
double average=sum/n;
if(average>89){
return 'O';
}
else if(average>79){
return 'E';
}
else if(average>69){
return 'A';
}
else if(average>54){
return 'P';
}
else if(average>39){
return 'D';
}
else return 'T';
}
// Write your method here
}
| 25.680851 | 79 | 0.523612 |
76cc7513783fee46199a331be1fe07f289ec5c21 | 2,144 | package graphql.execution;
import graphql.PublicApi;
import graphql.language.SourceLocation;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLFieldDefinition;
import java.util.Map;
/**
* The parameters available to {@link DataFetcherExceptionHandler}s
*/
@PublicApi
public class DataFetcherExceptionHandlerParameters {
private final DataFetchingEnvironment dataFetchingEnvironment;
private final Throwable exception;
private DataFetcherExceptionHandlerParameters(Builder builder) {
this.exception = builder.exception;
this.dataFetchingEnvironment = builder.dataFetchingEnvironment;
}
public Throwable getException() {
return exception;
}
public ExecutionPath getPath() {
return dataFetchingEnvironment.getExecutionStepInfo().getPath();
}
public DataFetchingEnvironment getDataFetchingEnvironment() {
return dataFetchingEnvironment;
}
public MergedField getField() {
return dataFetchingEnvironment.getMergedField();
}
public GraphQLFieldDefinition getFieldDefinition() {
return dataFetchingEnvironment.getFieldDefinition();
}
public Map<String, Object> getArgumentValues() {
return dataFetchingEnvironment.getArguments();
}
public SourceLocation getSourceLocation() {
return getField().getSingleField().getSourceLocation();
}
public static Builder newExceptionParameters() {
return new Builder();
}
public static class Builder {
DataFetchingEnvironment dataFetchingEnvironment;
Throwable exception;
private Builder() {
}
public Builder dataFetchingEnvironment(DataFetchingEnvironment dataFetchingEnvironment) {
this.dataFetchingEnvironment = dataFetchingEnvironment;
return this;
}
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public DataFetcherExceptionHandlerParameters build() {
return new DataFetcherExceptionHandlerParameters(this);
}
}
}
| 27.487179 | 97 | 0.711754 |
9eab1df2ad466499e926b9bec01b119db0aeac19 | 3,035 | package dgm.modules.elasticsearch;
import dgm.GraphUtilities;
import dgm.ID;
import dgm.trees.Pair;
import org.elasticsearch.action.get.GetResponse;
import org.nnsoft.guice.sli4j.core.InjectLogger;
import org.slf4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
/**
* Retrieve document from elasticsearch, based on Vertex
* <p/>
* TODO caching
* TODO query priorities
*
* @author wires
*/
public class QueryFunction implements Function<Pair<Edge, Vertex>, Optional<ResolvedPathElement>> {
@InjectLogger
protected Logger log;
protected final DocumentProvider documentProvider;
protected final ObjectMapper objectMapper;
@Inject
public QueryFunction(DocumentProvider documentProvider, ObjectMapper objectMapper) {
this.documentProvider = documentProvider;
this.objectMapper = objectMapper;
}
@Override
public final Optional<ResolvedPathElement> apply(final Pair<Edge, Vertex> pair) {
// dump information on the current vertex
if (log.isTraceEnabled()) {
log.trace("Retrieving document from ES for vertex {}", pair.b);
for (String key : pair.b.getPropertyKeys()) {
log.trace("Property {} has value '{}'", key, pair.b.getProperty(key));
}
}
// retrieve id property
final ID id = GraphUtilities.getID(objectMapper, pair.b);
// vertices without ID's cannot be looked up
if (id == null) {
if (log.isDebugEnabled()) {
log.debug("Vertex has no ID assigned, properties are: ");
for (String key : pair.b.getPropertyKeys()) {
log.debug("Property {} has value '{}'", key, pair.b.getProperty(key));
}
}
return Optional.of(new ResolvedPathElement(Optional.<GetResponse>absent(), pair.a, pair.b));
}
// this document should not exist in elastic search, otherwise the vertex would have a version > 0
if (id.version() == 0) {
log.debug("Document {} is symbolic, so we won't attempt to find it in elasticsearch", id);
return Optional.of(new ResolvedPathElement(Optional.<GetResponse>absent(), pair.a, pair.b));
}
GetResponse r = documentProvider.get(id);
if ((r.version() == -1) || !r.exists())
{
log.debug("Document {} does not exist!", id);
return Optional.of(new ResolvedPathElement(Optional.<GetResponse>absent(), pair.a, pair.b));
}
// query has expired in the meantime
if (r.version() != id.version()) {
log.warn("Document {} expired, version in ES is {}!", id, r.version());
return Optional.absent();
}
return Optional.of(new ResolvedPathElement(Optional.of(r), pair.a, pair.b));
}
}
| 34.488636 | 106 | 0.63888 |
0dc292ea00c4936895ae1c0b93b3017e563050c5 | 2,492 | /*
* Copyright 2019 Scott Logic Ltd
*
* 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.scottlogic.datahelix.generator.core.profile;
import com.scottlogic.datahelix.generator.common.profile.Field;
import com.scottlogic.datahelix.generator.common.profile.Fields;
import com.scottlogic.datahelix.generator.common.profile.ProfileFields;
import com.scottlogic.datahelix.generator.core.profile.constraints.Constraint;
import com.scottlogic.datahelix.generator.core.profile.relationships.Relationship;
import java.util.Collection;
import java.util.List;
public class Profile {
private final Fields fields;
private final Collection<Constraint> constraints;
private final String description;
private final Collection<Relationship> relationships;
public Profile(List<Field> fields, Collection<Constraint> constraints, Collection<Relationship> relationships) {
this(null, new ProfileFields(fields), constraints, relationships);
}
public Profile(List<Field> fields, Collection<Constraint> constraints, Collection<Relationship> relationships, String description) {
this(description, new ProfileFields(fields), constraints, relationships);
}
public Profile(Fields fields, Collection<Constraint> constraints, Collection<Relationship> relationships) {
this(null, fields, constraints, relationships);
}
public Profile(String description, Fields fields, Collection<Constraint> constraints, Collection<Relationship> relationships) {
this.fields = fields;
this.constraints = constraints;
this.description = description;
this.relationships = relationships;
}
public Fields getFields() {
return fields;
}
public Collection<Constraint> getConstraints() {
return constraints;
}
public String getDescription() {
return description;
}
public Collection<Relationship> getRelationships() {
return relationships;
}
}
| 36.115942 | 136 | 0.74679 |
13efec4afee02b8953e7829f633aacb3d84b9ddd | 1,088 | package com.dianping.phoenix.spi.internal;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import com.dianping.phoenix.spi.WebappProvider;
public class OrderingReservedWepappProvider implements WebappProvider {
private List<File> classpathEntries = new ArrayList<File>();
private File m_warRoot;
public OrderingReservedWepappProvider(String docBase, URLClassLoader ucl) throws IOException {
m_warRoot = new File(docBase).getCanonicalFile();
copyClasspathEntriesFrom(ucl);
}
private void copyClasspathEntriesFrom(URLClassLoader ucl) {
URL[] urls = ucl.getURLs();
for (int i = 0; i < urls.length; i++) {
try {
classpathEntries.add(new File(urls[i].toURI()));
} catch (URISyntaxException e) {
throw new RuntimeException("error convert URL to File", e);
}
}
}
@Override
public List<File> getClasspathEntries() {
return classpathEntries;
}
@Override
public File getWarRoot() {
return m_warRoot;
}
}
| 23.652174 | 95 | 0.75 |
1c1747ec2db67a66a015796b926bddfd90440aff | 6,774 | package me.gingerninja.authenticator.data.adapter;
import android.content.res.ColorStateList;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.chip.Chip;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import me.gingerninja.authenticator.R;
import me.gingerninja.authenticator.data.db.entity.Label;
import me.gingerninja.authenticator.ui.account.BaseAccountViewModel;
import me.gingerninja.authenticator.ui.home.form.LabelClickListener;
import me.gingerninja.authenticator.util.BindingHelpers;
import timber.log.Timber;
public class AccountLabelListAdapter extends RecyclerView.Adapter<AccountLabelListAdapter.ChipViewHolder> implements LabelClickListener {
private static final int TYPE_LABEL = R.layout.account_form_label_list_entry;
private static final int TYPE_ADD_BUTTON = R.layout.account_form_label_list_add_item;
@Nullable
private List<BaseAccountViewModel.LabelData> labels;
@Nullable
private LabelClickListener labelClickListener;
private View.OnClickListener labelRemoveClickListener = v -> onLabelRemoved((Label) v.getTag(), -1);
private View.OnClickListener labelAddClickListener = this::onLabelAddClicked;
private Disposable labelsDisposable;
public AccountLabelListAdapter(@NonNull Single<List<BaseAccountViewModel.LabelData>> labels) {
setHasStableIds(true);
labelsDisposable = labels.subscribe((labelData, throwable) -> {
this.labels = labelData;
notifyDataSetChanged();
});
}
public AccountLabelListAdapter setLabelClickListener(@Nullable LabelClickListener labelClickListener) {
this.labelClickListener = labelClickListener;
return this;
}
public void addLabel(@NonNull Label label) {
this.labels.add(new BaseAccountViewModel.LabelData(label, this.labels.size()));
notifyDataSetChanged();
}
public void addLabel(@NonNull Label label, int position) {
this.labels.add(Math.min(position, labels.size()), new BaseAccountViewModel.LabelData(label, this.labels.size()));
notifyDataSetChanged();
}
@Nullable
public List<BaseAccountViewModel.LabelData> getLabels() {
return labels;
}
@NonNull
@Override
public AccountLabelListAdapter.ChipViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ChipViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false));
}
@Override
public void onBindViewHolder(@NonNull AccountLabelListAdapter.ChipViewHolder holder, int position) {
if (getItemViewType(position) == TYPE_LABEL) {
holder.chip.setOnCloseIconClickListener(labelRemoveClickListener);
//holder.chip.setOnClickListener(null);
holder.setFromLabel(labels.get(position).getLabel());
} else {
//holder.chip.setOnCloseIconClickListener(null);
holder.chip.setOnClickListener(labelAddClickListener);
}
}
@Override
public long getItemId(int position) {
if (getItemViewType(position) == TYPE_LABEL) {
return labels.get(position).getLabel().getId();
}
return RecyclerView.NO_ID;
}
@Override
public int getItemViewType(int position) {
if (position + 1 == getItemCount()) {
return TYPE_ADD_BUTTON;
}
return TYPE_LABEL;
}
@Override
public int getItemCount() {
return labels == null ? 1 : labels.size() + 1;
}
@Override
public void onLabelAddClicked(View view) {
if (labelClickListener != null) {
labelClickListener.onLabelAddClicked(view);
}
}
@Override
public void onLabelRemoved(Label label, int fakePos) {
if (labelClickListener != null) {
int i = 0;
for (Iterator<BaseAccountViewModel.LabelData> it = labels.iterator(); it.hasNext(); i++) {
BaseAccountViewModel.LabelData labelData = it.next();
if (labelData.getLabel().getId() == label.getId()) {
it.remove();
labelClickListener.onLabelRemoved(label, i);
break;
}
}
// labels.remove(label);
notifyDataSetChanged();
}
}
public boolean onItemMove(int fromPosition, int toPosition) {
Timber.v("onItemMove() - from: %d, to: %d", fromPosition, toPosition);
toPosition = Math.min(labels.size() - 1, toPosition);
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(labels, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(labels, i, i - 1);
}
}
for (int i = 0; i < labels.size(); i++) {
BaseAccountViewModel.LabelData label = labels.get(i);
if (label.getPosition() != i) {
label.setPosition(i);
}
}
notifyItemMoved(fromPosition, toPosition);
return true;
}
public void onItemDrag(RecyclerView.ViewHolder viewHolder, boolean isDragging) {
if (viewHolder == null) {
return;
}
ChipViewHolder holder = (ChipViewHolder) viewHolder;
holder.chip.setAlpha(isDragging ? .75f : 1f);
}
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
if (labelsDisposable != null) {
labelsDisposable.dispose();
}
}
static class ChipViewHolder extends RecyclerView.ViewHolder {
private Chip chip;
private ChipViewHolder(@NonNull View itemView) {
super(itemView);
if (itemView instanceof Chip) {
this.chip = (Chip) itemView;
} else {
throw new IllegalArgumentException("Chip was expected, found: " + itemView.getClass().getSimpleName());
}
}
private void setFromLabel(Label label) {
chip.setChipIcon(label.getIconDrawable(itemView.getContext()));
chip.setTag(label);
chip.setText(label.getName());
chip.setChipBackgroundColor(ColorStateList.valueOf(label.getColor()));
BindingHelpers.setChipTextColor(chip, label.getColor());
}
}
}
| 34.212121 | 137 | 0.653381 |
7d75eccb058cbb72d867830205764922245e63b7 | 3,593 | package com.huaweicloud.sdk.vpcep.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** Response Object */
public class UpdateEndpointRoutetableResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "routetables")
private List<String> routetables = null;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "error")
private RoutetableInfoError error;
public UpdateEndpointRoutetableResponse withRoutetables(List<String> routetables) {
this.routetables = routetables;
return this;
}
public UpdateEndpointRoutetableResponse addRoutetablesItem(String routetablesItem) {
if (this.routetables == null) {
this.routetables = new ArrayList<>();
}
this.routetables.add(routetablesItem);
return this;
}
public UpdateEndpointRoutetableResponse withRoutetables(Consumer<List<String>> routetablesSetter) {
if (this.routetables == null) {
this.routetables = new ArrayList<>();
}
routetablesSetter.accept(this.routetables);
return this;
}
/** 路由表ID列表。节点的白名单。 此参数可以添加IPv4或CIDR: ● 当取值不为空时,表示将白 名单更新为取值所示内容。 ● 当取值为空时,表示删除所 有白名单。 默认为空列表。
*
* @return routetables */
public List<String> getRoutetables() {
return routetables;
}
public void setRoutetables(List<String> routetables) {
this.routetables = routetables;
}
public UpdateEndpointRoutetableResponse withError(RoutetableInfoError error) {
this.error = error;
return this;
}
public UpdateEndpointRoutetableResponse withError(Consumer<RoutetableInfoError> errorSetter) {
if (this.error == null) {
this.error = new RoutetableInfoError();
errorSetter.accept(this.error);
}
return this;
}
/** Get error
*
* @return error */
public RoutetableInfoError getError() {
return error;
}
public void setError(RoutetableInfoError error) {
this.error = error;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UpdateEndpointRoutetableResponse updateEndpointRoutetableResponse = (UpdateEndpointRoutetableResponse) o;
return Objects.equals(this.routetables, updateEndpointRoutetableResponse.routetables)
&& Objects.equals(this.error, updateEndpointRoutetableResponse.error);
}
@Override
public int hashCode() {
return Objects.hash(routetables, error);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UpdateEndpointRoutetableResponse {\n");
sb.append(" routetables: ").append(toIndentedString(routetables)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 30.193277 | 113 | 0.654606 |
ef1a7af2af9742d0e865742cdb3b85e722e0c5e6 | 1,282 | package com.bloomhousemc.thermus;
import com.bloomhousemc.thermus.client.UserHud;
import com.bloomhousemc.thermus.client.renderer.BoilerBlockEntityRenderer;
import com.bloomhousemc.thermus.client.renderer.PipeBlockEntityRenderer;
import com.bloomhousemc.thermus.common.registry.ThermusObjects;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import net.fabricmc.fabric.api.client.rendering.v1.BlockEntityRendererRegistry;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.block.entity.BlockEntityRendererFactory;
public class ThermusClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
HudRenderCallback.EVENT.register(new UserHud());
BlockEntityRendererRegistry.register(ThermusObjects.BOILER_BLOCK_ENTITY, (BlockEntityRendererFactory.Context rendererDispatcherIn) -> new BoilerBlockEntityRenderer());
BlockEntityRendererRegistry.register(ThermusObjects.PIPE_BLOCK_ENTITY, (BlockEntityRendererFactory.Context rendererDispatcherIn) -> new PipeBlockEntityRenderer());
BlockRenderLayerMap.INSTANCE.putBlock(ThermusObjects.PIPE_BLOCK, RenderLayer.getCutout());
}
}
| 53.416667 | 169 | 0.859594 |
93ae491eee3c0fc360f6f5b38aaeccb614322d75 | 1,419 | package com.github.zhenwei.pkix.util.oer.its;
import com.github.zhenwei.core.asn1.ASN1Integer;
import java.math.BigInteger;
/**
* NinetyDegreeInt ::= INTEGER { min (-900000000), max (900000000), unknown (900000001) }
*/
public class OneEightyDegreeInt
extends ASN1Integer {
private static final BigInteger loweBound = new BigInteger("-1799999999");
private static final BigInteger upperBound = new BigInteger("1800000000");
private static final BigInteger unknown = new BigInteger("1800000001");
public OneEightyDegreeInt(long value) {
super(value);
assertValue();
}
public OneEightyDegreeInt(BigInteger value) {
super(value);
assertValue();
}
public OneEightyDegreeInt(byte[] bytes) {
super(bytes);
assertValue();
}
public static OneEightyDegreeInt getInstance(Object o) {
if (o instanceof OneEightyDegreeInt) {
return (OneEightyDegreeInt) o;
} else {
return new OneEightyDegreeInt(ASN1Integer.getInstance(o).getValue());
}
}
public void assertValue() {
BigInteger bi = getValue();
if (bi.compareTo(loweBound) < 0) {
throw new IllegalStateException("one eighty degree int cannot be less than -1799999999");
}
if (bi.equals(unknown)) {
return;
}
if (bi.compareTo(upperBound) > 0) {
throw new IllegalStateException("one eighty degree int cannot be greater than 1800000000");
}
}
} | 24.894737 | 97 | 0.693446 |
df9b4f67802dc12a43b30d7ec9178c3e2d538938 | 477 | package de.quinscape.automaton.runtime.filter.impl;
import de.quinscape.automaton.runtime.filter.Filter;
import de.quinscape.automaton.runtime.filter.FilterEvaluationContext;
public final class NotFilter
implements Filter
{
private final Filter filter;
public NotFilter(Filter filter)
{
this.filter = filter;
}
@Override
public Object evaluate(FilterEvaluationContext ctx)
{
return !(boolean)filter.evaluate(ctx);
}
}
| 19.08 | 69 | 0.719078 |
d25594ecb9f47d9933b5e6a2c0f8422b638addba | 833 | package org.benetech.servicenet.service.dto.provider;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class ProviderFilterDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String city;
private String region;
private String zip;
private List<String> serviceTypes = new ArrayList<>();
@Override
public String toString() {
StringBuilder serviceTypesString = new StringBuilder();
for (String s : serviceTypes) {
serviceTypesString.append(s);
serviceTypesString.append(" | ");
}
return "ProviderFilterDTO" + " city: " + city + " region: " + region + " zip: " + zip + " "
+ " serviceTypes " + serviceTypesString.toString();
}
}
| 25.242424 | 99 | 0.656663 |
1804e6017e182920ed6b75a2ca1919efa8359b48 | 5,446 | package team.hollow.neutronia.client.entity.render.model.model;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.model.Cuboid;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.entity.Entity;
/**
* Axoleen - Undefined
* Created using Tabula 7.0.0
*/
public class ModelAxoleen extends EntityModel {
public Cuboid BlowHole2;
public Cuboid BlowHole1;
public Cuboid LeftEye;
public Cuboid Head;
public Cuboid Lips;
public Cuboid Mouth;
public Cuboid Body1;
public Cuboid RightFlipper;
public Cuboid LeftFinger;
public Cuboid Body2;
public Cuboid RightEye;
public Cuboid Tail;
public Cuboid BackFin;
public Cuboid BlowHole3;
public Cuboid FrontFin;
public ModelAxoleen() {
this.textureWidth = 256;
this.textureHeight = 128;
this.BlowHole2 = new Cuboid(this, 77, 16);
this.BlowHole2.setRotationPoint(0.0F, -1.0F, -17.0F);
this.BlowHole2.addBox(-1.0F, -2.0F, -3.0F, 2, 2, 5, 0.0F);
this.Lips = new Cuboid(this, 0, 46);
this.Lips.setRotationPoint(0.0F, 15.0F, -12.5F);
this.Lips.addBox(-12.5F, -1.0F, -8.5F, 25, 2, 17, 0.0F);
this.BlowHole3 = new Cuboid(this, 86, 17);
this.BlowHole3.setRotationPoint(0.0F, -2.0F, -20.0F);
this.BlowHole3.addBox(-1.5F, -1.5F, -1.0F, 3, 3, 1, 0.0F);
this.Head = new Cuboid(this, 0, 0);
this.Head.setRotationPoint(0.0F, 12.5F, 0.0F);
this.Head.addBox(-11.5F, -11.5F, -20.0F, 23, 23, 23, 0.0F);
this.RightEye = new Cuboid(this, 69, 12);
this.RightEye.setRotationPoint(-10.0F, 11.0F, -19.0F);
this.RightEye.addBox(-2.0F, -0.5F, -1.5F, 4, 1, 3, 0.0F);
this.setRotateAngle(RightEye, 0.0F, 0.0F, -0.04363323129985824F);
this.Mouth = new Cuboid(this, 0, 65);
this.Mouth.setRotationPoint(0.0F, 15.0F, -4.75F);
this.Mouth.addBox(-12.0F, 0.0F, -16.0F, 24, 10, 16, 0.0F);
this.setRotateAngle(Mouth, 0.22759093446006054F, 0.0F, 0.0F);
this.FrontFin = new Cuboid(this, 114, 28);
this.FrontFin.setRotationPoint(0.0F, 3.0F, 0.0F);
this.FrontFin.addBox(-1.0F, -18.0F, -8.0F, 2, 20, 16, 0.0F);
this.setRotateAngle(FrontFin, -0.08726646259971647F, 0.0F, 0.0F);
this.Body1 = new Cuboid(this, 0, 91);
this.Body1.setRotationPoint(0.0F, 13.5F, 0.0F);
this.Body1.addBox(-10.0F, -8.5F, 0.0F, 20, 17, 20, 0.0F);
this.Body2 = new Cuboid(this, 80, 64);
this.Body2.setRotationPoint(0.0F, 14.0F, 17.0F);
this.Body2.addBox(-7.0F, -7.0F, 0.0F, 14, 14, 24, 0.0F);
this.Tail = new Cuboid(this, 80, 102);
this.Tail.setRotationPoint(0.0F, 15.0F, 41.0F);
this.Tail.addBox(-21.0F, -1.0F, -7.0F, 42, 2, 24, 0.0F);
this.RightFlipper = new Cuboid(this, 95, 0);
this.RightFlipper.setRotationPoint(-10.0F, 20.0F, 11.0F);
this.RightFlipper.addBox(-1.0F, 0.0F, -7.5F, 1, 23, 15, 0.0F);
this.setRotateAngle(RightFlipper, 0.0F, 0.0F, 0.6981317007977318F);
this.LeftFinger = new Cuboid(this, 95, 0);
this.LeftFinger.mirror = true;
this.LeftFinger.setRotationPoint(10.0F, 20.0F, 11.0F);
this.LeftFinger.addBox(0.0F, 0.0F, -7.5F, 1, 23, 15, 0.0F);
this.setRotateAngle(LeftFinger, 0.0F, 0.0F, -0.6981317007977318F);
this.BlowHole1 = new Cuboid(this, 69, 17);
this.BlowHole1.setRotationPoint(0.0F, 2.0F, -16.0F);
this.BlowHole1.addBox(-1.0F, -3.0F, -1.0F, 2, 4, 2, 0.0F);
this.BackFin = new Cuboid(this, 69, 0);
this.BackFin.setRotationPoint(0.0F, 8.0F, 35.0F);
this.BackFin.addBox(-1.0F, -6.0F, -3.0F, 2, 6, 6, 0.0F);
this.LeftEye = new Cuboid(this, 69, 12);
this.LeftEye.mirror = true;
this.LeftEye.setRotationPoint(10.0F, 11.0F, -19.0F);
this.LeftEye.addBox(-2.0F, -0.5F, -1.5F, 4, 1, 3, 0.0F);
this.setRotateAngle(LeftEye, 0.0F, 0.0F, 0.04363323129985824F);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.BlowHole2.render(f5);
GlStateManager.pushMatrix();
GlStateManager.translatef(this.Lips.x, this.Lips.y, this.Lips.z);
GlStateManager.translatef(this.Lips.rotationPointX * f5, this.Lips.rotationPointY * f5, this.Lips.rotationPointZ * f5);
GlStateManager.scaled(1.0D, 0.9D, 1.0D);
GlStateManager.translatef(-this.Lips.x, -this.Lips.y, -this.Lips.z);
GlStateManager.translatef(-this.Lips.rotationPointX * f5, -this.Lips.rotationPointY * f5, -this.Lips.rotationPointZ * f5);
this.Lips.render(f5);
GlStateManager.popMatrix();
this.BlowHole3.render(f5);
this.Head.render(f5);
this.RightEye.render(f5);
this.Mouth.render(f5);
this.FrontFin.render(f5);
this.Body1.render(f5);
this.Body2.render(f5);
this.Tail.render(f5);
this.RightFlipper.render(f5);
this.LeftFinger.render(f5);
this.BlowHole1.render(f5);
this.BackFin.render(f5);
this.LeftEye.render(f5);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(Cuboid Cuboid, float x, float y, float z) {
Cuboid.rotationPointX = x;
Cuboid.rotationPointY = y;
Cuboid.rotationPointZ = z;
}
}
| 44.639344 | 130 | 0.622475 |
716fd6e492c833ed2f5814781ae9408e61de6d99 | 1,710 | package edu.jhu.pacaya.autodiff.tensor;
import org.junit.Test;
import edu.jhu.pacaya.autodiff.AbstractModuleTest;
import edu.jhu.pacaya.autodiff.AbstractModuleTest.Tensor2Factory;
import edu.jhu.pacaya.autodiff.Module;
import edu.jhu.pacaya.autodiff.Tensor;
import edu.jhu.pacaya.autodiff.TensorUtils;
import edu.jhu.pacaya.util.semiring.Algebra;
import edu.jhu.pacaya.util.semiring.RealAlgebra;
public class ScalarMultiplyTest {
private Algebra s = RealAlgebra.getInstance();
@Test
public void testForwardAndBackward() {
Tensor t1 = TensorUtils.getVectorFromValues(s, 2, 3, 5);
Tensor t2 = TensorUtils.getVectorFromValues(s, 4, 6, 7);
Tensor expOut = TensorUtils.getVectorFromValues(s,
2 * 6,
3 * 6,
5 * 6);
double adjFill = 2.2;
Tensor expT1Adj = TensorUtils.getVectorFromValues(s, 2.2*6, 2.2*6, 2.2*6);
Tensor expT2Adj = TensorUtils.getVectorFromValues(s, 0, 2.2*2 + 2.2*3 + 2.2*5, 0);
Tensor2Factory fact = new Tensor2Factory() {
public Module<Tensor> getModule(Module<Tensor> m1, Module<Tensor> m2) {
return new ScalarMultiply(m1, m2, 1);
}
};
AbstractModuleTest.evalTensor2(t1, expT1Adj, t2, expT2Adj, fact, expOut, adjFill);
}
@Test
public void testGradByFiniteDiffsAllSemirings() {
Tensor2Factory fact = new Tensor2Factory() {
public Module<Tensor> getModule(Module<Tensor> m1, Module<Tensor> m2) {
return new ScalarMultiply(m1, m2, 1);
}
};
AbstractModuleTest.evalTensor2ByFiniteDiffs(fact);
}
}
| 34.2 | 90 | 0.635673 |
e3b9df745fbf4302bbb0c87c31349edfd3709499 | 13,118 | package com.randomappsinc.simpleflashcards.activities;
import android.animation.Animator;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.randomappsinc.simpleflashcards.R;
import com.randomappsinc.simpleflashcards.constants.Constants;
import com.randomappsinc.simpleflashcards.constants.QuizScore;
import com.randomappsinc.simpleflashcards.dialogs.QuitQuizDialog;
import com.randomappsinc.simpleflashcards.models.Problem;
import com.randomappsinc.simpleflashcards.models.Quiz;
import com.randomappsinc.simpleflashcards.persistence.DatabaseManager;
import com.randomappsinc.simpleflashcards.persistence.models.FlashcardSet;
import com.randomappsinc.simpleflashcards.utils.UIUtils;
import java.util.List;
import java.util.Locale;
import butterknife.BindInt;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class QuizActivity extends StandardActivity implements QuitQuizDialog.Listener {
@BindView(R.id.problem_parent) View problemParent;
@BindView(R.id.question_header) TextView questionHeader;
@BindView(R.id.question) TextView questionText;
@BindView(R.id.options) RadioGroup optionsContainer;
@BindViews({R.id.option_1, R.id.option_2, R.id.option_3, R.id.option_4}) List<RadioButton> optionButtons;
@BindView(R.id.submit) View submitButton;
@BindView(R.id.results_page) View resultsPage;
@BindView(R.id.results_header) TextView resultsHeader;
@BindView(R.id.score) TextView score;
@BindString(R.string.quiz_question_header) String headerTemplate;
@BindString(R.string.good_score_message) String goodScore;
@BindString(R.string.okay_score_message) String okayScore;
@BindString(R.string.bad_score_message) String badScore;
@BindString(R.string.your_score_was) String scoreHeaderTemplate;
@BindString(R.string.quiz_score_template) String scoreTemplate;
@BindInt(R.integer.shorter_anim_length) int animationLength;
private FlashcardSet flashcardSet;
private Quiz quiz;
private QuitQuizDialog quitQuizDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
ButterKnife.bind(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
int setId = getIntent().getIntExtra(Constants.FLASHCARD_SET_ID_KEY, 0);
flashcardSet = DatabaseManager.get().getFlashcardSet(setId);
setTitle(flashcardSet.getName());
quitQuizDialog = new QuitQuizDialog(this, this);
quiz = new Quiz(flashcardSet);
int numOptions = quiz.getNumOptions();
if (numOptions >= 3) {
optionButtons.get(2).setVisibility(View.VISIBLE);
}
if (numOptions >= 4) {
optionButtons.get(3).setVisibility(View.VISIBLE);
}
loadCurrentQuestionIntoView();
}
private void loadCurrentQuestionIntoView() {
// Uncheck currently chosen option if applicable
RadioButton chosenButton = getChosenButton();
if (chosenButton != null) {
optionsContainer.clearCheck();
optionsContainer.jumpDrawablesToCurrentState();
}
String headerText = String.format(
headerTemplate,
quiz.getCurrentProblemPosition() + 1,
quiz.getNumQuestions());
questionHeader.setText(headerText);
Problem problem = quiz.getCurrentProblem();
questionText.setText(problem.getQuestion());
List<String> options = problem.getOptions();
for (int i = 0; i < options.size(); i++) {
optionButtons.get(i).setText(options.get(i));
}
}
private void animateQuestionOut() {
submitButton.setEnabled(false);
problemParent
.animate()
.translationXBy(-1 * problemParent.getWidth())
.alpha(0)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
problemParent.setTranslationX(0);
animationQuestionIn();
}
@Override
public void onAnimationCancel(Animator animation) {
makeQuestionViewSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
}
private void animationQuestionIn() {
problemParent
.animate()
.alpha(1)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
loadCurrentQuestionIntoView();
}
@Override
public void onAnimationEnd(Animator animation) {
submitButton.setEnabled(true);
}
@Override
public void onAnimationCancel(Animator animation) {
makeQuestionViewSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
}
private void makeQuestionViewSane() {
problemParent.setTranslationX(0);
problemParent.setAlpha(1);
loadCurrentQuestionIntoView();
submitButton.setEnabled(true);
resultsPage.setVisibility(View.GONE);
resultsPage.setAlpha(0);
problemParent.setVisibility(View.VISIBLE);
submitButton.setVisibility(View.VISIBLE);
}
private void makeResultsPageSane() {
resultsPage.setAlpha(1);
resultsPage.setVisibility(View.VISIBLE);
problemParent.setVisibility(View.GONE);
submitButton.setVisibility(View.GONE);
}
@OnClick(R.id.submit)
public void submitAnswer() {
if (quiz.isQuizComplete()) {
return;
}
RadioButton chosenButton = getChosenButton();
if (chosenButton == null) {
UIUtils.showLongToast(R.string.please_check_something);
} else {
quiz.submitAnswer(chosenButton.getText().toString());
quiz.advanceToNextProblem();
if (quiz.isQuizComplete()) {
fadeOutProblemPage();
} else {
animateQuestionOut();
}
}
}
private void fadeOutProblemPage() {
problemParent
.animate()
.alpha(0)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
problemParent.setVisibility(View.GONE);
submitButton.setVisibility(View.GONE);
fadeInResultsPage();
}
@Override
public void onAnimationCancel(Animator animation) {
makeResultsPageSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
submitButton.animate().alpha(0).setDuration(animationLength);
}
private void loadResultsIntoView() {
Quiz.Grade grade = quiz.getGrade();
String quizScore = "";
switch (grade.getScore()) {
case QuizScore.GOOD:
quizScore = goodScore;
break;
case QuizScore.OKAY:
quizScore = okayScore;
break;
case QuizScore.BAD:
quizScore = badScore;
break;
}
String scoreHeaderText = String.format(
Locale.getDefault(),
scoreHeaderTemplate,
quizScore);
resultsHeader.setText(scoreHeaderText);
String scoreText = String.format(
Locale.getDefault(),
scoreTemplate,
grade.getFractionText(),
grade.getPercentText());
score.setText(scoreText);
}
private void fadeInResultsPage() {
resultsPage
.animate()
.alpha(1)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
loadResultsIntoView();
resultsPage.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {
makeResultsPageSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
}
private void fadeOutResultsPage() {
resultsPage
.animate()
.alpha(0)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
resultsPage.setVisibility(View.GONE);
fadeInProblemPage();
}
@Override
public void onAnimationCancel(Animator animation) {
makeQuestionViewSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
}
private void fadeInProblemPage() {
problemParent
.animate()
.alpha(1)
.setDuration(animationLength)
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
loadCurrentQuestionIntoView();
problemParent.setVisibility(View.VISIBLE);
submitButton.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {
makeQuestionViewSane();
}
@Override
public void onAnimationRepeat(Animator animation) {}
});
submitButton.animate().alpha(1).setDuration(animationLength);
}
@OnClick(R.id.retake)
public void retake() {
quiz = new Quiz(flashcardSet);
fadeOutResultsPage();
}
@OnClick(R.id.exit)
public void exit() {
finish();
}
@OnClick(R.id.view_results)
public void viewResults() {
Intent intent = new Intent(this, QuizResultsActivity.class)
.putParcelableArrayListExtra(Constants.QUIZ_RESULTS_KEY, quiz.getProblems())
.putExtra(Constants.FLASHCARD_SET_NAME_KEY, flashcardSet.getName())
.putExtra(Constants.FLASHCARD_SET_SIZE_KEY, flashcardSet.getFlashcards().size());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.stay);
}
@Nullable
private RadioButton getChosenButton() {
for (RadioButton radioButton : optionButtons) {
if (radioButton.isChecked()) {
return radioButton;
}
}
return null;
}
private void onQuizExit() {
if (!quiz.isQuizComplete()) {
quitQuizDialog.show();
} else {
finish();
}
}
@Override
public void onQuitQuizConfirmed() {
finish();
}
@Override
public void onBackPressed() {
onQuizExit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onQuizExit();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 34.430446 | 109 | 0.576841 |
69963933fc74247b430cfe01cfb3daf6125c4b95 | 753 | package net.lshift.spki.suiteb.sexpstructs;
import net.lshift.spki.convert.Convert;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;
/**
* Serialization format for public encryption keys
*/
@Convert.RequiresConverter(ECPointConverter.class)
@Convert.ByPosition(name="suiteb-p384-ecdh-public-key", fields={"point"})
public class EcdhPublicKey extends EcPublicKey {
public EcdhPublicKey(final ECPoint point) {
super(point);
}
public EcdhPublicKey(final ECPublicKeyParameters publicKey) {
super(publicKey);
}
public EcdhPublicKey(final AsymmetricCipherKeyPair keyPair) {
super(keyPair);
}
}
| 26.892857 | 73 | 0.759628 |
1a788a62ab4305a933b8c79e8a38875a669d130c | 15,612 |
package com.trovebox.android.app;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.holoeverywhere.addon.AddonSlider;
import org.holoeverywhere.addon.AddonSlider.AddonSliderA;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Activity.Addons;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.trovebox.android.app.FacebookFragment.FacebookLoadingControlAccessor;
import com.trovebox.android.app.NavigationHandlerFragment.TitleChangedHandler;
import com.trovebox.android.app.SyncFragment.SyncHandler;
import com.trovebox.android.app.TwitterFragment.TwitterLoadingControlAccessor;
import com.trovebox.android.app.bitmapfun.util.ImageCacheUtils;
import com.trovebox.android.app.facebook.FacebookProvider;
import com.trovebox.android.app.net.account.AccountLimitUtils2;
import com.trovebox.android.app.twitter.TwitterUtils;
import com.trovebox.android.common.activity.CommonActivity;
import com.trovebox.android.common.model.Album;
import com.trovebox.android.common.provider.UploadsUtils;
import com.trovebox.android.common.provider.UploadsUtils.UploadsClearedHandler;
import com.trovebox.android.common.util.BackKeyControl;
import com.trovebox.android.common.util.CommonUtils;
import com.trovebox.android.common.util.GalleryOpenControl;
import com.trovebox.android.common.util.GuiUtils;
import com.trovebox.android.common.util.LoadingControl;
import com.trovebox.android.common.util.ObjectAccessor;
import com.trovebox.android.common.util.SyncUtils;
import com.trovebox.android.common.util.SyncUtils.SyncStartedHandler;
import com.trovebox.android.common.util.TrackerUtils;
@Addons(Activity.ADDON_SLIDER)
public class MainActivity extends CommonActivity implements LoadingControl, GalleryOpenControl,
SyncHandler, UploadsClearedHandler, TwitterLoadingControlAccessor,
FacebookLoadingControlAccessor, SyncStartedHandler, GalleryFragment.StartNowHandler,
TitleChangedHandler {
private static final String NAVIGATION_HANDLER_FRAGMENT_TAG = "NavigationHandlerFragment";
public static final String TAG = MainActivity.class.getSimpleName();
public final static int AUTHORIZE_ACTIVITY_REQUEST_CODE = 0;
public static final int REQUEST_ALBUMS = 2;
private ActionBar mActionBar;
private AtomicInteger loaders = new AtomicInteger(0);
private AtomicBoolean cameraActionProcessing = new AtomicBoolean(false);
boolean instanceSaved = false;
final Handler handler = new Handler();
static WeakReference<MainActivity> currentInstance;
static ObjectAccessor<MainActivity> currentInstanceAccessor = new ObjectAccessor<MainActivity>() {
private static final long serialVersionUID = 1L;
@Override
public MainActivity run() {
return currentInstance == null ? null : currentInstance.get();
}
};
/**
* Called when Main Activity is first loaded
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
currentInstance = new WeakReference<MainActivity>(this);
instanceSaved = false;
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
mActionBar = getSupportActionBar();
mActionBar.setDisplayUseLogoEnabled(true);
mActionBar.setDisplayShowTitleEnabled(true);
if (loaders.get() == 0)
{
setSupportProgressBarIndeterminateVisibility(false);
}
setContentView(R.layout.content);
addRegisteredReceiver(UploadsUtils
.getAndRegisterOnUploadClearedActionBroadcastReceiver(TAG,
this, this));
addRegisteredReceiver(SyncUtils.getAndRegisterOnSyncStartedActionBroadcastReceiver(
TAG, this, this));
addRegisteredReceiver(ImageCacheUtils.getAndRegisterOnDiskCacheClearedBroadcastReceiver(
TAG,
this));
}
@Override
protected void onPostCreate(Bundle sSavedInstanceState) {
super.onPostCreate(sSavedInstanceState);
// //TODO hack which refreshes indeterminate progress state on
// // orientation change
// handler.postDelayed(new Runnable() {
//
// @Override
// public void run() {
// startLoading();
// stopLoading();
// }
// }, 100);
final AddonSliderA slider = addonSlider();
mActionBar.setDisplayHomeAsUpEnabled(true);
slider.setLeftViewWidth(computeMenuWidth());
slider.setDragWithActionBar(true);
navigationHandlerFragment = (NavigationHandlerFragment) getSupportFragmentManager()
.findFragmentByTag(NAVIGATION_HANDLER_FRAGMENT_TAG);
if (navigationHandlerFragment == null)
{
navigationHandlerFragment = (NavigationHandlerFragment) Fragment.instantiate(
MainActivity.this,
NavigationHandlerFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.add(R.id.leftView, navigationHandlerFragment,
NAVIGATION_HANDLER_FRAGMENT_TAG).commit();
}
if (GuiUtils.checkLoggedIn(true))
{
AccountLimitUtils2.updateLimitInformationCacheAsync(this);
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (currentInstance != null)
{
if (currentInstance.get() == MainActivity.this
|| currentInstance.get() == null)
{
CommonUtils.debug(TAG, "Nullify current instance");
currentInstance = null;
} else
{
CommonUtils.debug(TAG,
"Skipped nullify of current instance, such as it is not the same");
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
instanceSaved = true;
}
@Override
protected void onResume()
{
super.onResume();
instanceSaved = false;
reinitMenu();
if (!Preferences.isLoggedIn(this))
{
// startActivity(new Intent(this, SetupActivity.class));
// startActivity(new Intent(this, AccountActivity.class));
if(Preferences.isSkipIntro() == false)
startActivity(new Intent(this, IntroActivity.class));
else
startActivity(new Intent(this, AccountActivity.class));
finish();
}
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
if (intent != null && intent.getData() != null)
{
Uri uri = intent.getData();
TwitterUtils.verifyOAuthResponse(this, this, uri,
TwitterUtils.getDefaultCallbackUrl(this),
null);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
/*
* if this is the activity result from authorization flow, do a call
* back to authorizeCallback Source Tag: login_tag
*/
case AUTHORIZE_ACTIVITY_REQUEST_CODE: {
FacebookProvider.getFacebook().authorizeCallback(requestCode,
resultCode,
data);
}
break;
}
}
public void reinitMenu()
{
handler.post(new Runnable() {
@Override
public void run() {
invalidateOptionsMenu();
}
});
}
public void reinitMenu(Menu menu)
{
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
reinitMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case android.R.id.home:
TrackerUtils.trackOptionsMenuClickEvent("menu_home", MainActivity.this);
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
addonSlider().toggle();
} else {
onBackPressed();
}
return true;
case R.id.menu_settings: {
TrackerUtils.trackOptionsMenuClickEvent("menu_settings", MainActivity.this);
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
return true;
}
case R.id.menu_camera: {
TrackerUtils.trackOptionsMenuClickEvent("menu_camera", MainActivity.this);
if (!cameraActionProcessing.getAndSet(true))
{
com.trovebox.android.common.net.account.AccountLimitUtils.checkQuotaPerOneUploadAvailableAndRunAsync(
new Runnable() {
@Override
public void run() {
CommonUtils.debug(TAG, "Upload limit check passed");
TrackerUtils.trackLimitEvent("upload_activity_open", "success");
Intent i = new Intent(MainActivity.this, UploadActivity.class);
startActivity(i);
cameraActionProcessing.set(false);
}
},
new Runnable() {
@Override
public void run() {
CommonUtils.debug(TAG, "Upload limit check failed");
TrackerUtils.trackLimitEvent("upload_activity_open", "fail");
cameraActionProcessing.set(false);
}
},
this);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Get the currently selected fragment
*
* @return
*/
public Fragment getCurrentFragment()
{
return navigationHandlerFragment.getCurrentFragment();
}
@Override
public void openGallery(String tag, Album album)
{
navigationHandlerFragment.getGalleryFragment().setCurrentParameters(tag, album, null, null);
selectTab(navigationHandlerFragment.getGalleryIndex());
}
@Override
public void startLoading()
{
if (loaders.getAndIncrement() == 0)
{
reinitMenu();
showLoading(true);
}
}
@Override
public void stopLoading()
{
if (loaders.decrementAndGet() == 0)
{
showLoading(false);
reinitMenu();
}
}
@Override
public boolean isLoading() {
return loaders.get() > 0;
}
private void showLoading(final boolean show)
{
handler.post(new Runnable() {
@Override
public void run() {
setSupportProgressBarIndeterminateVisibility(show);
}
});
}
@Override
public void syncStarted()
{
CommonUtils.debug(TAG, "Sync started");
if (navigationHandlerFragment.getSelectedNavigationIndex() == navigationHandlerFragment
.getSyncIndex())
{
if (!instanceSaved)
{
selectTab(navigationHandlerFragment.getGalleryIndex());
}
}
}
@Override
public void uploadsCleared()
{
SyncFragment fragment = navigationHandlerFragment.getFragment(navigationHandlerFragment
.getSyncIndex());
if (fragment != null)
{
fragment.uploadsCleared();
}
}
@Override
public LoadingControl getTwitterLoadingControl() {
return this;
}
@Override
public LoadingControl getFacebookLoadingControl() {
return this;
}
@Override
public boolean dispatchKeyEvent(android.view.KeyEvent event) {
final int keyCode = event.getKeyCode();
boolean proceed = true;
if (keyCode == KeyEvent.KEYCODE_BACK) {
Fragment fragment = getCurrentFragment();
if (fragment != null && fragment instanceof BackKeyControl) {
proceed &= !((BackKeyControl) fragment).isBackKeyOverrode();
}
}
if (proceed) {
return super.dispatchKeyEvent(event);
}
return proceed;
}
@Override
public void syncStarted(List<String> processedFileNames) {
CommonUtils.debug(TAG, "Sync started call");
SyncFragment syncFragment = navigationHandlerFragment.getSyncFragment();
if (syncFragment != null)
{
syncFragment.syncStarted(processedFileNames);
}
}
@Override
public void startNow() {
CommonUtils.debug(TAG, "Start now");
if (navigationHandlerFragment.getSelectedNavigationIndex() != navigationHandlerFragment
.getSyncIndex())
{
if (!instanceSaved)
{
selectTab(navigationHandlerFragment.getSyncIndex());
}
}
}
private NavigationHandlerFragment navigationHandlerFragment;
/**
* Get the slider addon
*
* @return
*/
public AddonSliderA addonSlider() {
return addon(AddonSlider.class);
}
private int computeMenuWidth() {
return (int) getResources().getDimensionPixelSize(R.dimen.slider_menu_width);
}
/**
* Set the action bar title
*
* @param title
*/
public void setActionBarTitle(String title)
{
mActionBar.setTitle(title);
}
public void selectTab(int index)
{
navigationHandlerFragment.selectTab(index);
}
@Override
public void titleChanged() {
navigationHandlerFragment.refreshActionBarTitle();
}
}
| 33.146497 | 122 | 0.594607 |
f6fb75e1d5c9ef68e78347a335b34b895f49d0f4 | 2,632 | /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.rest.repr;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.kernel.Version;
public class DatabaseRepresentation extends MappingRepresentation implements ExtensibleRepresentation
{
private final GraphDatabaseService graphDb;
public DatabaseRepresentation( GraphDatabaseService graphDb )
{
super( RepresentationType.GRAPHDB );
this.graphDb = graphDb;
}
@Override
public String getIdentity()
{
// This is in fact correct - there is only one graphdb - hence no id
return null;
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "node", "node" );
try
{
// TODO Depracation of reference node
/*
* When the reference node is removed as a concept this try/catch should be removed completely.
* This will make GetOnRootFunctionalTest to break so the two places (at the time of this writing)
* where the field reference_node is checked should just be removed.
*/
serializer.putUri( "reference_node", NodeRepresentation.path( graphDb.getReferenceNode() ) );
}
catch ( NotFoundException e )
{
// serializer.putString( "reference_node","null" );
}
serializer.putUri( "node_index", "index/node" );
serializer.putUri( "relationship_index", "index/relationship" );
serializer.putUri( "extensions_info", "ext" );
serializer.putUri( "relationship_types", "relationship/types" );
serializer.putUri( "batch", "batch" );
serializer.putUri( "cypher", "cypher" );
serializer.putString( "neo4j_version", Version.getKernelRevision() );
}
}
| 37.070423 | 110 | 0.677812 |
33c727e68658a33e156a27ee45487ede71d58781 | 3,721 | package org.firstinspires.ftc.teamcode.test;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.hardware.Button;
import org.firstinspires.ftc.teamcode.hardware.Carousel;
@TeleOp (name = "TestCarouselTuner", group = "PRTest")
public class TestCarouselTuner extends LinearOpMode {
Carousel carousel;
Button left_bumper, right_bumper, a, dpad_left, dpad_right;
double power = 0;
boolean aToggle = false;
boolean dpLeftToggle = false;
boolean dpRightToggle = false;
ElapsedTime time;
double startSpin;
@Override
public void runOpMode() throws InterruptedException {
carousel = new Carousel(hardwareMap.dcMotor.get("leftCarousel"), hardwareMap.dcMotor.get("rightCarousel"));
left_bumper = new Button();
right_bumper = new Button();
a = new Button();
dpad_left = new Button();
dpad_right = new Button();
time = new ElapsedTime();
telemetry.addData("Desc", "Carousel Tuner class");
telemetry.addData("How to Use", "GP1 l/r bumper: decrease/increase power")
.addData("GP1 a", "Toggle carousel")
.addData("GP1 dpad l/r", "Gradual build in power");
telemetry.update();
telemetry.setMsTransmissionInterval(20);
waitForStart();
time.reset();
while (opModeIsActive()) {
left_bumper.previous();
left_bumper.setState(gamepad1.left_bumper);
right_bumper.previous();
right_bumper.setState(gamepad1.right_bumper);
a.previous();
a.setState(gamepad1.a);
if (left_bumper.isPressed()) power -= 0.05;
if (right_bumper.isPressed()) power += 0.05;
dpad_left.previous();
dpad_left.setState(gamepad1.dpad_left);
dpad_right.previous();
dpad_right.setState(gamepad1.dpad_right);
/*
if (dpad_left.isPressed()) {
dpLeftToggle = !dpLeftToggle;
power = -0.4;
}
if (dpad_right.isPressed()) {
dpRightToggle = !dpRightToggle;
power = 0.4;
}
if (dpLeftToggle) {
startSpin = time.milliseconds();
if (time.milliseconds() % 250 > 150) power *= 1.04;
} else if (dpRightToggle) {
if (time.milliseconds() % 250 > 150) power *= 1.04;
} else {
power = 0;
}
*/
if (dpad_left.isPressed()) {
power = -0.4;
startSpin = time.milliseconds();
while (time.milliseconds() < startSpin + 1400) {
if (time.milliseconds() % 250 > 150) power *= 1.04;
if (power > 1) power = 1.0;
carousel.spin(power);
}
carousel.spin(0);
}
/*
if (power > 1) {
power = 1.0;
} else if (power < -1) {
power = -1.0;
}
if (a.isPressed()) aToggle = !aToggle;
if (aToggle) {
carousel.spin(power);
} else {
carousel.stopSpin();
}
*/
telemetry.addData("power", power);
telemetry.addData("a toggle", aToggle);
telemetry.addData("dpad_left toggle", dpLeftToggle);
telemetry.addData("dpad_right toggle", dpRightToggle);
telemetry.update();
}
}
}
| 30.5 | 115 | 0.53749 |
cb4c23f5bdb43cec61bf7aed25d4b9fed5d23c21 | 2,676 | /**
* RobotLib Version Number. Update for each release. Also update overview.html for
* the JavaDoc as well as the readme.md and gradle.properties files.
*/
package Team4450.Lib;
/**
* Provides static access to current version of the library.
*/
public class LibraryVersion
{
/**
* Returns current version of RobotLib.
*/
/*
* When you start a new version of the library, you can change the version here
* so that it is reflected by the robot programs that use the library. After a
* library compile, you go the robot program project's external references and do a
* refresh to pull in the changes. You can push to github along the way to save
* your work. You can also change src/main/resources/overview.html and gradle.properties
* now or just before release. Build the library using Build RobotLib (or offline) not
* Build RobotLib (Release). You can push as needed as you work.
*
* Note: The gradle process stores the compiled library in the local gradle
* cache. The Robot program projects on this PC use a RobotLib.json file that
* specifies local as the desired version number so the library artifacts are
* pulled from the local cache. However, a side effect of this scheme is that
* since the version, "local", never changes, you have to refresh the programs
* external references to have the updated local version pulled into the project.
* Robot projects on other PCs use a RobotLib.json with an actual version number
* to pull that version from the online artifact library Jitpack.io where our
* releases are stored.
*
* When you are ready to release, make sure the readme.md, src/main/resources/overview.html
* and gradle.properties files are set to the new version number. Do a final compile using
* Build RobotLib (Release). Then push to github. Then on the github repository create a
* new release for the new version. This will trigger a Travis-ci compile (on github) which
* will generate the constituent release artifacts (files). It will also store the release
* artifacts on Jitpack.io repository.
*
* Robot program projects on other computers can then download or update their RobotLib.json
* with the new version number. On the next compile gradle will pull down the new library
* release from Jitpack.
*
* Note: The Javadoc output is not pushed to github. Javadoc will be generated as an artifact
* of the Travis compile and will be available in the release for consumption by others.
*/
public static final String version = "3.8.0 (09.23.2021-1)";
// Private constructor means this class can't be instantiated.
private LibraryVersion()
{
}
} | 45.355932 | 95 | 0.741779 |
9e78c07d5f8ce6069e32b88bafe2858b4ac77e61 | 3,067 | package com.todolistapp.restservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
@RestController
public class ToDoEntryController {
Logger log = LoggerFactory.getLogger(ToDoEntryController.class);
JdbcTemplate jdbcTemplate;
public ToDoEntryController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@GetMapping("get_list") //TODO: The input here should be already sanitized, but should double check.
public List<ToDoEntry> returnToDoList(@RequestParam(value = "user", defaultValue = "nobody") String user) {
ArrayList<ToDoEntry> result = new ArrayList<ToDoEntry>();
//jdbcTemplate.query("SELECT id, username, entry "+
//"FROM entries WHERE username = ?", new Object[] { "Nikita" }, (rs, rowNum) -> new ToDoEntry(rs.getString("entry"))).forEach(entry -> forDebug.setContent(forDebug.getContent()+"\nEntry:"+entry.getContent()));
result = jdbcTemplate.query("SELECT id, username, entry FROM entries WHERE username = ?", new ResultSetExtractor<ArrayList<ToDoEntry>>(){
@Override
public ArrayList<ToDoEntry> extractData(ResultSet rs) throws SQLException, DataAccessException {
ArrayList<ToDoEntry> list = new ArrayList<ToDoEntry>();
String content = null;
while(rs.next()) {
content = rs.getString("entry");
list.add(new ToDoEntry(content));
log.info("Added ToDoEntry with content "+content);
}
return list;
}
}, user);
return result;
//Note to self: http://localhost:8080/get_list?user=Nikita
}
@GetMapping("add_to_do_entry") //TODO: Input sanitization on SQL requests!
public void createToDoEntry(@RequestParam(value = "user", defaultValue = "nobody") String user, @RequestParam(value = "entry", defaultValue = "no_entry") String entry) {
if(entry != "no_entry")
/*
jdbcTemplate.update("" +
"IF NOT EXISTS (SELECT * FROM entries WHERE username = '"+user+"')"+
" BEGIN"+
" INSERT INTO entries (username, entry) VALUES ('"+user+"', '"+entry+"')"+
" END"); //Why wouldn't this work? Ok, another solution then.
*/
//This should work.
jdbcTemplate.update("INSERT INTO entries (username, entry) SELECT '"+user+"', '"+entry+"' WHERE NOT EXISTS (SELECT * FROM entries WHERE entry = '"+entry+"')");
//Note to self: localhost:8080/add_to_do_entry?user=Nikita&entry=Kektus
};
} | 44.449275 | 217 | 0.658298 |
08ce288d479bf98d5d504a5c4c7e0dd03250dd53 | 2,526 | package com.tuling.tulingmall.service.impl;
import com.github.pagehelper.PageHelper;
import com.tuling.tulingmall.mapper.SmsHomeBrandMapper;
import com.tuling.tulingmall.model.SmsHomeBrand;
import com.tuling.tulingmall.model.SmsHomeBrandExample;
import com.tuling.tulingmall.service.SmsHomeBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* 首页品牌管理Service实现类
* Created on 2018/11/6.
*/
@Service
public class SmsHomeBrandServiceImpl implements SmsHomeBrandService {
@Autowired
private SmsHomeBrandMapper homeBrandMapper;
@Override
public int create(List<SmsHomeBrand> homeBrandList) {
for (SmsHomeBrand smsHomeBrand : homeBrandList) {
smsHomeBrand.setRecommendStatus(1);
smsHomeBrand.setSort(0);
homeBrandMapper.insert(smsHomeBrand);
}
return homeBrandList.size();
}
@Override
public int updateSort(Long id, Integer sort) {
SmsHomeBrand homeBrand = new SmsHomeBrand();
homeBrand.setId(id);
homeBrand.setSort(sort);
return homeBrandMapper.updateByPrimaryKeySelective(homeBrand);
}
@Override
public int delete(List<Long> ids) {
SmsHomeBrandExample example = new SmsHomeBrandExample();
example.createCriteria().andIdIn(ids);
return homeBrandMapper.deleteByExample(example);
}
@Override
public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
SmsHomeBrandExample example = new SmsHomeBrandExample();
example.createCriteria().andIdIn(ids);
SmsHomeBrand record = new SmsHomeBrand();
record.setRecommendStatus(recommendStatus);
return homeBrandMapper.updateByExampleSelective(record,example);
}
@Override
public List<SmsHomeBrand> list(String brandName, Integer recommendStatus, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum,pageSize);
SmsHomeBrandExample example = new SmsHomeBrandExample();
SmsHomeBrandExample.Criteria criteria = example.createCriteria();
if(!StringUtils.isEmpty(brandName)){
criteria.andBrandNameLike("%"+brandName+"%");
}
if(recommendStatus!=null){
criteria.andRecommendStatusEqualTo(recommendStatus);
}
example.setOrderByClause("sort desc");
return homeBrandMapper.selectByExample(example);
}
}
| 35.577465 | 114 | 0.719715 |
1945bb11b8fc2570ce3b66485849488839a328c2 | 4,302 | package net.fishbulb.jcod;
import mockit.Mocked;
import net.fishbulb.jcod.display.TileDisplay;
import net.fishbulb.jcod.display.Tileset;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
import java.nio.charset.Charset;
import static org.testng.Assert.assertEquals;
public class ConsoleTest {
private static final Logger LOG = Logger.getLogger(ConsoleTest.class);
// not actually useful yet...
@Mocked Tileset mockTileset;
@Mocked TileDisplay mockDisplay;
// helps in diagnosing failed test results
private static byte[] strBytes(String s) {
return s.getBytes(Charset.forName("ISO-8859-1"));
}
@Test
public void testGetColorString() throws Exception {
assertEquals(Console.getColorControlString(Console.COLCTRL_1), "\u0001");
assertEquals(
strBytes(Console.getRGBAColorControlString(Console.COLCTRL_FORE_RGB, 0, 0, 0, 0)),
strBytes("\u0006\0\0\0\0")
);
assertEquals(strBytes(
Console.getRGBAColorControlString(Console.COLCTRL_BACK_RGB, 0.5f, 0.25f, 1f, 0f)),
strBytes("\u0007\u007f\u003f\u00ff\u0000")
);
}
@Test
public void testLineLength() throws Exception {
// one line
assertEquals(Console.lineLength("foobarbaz", 0), 9);
assertEquals(Console.lineLength("foo\u0001bar\u0002baz", 0), 9);
assertEquals(Console.lineLength("foo\u0007abcdbar\u0002baz", 0), 9);
assertEquals(Console.lineLength("", 0), 0);
assertEquals(Console.lineLength("abcdef", 2), 4);
assertEquals(Console.lineLength("abcdef", 10), 0);
// multiple lines
assertEquals(Console.lineLength("foo\u0007abcdbar\u0002baz\nmumble frotz", 0), 9);
assertEquals(Console.lineLength("foo\u0007abcdbar\u0002\nbaz mumble frotz", 0), 6);
assertEquals(Console.lineLength("foo\n\u0007abcdbar\u0002\nbaz mumble frotz", 0), 3);
assertEquals(Console.lineLength("foo\n\u0007abcdbar\u0002\nbaz mumble frotz", 2), 1);
assertEquals(Console.lineLength("foo\n\u0007abcdbar\u0002\nbaz mumble frotz", 3), 0);
assertEquals(Console.lineLength("foo\n\u0007abcdbar\u0002\nbaz mumble frotz", 4), 3);
// \n inside a color escape sequence
assertEquals(Console.lineLength("foo\u0007ab\ndbar\u0002\nbazmumble frotz", 0), 6);
}
@Test
public void testWrap() throws Exception {
assertEquals(Console.wrap("foobarbazmumblefrotz", 20), "foobarbazmumblefrotz");
assertEquals(Console.wrap("foobarbazmumblefrotz", 5), "foobarbazmumblefrotz");
assertEquals(Console.wrap("apple kumquat apple", 10), "apple\nkumquat\napple");
assertEquals(Console.wrap("Lorem ipsum dolor sit amet", 10), "Lorem\nipsum\ndolor sit\namet");
String wrapped;
wrapped = Console.wrap("foo bar baz mumble frotz", 8);
assertEquals(wrapped, "foo bar\nbaz\nmumble\nfrotz");
wrapped = Console.wrap("foo bar baz mumble frotz", 12);
assertEquals(wrapped, "foo bar baz\nmumble frotz");
wrapped = Console.wrap("foo bar baz reallylongstringthatwontwrapnosir mumble frotz", 12);
assertEquals(wrapped, "foo bar baz\nreallylongstringthatwontwrapnosir\nmumble frotz");
wrapped = Console.wrap("reallylongstringthatwontwrapnosir foo bar baz mumble frotz", 12);
assertEquals(wrapped, "reallylongstringthatwontwrapnosir\nfoo bar baz\nmumble frotz");
wrapped = Console.wrap("foo b\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001ar baz mumble frotz", 12);
assertEquals(wrapped, "foo b\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001ar baz\nmumble frotz");
wrapped = Console.wrap("foo b\u0006abcd\u0006abcd\u0007abcd\u0007abcd\u0007abcdar baz mumble frotz", 12);
assertEquals(wrapped, "foo b\u0006abcd\u0006abcd\u0007abcd\u0007abcd\u0007abcdar baz\nmumble frotz");
wrapped = Console.wrap("foo bar baz mumble frotz", 12);
// LOG.warn("\n" + wrapped.replace(" ", "."));
assertEquals(wrapped, "foo bar \nbaz \nmumble \nfrotz");
wrapped = Console.wrap("foo\nbar baz xyz mumble frotz", 12);
assertEquals(wrapped, "foo\nbar baz xyz\nmumble frotz");
}
}
| 43.02 | 123 | 0.682008 |
ce0a628e1e9a81919f54c7f21376f7d1fc6f43d1 | 3,848 | package org.sunbird.badge.service.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.sunbird.common.exception.ProjectCommonException;
import org.sunbird.common.models.response.HttpUtilResponse;
import org.sunbird.common.models.response.Response;
import org.sunbird.common.models.util.BadgingJsonKey;
import org.sunbird.common.models.util.HttpUtil;
import org.sunbird.common.request.Request;
import org.sunbird.common.responsecode.ResponseCode;
import org.sunbird.telemetry.util.TelemetryUtil;
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpUtil.class, TelemetryUtil.class, BadgrServiceImpl.class})
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"})
public class BadgrServiceImplBadgeAssertionTest {
private BadgrServiceImpl badgrServiceImpl;
private Request request;
private static final String BADGE_ASSERTION_REVOKE_RESPONSE_FAILURE =
"Assertion is already revoked.";
private static final String VALUE_ASSERTION_ID = "2093cf30-f82e-4975-88f8-35230832db14";
private static final String VALUE_RECIPIENT_ID = "bf5c4aa7-7d70-4488-915e-6e6ba3f7099b";
private static final String VALUE_RECIPIENT_TYPE_USER = "user";
private static final String VALUE_REVOCATION_REASON = "some reason";
private static final String VALUE_RECIPIENT_EMAIL = "[email protected]";
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(HttpUtil.class);
PowerMockito.mockStatic(TelemetryUtil.class);
PowerMockito.mockStatic(BadgrServiceImpl.class);
badgrServiceImpl = new BadgrServiceImpl();
request = new Request();
}
@Test
public void testRevokeAssertionSuccess() throws IOException {
PowerMockito.when(
HttpUtil.sendDeleteRequest(Mockito.anyString(), Mockito.anyMap(), Mockito.anyString()))
.thenReturn(new HttpUtilResponse("", 200));
PowerMockito.when(badgrServiceImpl.getEmail(Mockito.any(), Mockito.any()))
.thenReturn(VALUE_RECIPIENT_EMAIL);
request.put(BadgingJsonKey.ASSERTION_ID, VALUE_ASSERTION_ID);
request.put(BadgingJsonKey.RECIPIENT_ID, VALUE_RECIPIENT_ID);
request.put(BadgingJsonKey.RECIPIENT_TYPE, VALUE_RECIPIENT_TYPE_USER);
request.put(BadgingJsonKey.REVOCATION_REASON, VALUE_REVOCATION_REASON);
Response response = badgrServiceImpl.revokeAssertion(request);
assertNotEquals(null, response);
assertEquals(ResponseCode.OK, response.getResponseCode());
}
@Test
public void testRevokeAssertionFailure() throws IOException {
PowerMockito.when(
HttpUtil.sendDeleteRequest(Mockito.anyString(), Mockito.anyMap(), Mockito.anyString()))
.thenReturn(new HttpUtilResponse(BADGE_ASSERTION_REVOKE_RESPONSE_FAILURE, 400));
PowerMockito.when(badgrServiceImpl.getEmail(Mockito.any(), Mockito.any()))
.thenReturn(VALUE_RECIPIENT_EMAIL);
request.put(BadgingJsonKey.ASSERTION_ID, VALUE_ASSERTION_ID);
request.put(BadgingJsonKey.RECIPIENT_ID, VALUE_RECIPIENT_ID);
request.put(BadgingJsonKey.RECIPIENT_TYPE, VALUE_RECIPIENT_TYPE_USER);
request.put(BadgingJsonKey.REVOCATION_REASON, VALUE_REVOCATION_REASON);
boolean thrown = false;
try {
badgrServiceImpl.revokeAssertion(request);
} catch (ProjectCommonException exception) {
thrown = true;
assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), exception.getResponseCode());
}
assertEquals(true, thrown);
}
}
| 40.083333 | 99 | 0.785863 |
210541ae41bdec0e0ed8d9b7a94829cd4e6d9fad | 754 | package io.horizon.market.handler;
import org.junit.Test;
public class MarketDataMulticasterTest {
@Test
public void test() {
// private final MarketDataMulticaster<FtdcDepthMarketData, FastMarketDataBridge> multicaster = new MarketDataMulticaster<>(
// getAdaptorId(), FastMarketDataBridge::newInstance, (marketData, sequence, ftdcMarketData) -> {
// Instrument instrument = InstrumentKeeper.getInstrument(ftdcMarketData.getInstrumentID());
// marketData.setInstrument(instrument);
// var multiplier = instrument.getSymbol().getMultiplier();
// var fastMarketData = marketData.getFastMarketData();
// // TODO
// fastMarketData.setLastPrice(multiplier.toLong(ftdcMarketData.getLastPrice()));
// marketData.updated();
// });
}
}
| 31.416667 | 125 | 0.758621 |
80357ead6f2752637a1d988066d792ddff54dc1a | 2,928 | package com.kyperbox.systems;
import com.badlogic.gdx.maps.MapProperties;
import com.kyperbox.objects.GameLayer;
import com.kyperbox.objects.GameObject;
import com.kyperbox.objects.GameObject.GameObjectChangeType;
import com.kyperbox.umisc.Event;
import com.kyperbox.umisc.EventListener;
public abstract class LayerSystem extends AbstractSystem{
private EventListener<GameObject> gameObjectAdded;
private EventListener<GameObject> gameObjectRemoved;
private EventListener<GameObject> gameObjectControllerChanged;
public LayerSystem() {
gameObjectAdded = new GameObjectAddedListener();
gameObjectRemoved = new GameObjectRemovedListener();
gameObjectControllerChanged = new GameObjectControllerChangedListener();
}
@Override
public void addedToLayer(GameLayer layer) {
layer.gameObjectAdded.add(gameObjectAdded);
layer.gameObjectRemoved.add(gameObjectRemoved);
layer.gameObjectControllerChanged.add(gameObjectControllerChanged);
init(layer.getLayerProperties());
}
@Override
public void removedFromLayer(GameLayer layer) {
layer.gameObjectAdded.remove(gameObjectAdded);
layer.gameObjectRemoved.remove(gameObjectRemoved);
layer.gameObjectControllerChanged.remove(gameObjectControllerChanged);
onRemove();
}
/**
* called when the gamelayer and tmx is fully loaded
* @param properties
*/
public abstract void init(MapProperties properties);
/**
*A new gameObject has been added to the layer
* @param object
*/
public abstract void gameObjectAdded(GameObject object,GameObject parent);
/**
* an object has been altered drastically
* right now that means that its managers have been changed
* @param object
*/
public abstract void gameObjectChanged(GameObject object,int type,float value);
/**
* a game object has been removed from this
*/
public abstract void gameObjectRemoved(GameObject object,GameObject parent);
/**
* on layer update
* @param delta
*/
public abstract void update(float delta);
/**
* when the layer is removed
*/
public abstract void onRemove();
public class GameObjectAddedListener implements EventListener<GameObject>{
@Override
public void process(Event<GameObject> event, GameObject object) {
gameObjectAdded(object, null);
}
}
public class GameObjectRemovedListener implements EventListener<GameObject>{
@Override
public void process(Event<GameObject> event, GameObject object) {
gameObjectRemoved(object, null);
}
}
public class GameObjectControllerChangedListener implements EventListener<GameObject>{
@Override
public void process(Event<GameObject> event, GameObject object) {
gameObjectChanged(object, GameObjectChangeType.CONTROLLER, 1);
}
}
// public void refresh() {
// GameLayer layer = getLayer();
// for(Actor actor:layer.getChildren()) {
// GameObject base_object = (GameObject) actor;
// gameObjectAdded(base_object, null);
// }
// }
}
| 27.111111 | 87 | 0.767418 |
a0429d21c678fddcf9beac2d81b97d8e7ee37487 | 3,777 | /*
* MIT License
*
* Copyright (c) 2021 Brandon Li
*
* 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 io.github.pulsebeat02.deluxemediaplugin.utility;
import static net.kyori.adventure.text.Component.join;
import static net.kyori.adventure.text.Component.newline;
import static net.kyori.adventure.text.Component.space;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.JoinConfiguration.separator;
import static net.kyori.adventure.text.format.NamedTextColor.AQUA;
import static net.kyori.adventure.text.format.NamedTextColor.GOLD;
import static net.kyori.adventure.text.format.NamedTextColor.LIGHT_PURPLE;
import static net.kyori.adventure.text.format.NamedTextColor.RED;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.TextComponent;
import org.jetbrains.annotations.NotNull;
public final class ChatUtils {
private ChatUtils() {
}
public static @NotNull Optional<int[]> checkDimensionBoundaries(
@NotNull final Audience sender, @NotNull final String str) {
final String[] dims = str.split(":");
final String message;
final OptionalInt width = ChatUtils.checkIntegerValidity(dims[0]);
final OptionalInt height = ChatUtils.checkIntegerValidity(dims[1]);
if (width.isEmpty()) {
message = dims[0];
} else if (height.isEmpty()) {
message = dims[1];
} else {
return Optional.of(new int[]{width.getAsInt(), height.getAsInt()});
}
sender.sendMessage(
text()
.color(RED)
.append(text("Argument '"))
.append(text(str, GOLD))
.append(text("' "))
.append(text(message))
.append(text(" is not a valid argument!"))
.append(text(" (Must be Integer)")));
return Optional.empty();
}
public static @NotNull OptionalInt checkIntegerValidity(@NotNull final String num) {
try {
return OptionalInt.of(Integer.parseInt(num));
} catch (final NumberFormatException e) {
return OptionalInt.empty();
}
}
public static @NotNull TextComponent getCommandUsage(@NotNull final Map<String, String> usages) {
final TextComponent.Builder builder =
text().append(text("------------------", AQUA)).append(newline());
for (final Map.Entry<String, String> entry : usages.entrySet()) {
builder.append(
join(
separator(space()),
text(entry.getKey(), LIGHT_PURPLE),
text("-", GOLD),
text(entry.getValue(), AQUA),
newline()));
}
builder.append(text("------------------", AQUA));
return builder.build();
}
}
| 38.540816 | 99 | 0.694731 |
d160695399e8f1c9a57d35876a0d3585de87ee0a | 2,204 | package org.sonar.plugins.coverageevolution;
import org.junit.Test;
import org.sonar.api.resources.File;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.sonar.plugins.coverageevolution.CoverageUtils.calculateCoverage;
import static org.sonar.plugins.coverageevolution.CoverageUtils.computeEffectiveKey;
import static org.sonar.plugins.coverageevolution.CoverageUtils.roundedPercentageGreaterThan;
public class CoverageUtilsTest {
private static final double DELTA = 1e-6;
@Test
public void testCalculateCoverage() {
assertEquals(100.0, calculateCoverage(0, 0), DELTA); // special case
assertEquals(50.0, calculateCoverage(100, 50), DELTA);
assertEquals(94.5, calculateCoverage(1000, 55), DELTA);
assertEquals(87.3, calculateCoverage(1000, 127), DELTA);
assertEquals(31.09, calculateCoverage(10000, 6891), DELTA);
assertEquals(0.27, calculateCoverage(10000, 9973), DELTA);
// not a wanted case but it works with current implementation (so good future exception test)
assertEquals(200, calculateCoverage(100, -100), DELTA);
}
@Test
public void testRounderPercentageGreaterThan() {
assertTrue(roundedPercentageGreaterThan(1.1, 1.0));
assertFalse(roundedPercentageGreaterThan(1.0, 1.0));
assertFalse(roundedPercentageGreaterThan(0.9, 1.0));
assertFalse(roundedPercentageGreaterThan(1.04, 1.0));
assertTrue(roundedPercentageGreaterThan(1.05, 1.0));
}
@Test
public void testComputeEffectiveKey() {
Project module = new Project("foo:bar");
assertEquals(
"foo:bar",
computeEffectiveKey(new Project("foo:bar"), module)
);
assertEquals(
"baz",
computeEffectiveKey(new Project("baz"), module)
);
Resource r = File.create("xyz");
assertEquals(
"foo:bar:xyz",
computeEffectiveKey(r, module)
);
r.setEffectiveKey("quux");
assertEquals(
"quux",
computeEffectiveKey(r, module)
);
}
}
| 33.907692 | 98 | 0.705535 |
eebe7bcfd374efec3a45a4736412d696dd49d5e9 | 2,307 | package com.jetlag.jcreator.pictures;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
/**
* Created by vince on 17/04/16.
*/
public class DevicePicture implements Picture, Parcelable {
private String storeId;
private double latitude;
private double longitude;
private String description;
private boolean picked;
private State uploadState = State.LOCAL;
public DevicePicture() {}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Uri getUri() {
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, storeId);
}
public void setPicked(boolean picked) {
this.picked = picked;
}
public boolean isPicked() {
return picked;
}
@Override
public State getState() {
return uploadState;
}
/*
* Parcelable
*/
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<DevicePicture> CREATOR
= new Parcelable.Creator<DevicePicture>() {
public DevicePicture createFromParcel(Parcel in) {
return new DevicePicture(in);
}
public DevicePicture[] newArray(int size) {
return new DevicePicture[size];
}
};
private DevicePicture(Parcel in) {
storeId = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
description = in.readString();
picked = in.readInt() > 0;
uploadState = State.valueOf(in.readString());
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(storeId);
parcel.writeDouble(latitude);
parcel.writeDouble(longitude);
parcel.writeString(description);
parcel.writeInt(picked ? 1 : 0);
parcel.writeString(uploadState.name());
}
}
| 20.783784 | 87 | 0.690507 |
13854ebfb2ce14853840d84bd63cc1c8095b59fd | 366 | package ua.block06.trainigcod.exceptions.part_II;
/**
* Created on 22.02.2019.
*
* @author Aleks Sidorenko ([email protected]).
* @version $Id$.
* @since 0.1.
*/
public class App23 {
public static void f0(Throwable t) throws Exception {
//throw t;
}
public static void f1(Object ref){
//char c = ref.charAt(0);
}
}
| 19.263158 | 58 | 0.622951 |
7a42fb42223b967fe9b0fbb2efcfe7c1d9022c20 | 7,519 | package com.cisco.flare.trilateral;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.content.Context;
import android.content.Intent;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.cisco.flare.trilateral.common.Constants;
import com.cisco.flare.trilateral.DrawableThing;
import com.cisco.flare.trilateral.Scene;
import com.cisco.flare.Thing;
import com.cisco.flare.trilateral.common.HTMLColors;
import com.cisco.flare.trilateral.common.ScreenDensity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class CompassView extends SurfaceView {
private static String TAG = "CompassView";
private Paint piePaint;
private FullScreenAnimationThread animationThread;
public Scene myScene;
private float globalAngle;
private float environmentAngle;
private RectF rectF;
protected TouchInformation touchInfo;
private Paint touchCirclePaint;
private float finStrokeWidth = Constants.FLARE_FIN_ARC_STROKE_WIDTH;
private float nearFinStrokeWidth = Constants.FLARE_FIN_ARC_STROKE_WIDTH * 2.0f;
protected boolean handleTouchEvents = false;
public CompassView(Context context) {
super(context);
init();
}
public CompassView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CompassView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setHandleTouchEvents(boolean value) {
handleTouchEvents = value;
}
public synchronized void setGlobalAngle(float a) {
// System.out.println("!angle: "+a);
// Canvas canvas = surfaceHolder.lockCanvas();
// synchronized (surfaceHolder) {
globalAngle = a;
// }
// surfaceHolder.unlockCanvasAndPost(canvas);
}
private void init() {
globalAngle = 0.0f;
myScene = new Scene();
touchInfo = new TouchInformation();
handleTouchEvents = true;
addSceneCallback();
setZOrderOnTop(true);
final CompassView thisView = this;
SurfaceHolder surfaceHolder = getHolder();
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d("FullScreenView", "surfaceCreated");
rectF = new RectF();
updateFinStrokeWidth(false, finStrokeWidth);
touchCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
touchCirclePaint.setStrokeWidth(finStrokeWidth);
touchCirclePaint.setStyle(Paint.Style.STROKE);
touchCirclePaint.setColor(0x88f000ff);
piePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
piePaint.setStrokeWidth(1);
piePaint.setStyle(Paint.Style.STROKE);
piePaint.setColor(0x50ffffff);
animationThread = new FullScreenAnimationThread(thisView);
animationThread.setRunning(true);
animationThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
animationThread.setRunning(false);
while (retry) {
try {
animationThread.join();
retry = false;
animationThread = null;
} catch (InterruptedException e) {
}
}
}
});
}
public synchronized void updateFinStrokeWidth(boolean nearFin, float w) {
// Canvas canvas = surfaceHolder.lockCanvas();
//
// if (canvas != null) {
// synchronized (surfaceHolder) {
if (nearFin) {
nearFinStrokeWidth = ScreenDensity.dpsToPixels(w);
}
else {
finStrokeWidth = ScreenDensity.dpsToPixels(w);
float halfStrokeWidth = finStrokeWidth / 2;
float rectWidth = getWidth() - halfStrokeWidth,
rectHeight = getHeight() - halfStrokeWidth;
rectF.set(halfStrokeWidth, halfStrokeWidth, rectWidth, rectHeight);
}
// }
// surfaceHolder.unlockCanvasAndPost(canvas);
// }
}
public synchronized void setEnvAngle(double angle) {
environmentAngle = (float)angle;
}
public synchronized void setUserPosition(PointF userPosition) {
myScene.setUserPosition(userPosition);
}
public synchronized void replaceObjects(ArrayList<Thing> things) {
myScene.replaceObjects(things);
}
protected synchronized void drawScene(Canvas canvas) {
// draw the background (clear the screen)
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
// draw the objects
myScene.draw(rectF, canvas, 0 - environmentAngle + globalAngle, touchInfo, finStrokeWidth, nearFinStrokeWidth);
}
public void selectThing(Thing thing) {
myScene.selectThing(thing);
}
private void addSceneCallback() {
// when the selection changes, notify the wearable and the mobile
// In each case, CommonDrawingActivity will get the notification and update the view accordingly
myScene.addSceneChangedCallback(new Scene.SceneChangedCallback() {
@Override
public void selectionChanged(final Thing thing) {
setNearbyThing(thing);
}
});
}
private void setNearbyThing(final Thing thing) {
if (thing != null) {
Log.d(TAG, "Selected thing: " + thing.getName());
final WearActivity activity = (WearActivity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.setNearbyThing(thing);
}
});
}
}
public void updateColor(Thing thing) {
myScene.updateColor(thing);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!handleTouchEvents) {
return false;
}
touchInfo.coordinates.x = event.getX();
touchInfo.coordinates.y = event.getY();
DrawableThing touchedThing = myScene.getTouchedThing();
String thingName = " "+(touchedThing == null ? "null" : touchedThing.getName());
if (MotionEvent.ACTION_DOWN == event.getAction()) {
Log.d("onTouchEvent", "DOWN " + touchInfo.getCoordinates() + thingName);
touchInfo.screenTouched = true;
}
else if (MotionEvent.ACTION_UP == event.getAction()) {
Log.d("onTouchEvent", " UP " + touchInfo.getCoordinates() + thingName);
// find the first object being touched (there could be more than one if they overlap)
// and display information about this object
myScene.selectTouchedThing();
touchInfo.screenTouched = false;
// check if the user dropped something in the drag&drop area of the screen
if (touchedThing != null) {
PointF center = new PointF(this.getWidth() / 2, this.getHeight() / 2);
double distanceFromMiddleOfScreen = DrawableThing.distanceBetweenTwoPoints(touchInfo.coordinates, center);
Log.d("distance", "to "+center.x+","+center.y+" = "+distanceFromMiddleOfScreen);
if (distanceFromMiddleOfScreen <= Constants.DRAG_DROP_RADIUS) {
Log.d(TAG, "Swiped thing: " + touchedThing);
}
}
}
else if (MotionEvent.ACTION_MOVE == event.getAction()) {
Log.d("onTouchEvent", "MOVE " + touchInfo.getCoordinates() + thingName);
// nothing to do here, screenBeingTouched is already true
}
else
Log.d("onTouchEvent", "action "+event.getAction()+" not handled");
return touchedThing != null;
}
}
| 29.256809 | 113 | 0.729219 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.