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
|
|---|---|---|---|---|---|
4f345eacc5b110017264f6d105c418c273260b79
| 521
|
package com.wemirr.platform.authority.service;
import com.wemirr.framework.db.mybatis.SuperService;
import com.wemirr.platform.authority.domain.entity.tenant.Tenant;
import com.wemirr.platform.authority.domain.entity.tenant.TenantConfig;
/**
* @author Levin
*/
public interface TenantService extends SuperService<Tenant> {
/**
* 保存租户
*
* @param tenant 租户信息
*/
void saveOrUpdateTenant(Tenant tenant);
void tenantConfig(TenantConfig tenantConfig);
void initSqlScript(Long id);
}
| 21.708333
| 71
| 0.735125
|
30c72e5d68ada3a67980c1775d0e4d12893b76de
| 2,565
|
package com.quran.labs.androidquran.model.bookmark;
import com.quran.labs.androidquran.R;
import com.quran.labs.androidquran.dao.BookmarkData;
import com.quran.labs.androidquran.database.BookmarksDBAdapter;
import android.content.Context;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import rx.Observable;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class BookmarkImportExportModel {
private static final String FILE_NAME = "quran_android.backup";
private final Context appContext;
private final BookmarkJsonModel jsonModel;
private final BookmarkModel bookmarkModel;
@Inject
public BookmarkImportExportModel(Context appContext,
BookmarkJsonModel model, BookmarkModel bookmarkModel) {
this.appContext = appContext;
this.jsonModel = model;
this.bookmarkModel = bookmarkModel;
}
public Observable<BookmarkData> readBookmarks(final BufferedSource source) {
return Observable.defer(new Func0<Observable<BookmarkData>>() {
@Override
public Observable<BookmarkData> call() {
try {
return Observable.just(jsonModel.fromJson(source));
} catch (IOException ioe) {
return Observable.error(ioe);
}
}
}).subscribeOn(Schedulers.io());
}
public Observable<Uri> exportBookmarksObservable() {
return bookmarkModel.getBookmarkDataObservable(BookmarksDBAdapter.SORT_DATE_ADDED)
.flatMap(new Func1<BookmarkData, Observable<Uri>>() {
@Override
public Observable<Uri> call(BookmarkData bookmarkData) {
try {
return Observable.just(exportBookmarks(bookmarkData));
} catch (IOException ioe) {
return Observable.error(ioe);
}
}
}).subscribeOn(Schedulers.io());
}
private Uri exportBookmarks(BookmarkData data) throws IOException {
Uri result = null;
File externalFilesDir = new File(appContext.getExternalFilesDir(null), "backups");
if (externalFilesDir.exists() || externalFilesDir.mkdir()) {
File file = new File(externalFilesDir, FILE_NAME);
BufferedSink sink = Okio.buffer(Okio.sink(file));
jsonModel.toJson(sink, data);
sink.close();
result = FileProvider.getUriForFile(
appContext, appContext.getString(R.string.file_authority), file);
}
return result;
}
}
| 31.666667
| 86
| 0.71462
|
2a74e7593a66f7e6221f15f3d2d481ed9d09aab3
| 4,012
|
package tech.linjiang.android.pandora.ui;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import tech.linjiang.android.pandora.utils.ThreadPool;
import tech.linjiang.pandora.ui.recyclerview.UniversalAdapter;
import tech.linjiang.pandora.util.ViewKnife;
public class PicturesActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewKnife.transStatusBar(getWindow());
ViewKnife.setStatusBarColor(getWindow(), Color.TRANSPARENT);
RecyclerView recyclerView = new RecyclerView(this);
UniversalAdapter adapter;
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
recyclerView.setAdapter(adapter = new UniversalAdapter());
List<PictureItem> items = new ArrayList<>();
items.add(new PictureItem("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=973231800,2770258116&fm=27&gp=0.jpg"));
items.add(new PictureItem("http://img5.imgtn.bdimg.com/it/u=328517395,2303970886&fm=26&gp=0.jpg"));
items.add(new PictureItem("http://img5.imgtn.bdimg.com/it/u=1810050752,207505815&fm=200&gp=0.jpg"));
items.add(new PictureItem("http://img3.imgtn.bdimg.com/it/u=2593029726,847983021&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2891178660,473481395&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=923155321,1503094790&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=138662523,3773165341&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=814663857,560789006&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1741054598,1265588416&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=691950827,2308454275&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3823674128,1284221604&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=744475572,1363633948&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1814913138,2431912228&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2805867659,1277717018&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1436755091,2612803750&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2003961533,572853730&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1863669792,1614717395&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1317349462,3646749915&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2034840885,4119412488&fm=26&gp=0.jpg"));
items.add(new PictureItem("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1237415688,2071220902&fm=26&gp=0.jpg"));
adapter.setItems(items);
setContentView(recyclerView);
}
@Override
protected void onDestroy() {
Glide.get(this).clearMemory();
ThreadPool.post(() -> {
Glide.get(this).clearDiskCache();
});
super.onDestroy();
}
}
| 60.787879
| 133
| 0.740279
|
3eb8170ad001481f3af2f45927efb9d4a0dca780
| 3,840
|
/**
* @author Virtusa
*/
package org.bian.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.bian.dto.*;
import org.bian.util.JsonReader;
import com.fasterxml.jackson.core.type.TypeReference;
@Service
public class CustomerCaseApiServiceImpl implements CustomerCaseApiService {
public CustomerCaseCustomerCaseWithIdAndRoot executePost(CustomerCaseCustomerCaseBase request){
return JsonReader.read("executePost-CustomerCaseCustomerCaseWithIdAndRoot.json",new TypeReference<CustomerCaseCustomerCaseWithIdAndRoot>(){});
}
public CustomerCaseCustomerCaseWithIdAndRoot executePut(String crReferenceId, CustomerCaseCustomerCaseBase request){
return JsonReader.read("executePut-CustomerCaseCustomerCaseWithIdAndRoot.json",new TypeReference<CustomerCaseCustomerCaseWithIdAndRoot>(){});
}
public CustomerCaseRecordResponse record(String crReferenceId, CustomerCaseRecordRequest request){
return JsonReader.read("record-CustomerCaseRecordResponse.json",new TypeReference<CustomerCaseRecordResponse>(){});
}
public CustomerCaseDeterminationWithIdAndRoot requestPostDetermination(String crReferenceId, CustomerCaseDeterminationBase request){
return JsonReader.read("requestPost-CustomerCaseDeterminationWithIdAndRoot.json",new TypeReference<CustomerCaseDeterminationWithIdAndRoot>(){});
}
public CustomerCaseDeterminationWithIdAndRoot requestPutDetermination(String crReferenceId, String bqReferenceId, CustomerCaseDeterminationBase request){
return JsonReader.read("requestPut-CustomerCaseDeterminationWithIdAndRoot.json",new TypeReference<CustomerCaseDeterminationWithIdAndRoot>(){});
}
public CustomerCaseCustomerCaseWithIdAndRoot retrieve(String crReferenceId){
return JsonReader.read("retrieve-CustomerCaseCustomerCaseWithIdAndRoot.json",new TypeReference<CustomerCaseCustomerCaseWithIdAndRoot>(){});
}
public CustomerCaseAnalysisWithIdAndRoot retrieveAnalyses(String crReferenceId, String bqReferenceId){
return JsonReader.read("retrieve-CustomerCaseAnalysisWithIdAndRoot.json",new TypeReference<CustomerCaseAnalysisWithIdAndRoot>(){});
}
public List<String> retrieveBQIds(String crReferenceId, String behaviorQualifier){
return JsonReader.read("retrieveBQIds-String.json",new TypeReference<List<String>>(){});
}
public List<String> retrieveBQs(){
return JsonReader.read("retrieveBQs-String.json",new TypeReference<List<String>>(){});
}
public CustomerCaseDeterminationWithIdAndRoot retrieveDetermination(String crReferenceId, String bqReferenceId){
return JsonReader.read("retrieve-CustomerCaseDeterminationWithIdAndRoot.json",new TypeReference<CustomerCaseDeterminationWithIdAndRoot>(){});
}
public CustomerCaseProceduresWithIdAndRoot retrieveProcedures(String crReferenceId, String bqReferenceId){
return JsonReader.read("retrieve-CustomerCaseProceduresWithIdAndRoot.json",new TypeReference<CustomerCaseProceduresWithIdAndRoot>(){});
}
public List<String> retrieveRefIds(){
return JsonReader.read("retrieveRefIds-String.json",new TypeReference<List<String>>(){});
}
public CustomerCaseReportingWithIdAndRoot retrieveReportings(String crReferenceId, String bqReferenceId){
return JsonReader.read("retrieve-CustomerCaseReportingWithIdAndRoot.json",new TypeReference<CustomerCaseReportingWithIdAndRoot>(){});
}
public CustomerCaseResolutionWithIdAndRoot retrieveResolutions(String crReferenceId, String bqReferenceId){
return JsonReader.read("retrieve-CustomerCaseResolutionWithIdAndRoot.json",new TypeReference<CustomerCaseResolutionWithIdAndRoot>(){});
}
public CustomerCaseCustomerCaseWithIdAndRoot update(String crReferenceId, CustomerCaseCustomerCaseBase request){
return JsonReader.read("update-CustomerCaseCustomerCaseWithIdAndRoot.json",new TypeReference<CustomerCaseCustomerCaseWithIdAndRoot>(){});
}
}
| 49.87013
| 154
| 0.841927
|
8cd033653d2eae78afd2d2a115b442b59016b22a
| 773
|
package com.example.haams.myapplication.sms;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by haams on 2017-08-28.
*/
public class RandomAuthNumber {
Context context;
public RandomAuthNumber(Context context) {
this.context = context;
}
public void saveAuthRandNum(String key,String authNum){
SharedPreferences prefs = context.getSharedPreferences("prefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key,authNum);
editor.commit();
}
public String getAuthRandNum(String key){
SharedPreferences prefs = context.getSharedPreferences("prefs",Context.MODE_PRIVATE);
return prefs.getString(key,"");
}
}
| 27.607143
| 93
| 0.707633
|
b0d39e20a25bfa1cf2c3b2ca4b16790082202987
| 3,836
|
package org.season.ymir.core.heartbeat;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.season.ymir.common.base.MessageTypeEnum;
import org.season.ymir.common.base.SerializationTypeEnum;
import org.season.ymir.common.model.InvocationMessageWrap;
import org.season.ymir.common.model.Request;
import org.season.ymir.common.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 心跳请求处理器
*
* @author KevinClair
**/
@ChannelHandler.Sharable
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(HeartBeatServerHandler.class);
/**
* Channel 映射,存储Channel信息
*/
private ConcurrentMap<ChannelId, Channel> channels = new ConcurrentHashMap<>();
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
// 从管理器中添加
channels.put(ctx.channel().id(), ctx.channel());
logger.info("Netty server, one active channel add, channel info:{}", ctx.channel());
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
// 移除 channels
channels.remove(ctx.channel().id());
logger.info("Netty server, one channel unregistered, channel info:{}", ctx.channel());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 移除 channels
channels.remove(ctx.channel().id());
// 断开连接
ctx.close();
logger.error("Netty server, one channel caught error, channel info:{}, exception:{}", ctx.channel(), ExceptionUtils.getStackTrace(cause));
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
// 判断是否为读事件
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE){
Channel channel = ctx.channel();
logger.warn("Heartbeat check, it's more than two minutes since the last heartbeat,channel {} has lost connection.", channel.id());
channels.remove(channel.id());
ctx.close();
}
return;
}
super.userEventTriggered(ctx, evt);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
InvocationMessageWrap<Request> request = (InvocationMessageWrap<Request>) msg;
if (request.getType().equals(MessageTypeEnum.HEART_BEAT_RQEUEST)){
if (logger.isDebugEnabled()) {
logger.debug("Server heartbeat request:{}", GsonUtils.getInstance().toJson(request));
}
InvocationMessageWrap responseInvocationMessage = new InvocationMessageWrap();
responseInvocationMessage.setType(MessageTypeEnum.HEART_BEAT_RESPONSE);
responseInvocationMessage.setSerial(SerializationTypeEnum.PROTOSTUFF);
responseInvocationMessage.setRequestId(Integer.MIN_VALUE);
responseInvocationMessage.setData(null);
ctx.channel().writeAndFlush(responseInvocationMessage).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
;
ReferenceCountUtil.release(msg);
} else {
ctx.fireChannelRead(msg);
}
}
}
| 39.142857
| 146
| 0.699948
|
c0f4192b4f6553da5a92d6482bb47f6939891fae
| 739
|
package com.teashurov.algo.sort;
import com.teashurov.algo.commons.Printer;
import com.teashurov.algo.commons.Swapper;
/*
* O(n2) time complexity quadratic
* In our case, larger number will bubble to end of the array in each unsorted iteration
* stable
* */
public class BubbleSort extends Swapper {
public void sort() {
int[] intArray = {1, 54, 2, 4, 5, 7, 1, -1, -30};
for (int lastUnsortedIndex = intArray.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex; i++) {
if (intArray[i] > intArray[i + 1]) {
swap(intArray, i, i + 1);
}
}
}
Printer.printObj(intArray);
}
}
| 27.37037
| 103
| 0.581867
|
e943800d8a6d5aa0abcc5cae6018857f13ce4b8c
| 195
|
package com.k8s.xmetrics.service.hardware;
import com.k8s.xmetrics.model.hardware.ComputerInfo;
/**
* @author apastoriza
*/
public interface ComputerInfoService {
ComputerInfo readInfo();
}
| 17.727273
| 52
| 0.774359
|
9cbba8ae9cbb260ce6528e0cc26fb8dd348b7eee
| 11,881
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyun.oss.integrationtests;
import junit.framework.Assert;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.CreateUdfApplicationRequest;
import com.aliyun.oss.model.CreateUdfRequest;
import com.aliyun.oss.model.GetUdfApplicationLogRequest;
import com.aliyun.oss.model.ResizeUdfApplicationRequest;
import com.aliyun.oss.model.UdfApplicationConfiguration;
import com.aliyun.oss.model.UdfApplicationInfo;
import com.aliyun.oss.model.UdfApplicationLog;
import com.aliyun.oss.model.UdfGenericRequest;
import com.aliyun.oss.model.UdfImageInfo;
import com.aliyun.oss.model.UdfInfo;
import com.aliyun.oss.model.UpgradeUdfApplicationRequest;
import com.aliyun.oss.model.UploadUdfImageRequest;
@Ignore
public class UdfTest extends TestBase {
private static final String UDF_IMG_V1 = "D:\\work\\oss\\udf\\udf-go-pingpong.tar.gz";
private static final String UDF_IMG_V2 = "D:\\work\\oss\\udf\\udf-go-pingpong-upgrade.tar.gz";
@Test
public void testUdf() {
String udf = "udf-go-pingpong-1";
String desc = "udf-go-pingpong-1";
try {
// create udf
CreateUdfRequest createUdfRequest = new CreateUdfRequest(udf, desc);
ossClient.createUdf(createUdfRequest);
UdfGenericRequest genericRequest = new UdfGenericRequest(udf);
UdfInfo ui = ossClient.getUdfInfo(genericRequest);
System.out.println(ui);
// list image info
List<UdfImageInfo> udfImages = ossClient.getUdfImageInfo(genericRequest);
for (UdfImageInfo image : udfImages) {
System.out.println(image);
}
List<UdfInfo> udfs = ossClient.listUdfs();
for (UdfInfo u : udfs) {
System.out.println(u);
}
// delete udf
ossClient.deleteUdf(genericRequest);
udfs = ossClient.listUdfs();
System.out.println("After delete:");
for (UdfInfo u : udfs) {
System.out.println(u);
}
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
}
}
@Test
public void testUdfImage() {
String udf = "udf-go-pingpong-1";
String desc = "udf-go-pingpong-1";
try {
// create udf
CreateUdfRequest createUdfRequest = new CreateUdfRequest(udf, desc);
ossClient.createUdf(createUdfRequest);
UdfGenericRequest genericRequest = new UdfGenericRequest(udf);
UdfInfo ui = ossClient.getUdfInfo(genericRequest);
System.out.println(ui);
// upload image
InputStream in = new FileInputStream(UDF_IMG_V1);
UploadUdfImageRequest uploadUdfImageRequest = new UploadUdfImageRequest(udf, desc, in);
ossClient.uploadUdfImage(uploadUdfImageRequest);
in = new FileInputStream(UDF_IMG_V2);
uploadUdfImageRequest = new UploadUdfImageRequest(udf, desc, in);
ossClient.uploadUdfImage(uploadUdfImageRequest);
List<UdfImageInfo> udfImages = ossClient.getUdfImageInfo(genericRequest);
for (UdfImageInfo image : udfImages) {
System.out.println(image);
}
// wait build completed
for (UdfImageInfo image : udfImages) {
if (image.getStatus().equals("building")) {
TestUtils.waitForCacheExpiration(60);
udfImages = ossClient.getUdfImageInfo(genericRequest);
continue;
}
}
// delete udf image
ossClient.deleteUdfImage(genericRequest);
// wait images deleted
udfImages = ossClient.getUdfImageInfo(genericRequest);
for (; udfImages.size() > 0;) {
TestUtils.waitForCacheExpiration(60);
udfImages = ossClient.getUdfImageInfo(genericRequest);
}
// delete image
ossClient.deleteUdf(genericRequest);
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
}
}
@Test
public void testUdfApplication() {
String udf = "udf-go-pingpong-1";
String desc = "udf-go-pingpong-1";
try {
// create udf
CreateUdfRequest createUdfRequest = new CreateUdfRequest(udf, desc);
ossClient.createUdf(createUdfRequest);
UdfGenericRequest genericRequest = new UdfGenericRequest(udf);
UdfInfo ui = ossClient.getUdfInfo(genericRequest);
System.out.println(ui);
// upload image
InputStream in = new FileInputStream(UDF_IMG_V1);
UploadUdfImageRequest uploadUdfImageRequest = new UploadUdfImageRequest(udf, desc, in);
ossClient.uploadUdfImage(uploadUdfImageRequest);
in = new FileInputStream(UDF_IMG_V2);
uploadUdfImageRequest = new UploadUdfImageRequest(udf, desc, in);
ossClient.uploadUdfImage(uploadUdfImageRequest);
List<UdfImageInfo> udfImages = ossClient.getUdfImageInfo(genericRequest);
for (UdfImageInfo image : udfImages) {
System.out.println(image);
}
// wait build completed
for (UdfImageInfo image : udfImages) {
if (image.getStatus().equals("building")) {
TestUtils.waitForCacheExpiration(60);
udfImages = ossClient.getUdfImageInfo(genericRequest);
continue;
}
}
// list images
udfImages = ossClient.getUdfImageInfo(genericRequest);
for (UdfImageInfo image : udfImages) {
System.out.println(image);
}
// list applications
List<UdfApplicationInfo> appInfos = ossClient.listUdfApplications();
for (UdfApplicationInfo app : appInfos) {
System.out.println(app);
}
// create application
UdfApplicationConfiguration configuration = new UdfApplicationConfiguration(1, 1);
CreateUdfApplicationRequest createUdfApplicationRequest = new CreateUdfApplicationRequest(udf, configuration);
ossClient.createUdfApplication(createUdfApplicationRequest);
// wait application running
UdfApplicationInfo appInfo = ossClient.getUdfApplicationInfo(genericRequest);
System.out.println(appInfo);
for (; appInfo.getStatus().equals("creating"); ) {
TestUtils.waitForCacheExpiration(60);
appInfo = ossClient.getUdfApplicationInfo(genericRequest);
}
System.out.println(appInfo);
// upgrade application
UpgradeUdfApplicationRequest UpgradeUdfApplicationRequest = new UpgradeUdfApplicationRequest(udf, 2);
ossClient.upgradeUdfApplication(UpgradeUdfApplicationRequest);
appInfo = ossClient.getUdfApplicationInfo(genericRequest);
System.out.println(appInfo);
for (; appInfo.getStatus().equals("upgrading"); ) {
TestUtils.waitForCacheExpiration(60);
appInfo = ossClient.getUdfApplicationInfo(genericRequest);
}
System.out.println(appInfo);
// resize application
ResizeUdfApplicationRequest resizeUdfApplicationRequest = new ResizeUdfApplicationRequest(udf, 2);
ossClient.resizeUdfApplication(resizeUdfApplicationRequest);
appInfo = ossClient.getUdfApplicationInfo(genericRequest);
System.out.println(appInfo);
for (; appInfo.getStatus().equals("resizing"); ) {
TestUtils.waitForCacheExpiration(60);
appInfo = ossClient.getUdfApplicationInfo(genericRequest);
}
System.out.println(appInfo);
// get application log
GetUdfApplicationLogRequest getUdfApplicationLogRequest = new GetUdfApplicationLogRequest(udf);
getUdfApplicationLogRequest.setStartTime(DateUtil.parseRfc822Date("Wed, 15 Mar 2017 03:23:45 GMT"));
getUdfApplicationLogRequest.setEndLines(100L);
UdfApplicationLog udfApplicationLog = ossClient.getUdfApplicationLog(getUdfApplicationLogRequest);
displayTextInputStream(udfApplicationLog.getLogContent());
// // delete application
// ossClient.deleteUdfApplication(genericRequest);
//
// // wait application deleted
// appInfos = ossClient.listUdfApplications();
// for (; appInfos.size() > 0 ; ) {
// TestUtils.waitForCacheExpiration(60);
// appInfos = ossClient.listUdfApplications();
// }
//
// // delete udf image
// ossClient.deleteUdfImage(genericRequest);
//
// // wait images deleted
// udfImages = ossClient.getUdfImageInfo(genericRequest);
// for (; udfImages.size() > 0;) {
// TestUtils.waitForCacheExpiration(60);
// udfImages = ossClient.getUdfImageInfo(genericRequest);
// }
//
// // delete image
// ossClient.deleteUdf(genericRequest);
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
}
}
@Test
public void testUdfApplicationLog() {
String udf = "udf-go-pingpong-1";
try {
GetUdfApplicationLogRequest getUdfApplicationLogRequest = new GetUdfApplicationLogRequest(udf);
getUdfApplicationLogRequest.setStartTime(DateUtil.parseRfc822Date("Wed, 15 Mar 2017 03:23:45 GMT"));
getUdfApplicationLogRequest.setEndLines(10L);
UdfApplicationLog udfApplicationLog = ossClient.getUdfApplicationLog(getUdfApplicationLogRequest);
displayTextInputStream(udfApplicationLog.getLogContent());
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
}
}
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
int lines = 0;
while (true) {
String line = reader.readLine();
if (line == null) break;
lines++;
System.out.println(" " + line);
}
System.out.println("Lines:" + lines);
reader.close();
}
}
| 38.954098
| 122
| 0.621076
|
6c7b999045383354d52b117d141d98b1da0cba8b
| 923
|
package com.baeldung.string.tostring;
import java.util.List;
public class CustomerWrapperCollectionToString extends Customer {
private Integer score;
private List<String> orders;
private StringBuffer fullname;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public List<String> getOrders() {
return orders;
}
public void setOrders(List<String> orders) {
this.orders = orders;
}
public StringBuffer getFullname() {
return fullname;
}
public void setFullname(StringBuffer fullname) {
this.fullname = fullname;
}
@Override
public String toString() {
return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname
+ ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
}
}
| 23.075
| 85
| 0.619718
|
edfcd4c2cf82ad5612899e07065c39eb5d20abc3
| 3,177
|
/************************************************************************************************
* ____________ _ _ _____ _ _____ _ _ _______ __ _ _ _
* |___ / ____| \ | |/ ____| | | / ____| | | |_ _\ \ / / | | | | |
* / /| |__ | \| | | __ _ ___| |__ | | __| | | | | | \ \ /\ / /_ _| | | ___| |_
* / / | __| | . ` | | / _` / __| '_ \| | |_ | | | | | | \ \/ \/ / _` | | |/ _ \ __|
* / /__| |____| |\ | |___| (_| \__ \ | | | |__| | |__| |_| |_ \ /\ / (_| | | | __/ |_
* /_____|______|_| \_|\_____\__,_|___/_| |_|\_____|\____/|_____| \/ \/ \__,_|_|_|\___|\__|
*
* Copyright (c) 2016-2018 The ZEN Developers
*
* 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 com.vaklinov.zcashui;
import javax.swing.JComboBox;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
/**
* Combo Box that is aware of whether is is dropped down.
*/
public class DropdownComboBox<E>
extends JComboBox<E>
{
protected boolean isMenuDown;
public DropdownComboBox(E[] list)
{
super(list);
this.isMenuDown = false;
this.initDownListener();
}
public boolean isMenuDown()
{
return this.isMenuDown;
}
private void initDownListener()
{
this.addPopupMenuListener(new PopupMenuListener()
{
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
DropdownComboBox.this.isMenuDown = true;
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
DropdownComboBox.this.isMenuDown = false;
}
@Override
public void popupMenuCanceled(PopupMenuEvent e)
{
DropdownComboBox.this.isMenuDown = false;
}
});
}
}
| 38.277108
| 97
| 0.540447
|
0e3f76a417129c3f2d186908cf5c476a7487e908
| 13,659
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.threads;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
/**
*
*/
public final class ThreadPoolTestCase extends TestCase {
private final JBossThreadFactory threadFactory = new JBossThreadFactory(null, null, null, "test thread %p %t", null, null);
private static final class SimpleTask implements Runnable {
private final CountDownLatch taskUnfreezer;
private final CountDownLatch taskFinishLine;
private SimpleTask(final CountDownLatch taskUnfreezer, final CountDownLatch taskFinishLine) {
this.taskUnfreezer = taskUnfreezer;
this.taskFinishLine = taskFinishLine;
}
public void run() {
try {
assertTrue(taskUnfreezer.await(800L, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
fail("interrupted");
}
taskFinishLine.countDown();
}
}
public void testBasic() throws InterruptedException {
// Start some tasks, let them run, then shut down the executor
final int cnt = 100;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
taskUnfreezer.countDown();
final boolean finished = taskFinishLine.await(800L, TimeUnit.MILLISECONDS);
assertTrue(finished);
simpleQueueExecutor.shutdown();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (Throwable t) {
assertTrue(t instanceof RejectedExecutionException);
}
assertTrue(simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testShutdownNow() throws InterruptedException {
final AtomicBoolean interrupted = new AtomicBoolean();
final AtomicBoolean ran = new AtomicBoolean();
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch finLatch = new CountDownLatch(1);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
simpleQueueExecutor.execute(new Runnable() {
public void run() {
try {
ran.set(true);
startLatch.countDown();
Thread.sleep(5000L);
} catch (InterruptedException e) {
interrupted.set(true);
} finally {
finLatch.countDown();
}
}
});
assertTrue("Task not started", startLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Task returned", simpleQueueExecutor.shutdownNow().isEmpty());
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (RejectedExecutionException t) {
}
assertTrue("Task not finished", finLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
assertTrue("Task wasn't run", ran.get());
assertTrue("Worker wasn't interrupted", interrupted.get());
}
private static class Holder<T> {
private T instance;
public Holder(T instance) {
this.instance = instance;
}
public T get() { return instance; }
public void set(T instance) {this.instance = instance;}
}
public void testBlocking() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
Thread.currentThread().interrupt();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task was accepted");
} catch (RejectedExecutionException t) {
}
Thread.interrupted();
final CountDownLatch latch = new CountDownLatch(1);
final Thread otherThread = threadFactory.newThread(new Runnable() {
public void run() {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
}
});
otherThread.start();
assertFalse("Task executed without wait", latch.await(100L, TimeUnit.MILLISECONDS));
// safe to say the other thread is blocking...?
taskUnfreezer.countDown();
assertTrue("Task never ran", latch.await(800L, TimeUnit.MILLISECONDS));
otherThread.join(500L);
assertTrue("Simple Tasks never ran", taskFinishLine.await(800L, TimeUnit.MILLISECONDS));
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
final CountDownLatch shutdownLatch = new CountDownLatch(1);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
shutdownLatch.countDown();
} } , null);
shutdownLatch.await(100L, TimeUnit.MILLISECONDS);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testBlockingEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueuelessEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueuelessExecutor(threadFactory, SimpleDirectExecutor.INSTANCE, null, 500L);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueuelessExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueuelessKeepAlive() throws InterruptedException {
// Test for https://issues.jboss.org/browse/JBTHR-32 QueuelessExecutor doesn't shrink with keepAliveTime
final QueuelessExecutor simpleQueuelessExecutor = new QueuelessExecutor(threadFactory, SimpleDirectExecutor.INSTANCE, null, 100L);
simpleQueuelessExecutor.setMaxThreads(1);
final Holder<Thread> thread1 = new Holder<Thread>(null);
simpleQueuelessExecutor.execute(new Runnable() {
boolean first = true;
public void run() {
thread1.set(Thread.currentThread());
}
});
try {
Thread.sleep(500L);
} catch (InterruptedException ignore) { }
final CountDownLatch latch = new CountDownLatch(1);
final Holder<Thread> thread2 = new Holder<Thread>(null);
simpleQueuelessExecutor.execute(new Runnable() {
public void run() {
thread2.set(Thread.currentThread());
latch.countDown();
}
});
latch.await(100L, TimeUnit.MILLISECONDS);
assertTrue("First task and second task should be executed on different threads", thread1.get() != thread2.get());
simpleQueuelessExecutor.shutdown();
assertTrue("Executor not shut down in 800ms", simpleQueuelessExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueuelessKeepAliveRepeating() throws InterruptedException {
// Test for https://issues.jboss.org/browse/JBTHR-23 QueuelessExecutor repeats to execute previous runnable
final QueuelessExecutor simpleQueuelessExecutor = new QueuelessExecutor(threadFactory, SimpleDirectExecutor.INSTANCE, null, 100L);
simpleQueuelessExecutor.setMaxThreads(1);
final CountDownLatch latch = new CountDownLatch(1);
simpleQueuelessExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
latch.await(100L, TimeUnit.MILLISECONDS);
final Holder<Boolean> callback = new Holder<Boolean>(false);
simpleQueuelessExecutor.execute(new Runnable() {
boolean first = true;
public void run() {
callback.set(true);
if (!first) {
callback.set(false);
}
first = false;
}
});
try {
Thread.sleep(500L);
} catch (InterruptedException ignore) { }
simpleQueuelessExecutor.shutdown();
assertTrue("Calback only called once", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueuelessExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueueRejection() throws InterruptedException {
final int queueSize = 1;
final int coreThreads = 1;
final int extraThreads = 0;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService queueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, queueSize, threadFactory, false, null);
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final Runnable task = new Runnable() {
public void run() {
boolean running = true;
while (running) {
try {
taskUnfreezer.await();
running = false;
} catch (InterruptedException e) {
}
}
}
};
try {
try {
for (int i = 0; i < cnt; i++) {
queueExecutor.execute(task);
}
} catch (RejectedExecutionException e) {
fail("unexpected RejectedExecutionException");
}
try {
queueExecutor.execute(task);
fail("Task not rejected after too many tasks");
} catch (RejectedExecutionException e) {
// expected
}
} finally {
taskUnfreezer.countDown();
queueExecutor.shutdown();
}
}
}
| 43.224684
| 204
| 0.62823
|
0f08b96aea085343d2ae5fdddf239d7c025f8cef
| 237
|
package com.alibaba.alink.params.dataproc;
import com.alibaba.alink.params.shared.colname.HasWeightCol;
/**
* Params for WeightSampleBatchOp.
*/
public interface WeightSampleParams<T> extends
HasWeightCol <T>,
SampleParams <T> {
}
| 19.75
| 60
| 0.772152
|
5386dc4212aba766ee833993aa636a794b1af908
| 1,840
|
package com.alexstyl.specialdates.events.namedays.calendar.resource;
import com.alexstyl.specialdates.date.Date;
import com.alexstyl.specialdates.events.namedays.NameCelebrations;
import com.alexstyl.specialdates.events.namedays.NamesInADate;
import com.alexstyl.specialdates.events.namedays.calendar.EasternNameday;
import com.alexstyl.specialdates.events.namedays.calendar.EasternNamedaysExtractor;
import java.util.ArrayList;
import java.util.List;
final class RomanianSpecialNamedays implements SpecialNamedays {
private final RomanianNamedays namedays;
public static SpecialNamedays from(NamedayJSON namedayJSON, RomanianEasterSpecialCalculator romanianEasterCalculator) {
EasternNamedaysExtractor extractor = new EasternNamedaysExtractor(namedayJSON.getSpecial());
List<EasternNameday> easternNamedays = extractor.parse();
ArrayList<String> names = namesOf(easternNamedays);
RomanianNamedays namedays = new RomanianNamedays(romanianEasterCalculator, names);
return new RomanianSpecialNamedays(namedays);
}
private static ArrayList<String> namesOf(List<EasternNameday> easternNamedays) {
ArrayList<String> names = new ArrayList<>();
for (EasternNameday easternNameday : easternNamedays) {
names.addAll(easternNameday.getNamesCelebrating());
}
return names;
}
private RomanianSpecialNamedays(RomanianNamedays namedays) {
this.namedays = namedays;
}
@Override
public List<String> getAllNames() {
return namedays.getAllNames();
}
@Override
public NamesInADate getNamedayOn(Date date) {
return namedays.getNamedaysFor(date);
}
@Override
public NameCelebrations getNamedaysFor(String name, int year) {
return namedays.getNamedaysFor(name, year);
}
}
| 36.078431
| 123
| 0.753261
|
cae7e1ee193da7fd9a00f1db8b50493dea916e86
| 3,060
|
package lu.uni.bicslab.greenbot.android.ui.fragment.help;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import lu.uni.bicslab.greenbot.android.R;
import lu.uni.bicslab.greenbot.android.datamodel.IndicatorCategoryModel;
import lu.uni.bicslab.greenbot.android.datamodel.IndicatorModel;
import lu.uni.bicslab.greenbot.android.other.Utils;
/**
* A fragment representing a list of Items.
*/
public class IndicatorHelpFragment extends Fragment {
private List<IndicatorHelpItem> indicatorHelpItems;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public IndicatorHelpFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_indicator_help_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
createHelpItemsList(context);
recyclerView.setAdapter(new IndicatorHelpAdapter(indicatorHelpItems));
}
return view;
}
public void createHelpItemsList(Context context) {
//if(indicatorHelpItems != null) return;
indicatorHelpItems = new ArrayList<>();
List<IndicatorModel> indicators = Utils.getIndicatorList(context);
String currentCategoryId = "";
IndicatorHelpItem currentItem;
for (IndicatorModel ind: indicators) {
if(!ind.getCategory_id().equals(currentCategoryId)) {
currentCategoryId = ind.getCategory_id();
IndicatorCategoryModel icm = Utils.getIndicatorCategoryById(context, currentCategoryId);
currentItem = new IndicatorHelpItem();
currentItem.iconName = icm.getIcon_name();
currentItem.name = icm.getName();
currentItem.description = null;
indicatorHelpItems.add(currentItem);
}
currentItem = new IndicatorHelpItem();
currentItem.iconName = ind.getIcon_name();
currentItem.name = ind.getName();;
currentItem.description = ind.getGeneral_description();
indicatorHelpItems.add(currentItem);
}
}
public class IndicatorHelpItem {
public String iconName;
public String name;
public String description;
}
}
| 31.875
| 104
| 0.684641
|
0b98c7cff7fd58a1b9137e0ddfa45ee13f387af1
| 13,060
|
/*
* Copyright 2016 Netflix, 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 io.reactivex.netty.channel;
import io.netty.channel.Channel;
import io.netty.channel.FileRegion;
import io.netty.util.AttributeKey;
import rx.Observable;
import rx.functions.Func1;
/**
* A list of user initiated operations that can be done on a channel.
*
* @param <W> Type of data that can be written on the associated channel.
*/
public interface ChannelOperations<W> {
/**
* Flush selector that always returns true.
*/
Func1<String, Boolean> FLUSH_ON_EACH_STRING = new Func1<String, Boolean>() {
@Override
public Boolean call(String next) {
return true;
}
};
/**
* Flush selector that always returns true.
*/
Func1<byte[], Boolean> FLUSH_ON_EACH_BYTES = new Func1<byte[], Boolean>() {
@Override
public Boolean call(byte[] next) {
return true;
}
};
/**
* Flush selector that always returns true.
*/
Func1<FileRegion, Boolean> FLUSH_ON_EACH_FILE_REGION = new Func1<FileRegion, Boolean>() {
@Override
public Boolean call(FileRegion next) {
return true;
}
};
AttributeKey<Boolean> FLUSH_ONLY_ON_READ_COMPLETE =
AttributeKey.valueOf("_rxnetyy-flush-only-on-read-complete");
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel.
*
* <h2>Flush.</h2>
*
* All writes will be flushed on completion of the passed {@code Observable}
*
* @param msgs Stream of messages to write.
*
* @return {@link Observable} representing the result of this write. Every subscription to this {@link Observable}
* will replay the write on the channel.
*/
Observable<Void> write(Observable<W> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, everytime, {@code flushSelector} returns {@code true} . Any writes issued before
* subscribing, will also be flushed. However, the returned {@link Observable} will not capture the result of those
* writes, i.e. if the other writes, fail and this write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. Channel is
* flushed, iff this function returns, {@code true}.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, when the
* {@code flushSelector} returns {@code true}
*/
Observable<Void> write(Observable<W> msgs, Func1<W, Boolean> flushSelector);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, on every write. Any writes issued before subscribing, will also be flushed. However, the
* returned {@link Observable} will not capture the result of those writes, i.e. if the other writes, fail and this
* write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, on every
* write.
*/
Observable<Void> writeAndFlushOnEach(Observable<W> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel.
*
* <h2>Flush.</h2>
*
* All writes will be flushed on completion of the passed {@code Observable}
*
* @param msgs Stream of messages to write.
*
* @return {@link Observable} representing the result of this write. Every subscription to this {@link Observable}
* will replay the write on the channel.
*/
Observable<Void> writeString(Observable<String> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, everytime, {@code flushSelector} returns {@code true} . Any writes issued before
* subscribing, will also be flushed. However, the returned {@link Observable} will not capture the result of those
* writes, i.e. if the other writes, fail and this write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. Channel is
* flushed, iff this function returns, {@code true}.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, when the
* {@code flushSelector} returns {@code true}
*/
Observable<Void> writeString(Observable<String> msgs, Func1<String, Boolean> flushSelector);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, on every write. Any writes issued before subscribing, will also be flushed. However, the
* returned {@link Observable} will not capture the result of those writes, i.e. if the other writes, fail and this
* write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, on every
* write.
*/
Observable<Void> writeStringAndFlushOnEach(Observable<String> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel.
*
* <h2>Flush.</h2>
*
* All writes will be flushed on completion of the passed {@code Observable}
*
* @param msgs Stream of messages to write.
*
* @return {@link Observable} representing the result of this write. Every subscription to this {@link Observable}
* will replay the write on the channel.
*/
Observable<Void> writeBytes(Observable<byte[]> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, everytime, {@code flushSelector} returns {@code true} . Any writes issued before
* subscribing, will also be flushed. However, the returned {@link Observable} will not capture the result of those
* writes, i.e. if the other writes, fail and this write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. Channel is
* flushed, iff this function returns, {@code true}.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, when the
* {@code flushSelector} returns {@code true}
*/
Observable<Void> writeBytes(Observable<byte[]> msgs, Func1<byte[], Boolean> flushSelector);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, on every write. Any writes issued before subscribing, will also be flushed. However, the
* returned {@link Observable} will not capture the result of those writes, i.e. if the other writes, fail and this
* write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, on every
* write.
*/
Observable<Void> writeBytesAndFlushOnEach(Observable<byte[]> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel.
*
* <h2>Flush.</h2>
*
* All writes will be flushed on completion of the passed {@code Observable}
*
* @param msgs Stream of messages to write.
*
* @return {@link Observable} representing the result of this write. Every subscription to this {@link Observable}
* will replay the write on the channel.
*/
Observable<Void> writeFileRegion(Observable<FileRegion> msgs);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, everytime, {@code flushSelector} returns {@code true} . Any writes issued before
* subscribing, will also be flushed. However, the returned {@link Observable} will not capture the result of those
* writes, i.e. if the other writes, fail and this write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. Channel is
* flushed, iff this function returns, {@code true}.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, when the
* {@code flushSelector} returns {@code true}
*/
Observable<Void> writeFileRegion(Observable<FileRegion> msgs, Func1<FileRegion, Boolean> flushSelector);
/**
* On subscription of the returned {@link Observable}, writes the passed message stream on the underneath channel
* and flushes the channel, on every write. Any writes issued before subscribing, will also be flushed. However, the
* returned {@link Observable} will not capture the result of those writes, i.e. if the other writes, fail and this
* write does not, the returned {@link Observable} will not fail.
*
* @param msgs Message stream to write.
*
* @return An {@link Observable} representing the result of this write. Every
* subscription to this {@link Observable} will write the passed messages and flush all pending writes, on every
* write.
*/
Observable<Void> writeFileRegionAndFlushOnEach(Observable<FileRegion> msgs);
/**
* Modifies the underneath channel to enable writing new type of objects that will be transformed using the passed
* {@code transformer}
*
* @param transformer Transformer to transform objects written to the channel.
*
* @param <WW> The target type of the transformer.
*
* @return A new instance of {@code ChannelOperations} that accepts the transformed type to write.
*/
<WW> ChannelOperations<WW> transformWrite(AllocatingTransformer<WW, W> transformer);
/**
* Flushes any pending writes on this connection by calling {@link Channel#flush()}. This can be used for
* implementing any custom flusing strategies that otherwise can not be implemented by methods like
* {@link #write(Observable, Func1)}.
*/
void flush();
/**
* Flushes any pending writes and closes the connection. Same as calling {@code close(true)}
*
* @return {@link Observable} representing the result of close.
*/
Observable<Void> close();
/**
* Closes this channel after flushing all pending writes.
*
* @return {@link Observable} representing the result of close and flush.
*/
Observable<Void> close(boolean flush);
/**
* Closes the connection immediately. Same as calling {@link #close()} and subscribing to the returned
* {@code Observable}
*/
void closeNow();
/**
* Returns an {@link Observable} that completes when this connection is closed.
*
* @return An {@link Observable} that completes when this connection is closed.
*/
Observable<Void> closeListener();
}
| 45.664336
| 120
| 0.686371
|
1ee50c285f652267fef32370b89530e475dbb21b
| 4,266
|
package com.skrumaz.app.data.WebService;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.skrumaz.app.classes.User;
import com.skrumaz.app.data.Preferences;
import com.skrumaz.app.data.Store.Users;
import com.skrumaz.app.utils.ClientInfo;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
/**
* Created by Paito Anderson on 2014-03-22.
*/
public class GetUser {
public User FetchUser(Context context) {
User user = null;
// Setup HTTP Request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("https://rally1.rallydev.com/slm/webservice/v2.0/user?fetch=ObjectID,DisplayName,EmailAddress");
Log.d("GetUser", "https://rally1.rallydev.com/slm/webservice/v2.0/user?fetch=ObjectID,DisplayName,EmailAddress&pretty=true");
// Setup HTTP Headers / Authorization
get.setHeader("Accept", "application/json");
get = ClientInfo.addHttpGetHeaders(get);
get.setHeader("Authorization", Preferences.getCredentials(context));
try {
// Make HTTP Request
HttpResponse response = httpClient.execute(get);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
// Parse JSON Response
BufferedReader streamReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
// Get Object for this user
JSONObject userObject = new JSONObject(responseStrBuilder.toString()).getJSONObject("User");
user = new User(userObject.getString("DisplayName"));
user.setOid(userObject.getLong("ObjectID"));
user.setEmail(userObject.getString("EmailAddress"));
user.setPhotoBitmap(FetchUserProfile(context, user.getOid()));
// Store user in Database
Users db = new Users(context);
db.storeUser(user);
db.close();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return user;
}
private Bitmap FetchUserProfile(Context context, Long userId)
{
Bitmap profileImage = null;
// Setup HTTP Request
GetCookie getCookie = new GetCookie();
DefaultHttpClient httpClient = getCookie.FetchHttpClient(context);
HttpGet get = new HttpGet("https://rally1.rallydev.com/slm/profile/viewThumbnailImage.sp?tSize=150&uid=" + userId);
Log.d("GetUser", "https://rally1.rallydev.com/slm/profile/viewThumbnailImage.sp?tSize=150&uid=" + userId);
// Setup HTTP Headers / Authorization
get.setHeader("Accept", "application/json");
get = ClientInfo.addHttpGetHeaders(get);
get.setHeader("Authorization", Preferences.getCredentials(context));
try {
// Make HTTP Request
HttpResponse response = httpClient.execute(get);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
InputStream imageStream = bufferedHttpEntity.getContent();
profileImage = BitmapFactory.decodeStream(imageStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return profileImage;
}
}
| 39.137615
| 142
| 0.654712
|
f3680389418235dacecb19fb547112f4bb658a2b
| 2,337
|
package org.springframework.samples.petclinic.integration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.persistence.VisitRepository;
/**
* Class to perform integration testing between Visit repository and the persistence layer
*
* @author joycetan
*
*/
@SpringBootTest
public class VisitIntegrationTests {
@Autowired
private VisitRepository visitRepository;
@Test
void testFindByPetId() {
// Create visits
int petId = 2;
Visit visit1 = Utils.createVisit(LocalDate.of(2020, Month.DECEMBER, 1), "Description1", petId);
Visit visit2 = Utils.createVisit(LocalDate.of(2020, Month.DECEMBER, 7), "Description2", petId);
visitRepository.save(visit1);
visitRepository.save(visit2);
// Retrieve list of visits for given pet
List<Visit> visits = visitRepository.findByPetId(petId);
assertNotNull(visits);
assertEquals(2, visits.size());
}
@Test
void testFindByNonValidId() {
int nonValidPetId = -1;
List<Visit> visits = visitRepository.findByPetId(nonValidPetId);
assertNotNull(visits);
assertTrue(visits.isEmpty());
}
@Test
void testUpdateVisit() throws Exception {
// Create Visit
LocalDate date = LocalDate.of(2021, Month.DECEMBER, 5);
int petId = 1;
String oldDescription = "Old description", newDescription = "New description";
Visit oldVisit = Utils.createVisit(date, oldDescription, petId);
visitRepository.save(oldVisit);
// Update visit
Visit newVisit = oldVisit;
newVisit.setDescription(newDescription);
visitRepository.save(newVisit);
// Retrieve visit object and check if updated
List<Visit> visits = visitRepository.findByPetId(petId);
assertEquals(1, visits.size());
Visit visit = visits.get(0);
assertEquals(newVisit.getDescription(), visit.getDescription());
assertEquals(newVisit.getDate(), visit.getDate());
assertEquals(newVisit.getPetId(), visit.getPetId());
}
}
| 30.350649
| 97
| 0.768079
|
1efa1c3b55e85d974983494e5b940bc0f9916a08
| 1,061
|
package com.ps.quibbler.base;
import com.ps.quibbler.enums.ErrorCodeEnum;
import lombok.Getter;
import org.apache.commons.lang3.ObjectUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author paksu
*/
@Getter
public abstract class BaseException extends RuntimeException {
private final ErrorCodeEnum errorCode;
private final HashMap<String, Object> data = new HashMap<>();
protected BaseException(ErrorCodeEnum errorCode, Map<String,Object> data) {
super(errorCode.getMessage());
this.errorCode = errorCode;
if (!ObjectUtils.isEmpty(data)) {
this.data.putAll(data);
}
}
protected BaseException(ErrorCodeEnum errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}
protected BaseException(ErrorCodeEnum errorCode, Map<String, Object> data, Throwable cause) {
super(errorCode.getMessage(),cause);
this.errorCode = errorCode;
if (!ObjectUtils.isEmpty(data)) {
this.data.putAll(data);
}
}
}
| 26.525
| 97
| 0.675778
|
8bda85f775b35163b0d18478d4d9938cf2808fec
| 11,210
|
package testJpa.simple.parentChild.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnitUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import testJpa.TestJpaTestConfiguration;
import testJpa.simple.parentChild.domain.ChildTable;
import testJpa.simple.parentChild.domain.ParentTable;
/**
* Test CRUD functionality of a parent/child table.
* <p>
* This class uses DBUnit for database setup and verification of results. All
* changes are rolled back at the end of a test method.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestJpaTestConfiguration.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
@Transactional
public class SimpleParentTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleParentTest.class);
@Autowired
SimpleParentDao dao;
private PersistenceUnitUtil puu;
private EntityManager em;
/**
* Inject entity manager and persistence unit utility
*
* @param em
* the entity manager
*
*/
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
this.puu = em.getEntityManagerFactory().getPersistenceUnitUtil();
}
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
public void testFindAll() {
final List<ParentTable> list = dao.findAll();
assertEquals(3, list.size());
// Assert child elements are lazily loaded.
// EclipseLink logging level
// FINE should show four SELECTs: one for the parent table and one per
// parent record to retrieve the children (n+1). See also
// testBatchFetch().
for (ParentTable pt : list) {
assertFalse(puu.isLoaded(pt, "children"));
assertEquals(3, pt.getChildren().size());
}
}
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
public void testFindByData() {
final List<ParentTable> list = dao.findByData("one thousand");
assertEquals(1, list.size());
assertEquals(10001000, list.get(0).getId().longValue());
// Assert children are (lazily) loaded.
assertEquals(3, list.get(0).getChildren().size());
}
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "expect_ParentTable_deleted.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "expect_ChildTable_parent_deleted.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testRemoveParentManaged() {
final ParentTable st = dao.findOne(10001000l);
assertNotNull("entity to delete must not be null", st);
dao.delete(st);
assertNull("most not find deleted entity", dao.findOne(10001000l));
assertEquals("must be one entry less", 2, dao.count());
}
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "expect_ParentTable_updated.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "setup_ChildTable.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testUpdateParentManaged() {
LOGGER.info("start test update managed");
final ParentTable st = dao.findOne(10001000l);
st.setData("updated");
em.flush();
LOGGER.info("end test update managed");
}
/**
* Update parent table entry from an unmanaged object. While this works, it
* is not a good practice.
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "expect_ParentTable_updated.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "setup_ChildTable.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testUpdateParentUnmanaged() {
LOGGER.info("start test update unmanaged");
final ParentTable st = new ParentTable();
st.setId(10001000l);
st.setData("updated");
// child entry has to be added as well, otherwise orphanRemoval will
// just remove it
// when parent table entry is merged
final ChildTable ct1 = new ChildTable();
ct1.setId(20001000l);
ct1.setData("two thousand");
st.addChild(ct1);
final ChildTable ct2 = new ChildTable();
ct2.setId(20001010l);
ct2.setData("two thousand ten");
st.addChild(ct2);
final ChildTable ct3 = new ChildTable();
ct3.setId(20001020l);
ct3.setData("two thousand twenty");
st.addChild(ct3);
dao.save(st);
em.flush();
LOGGER.info("end test update unmanaged");
}
/**
* removing the child by modifying the collection is not allowed: children
* are managed by the owning entity parent
*/
@Test(expected = UnsupportedOperationException.class)
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
public void testRemoveChildWrong() {
final ParentTable st = dao.findOne(10001000l);
st.getChildren().remove(0);
}
/**
* child object will be removed by orphan removal
*
* This test fails with EclipseLink 2.5.2 due to the stream API, see
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=433075 and
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=467470
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "setup_ParentTable.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "expect_ChildTable_deleted.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testRemoveChild() {
final ParentTable st = dao.findOne(10001000l);
final int numberOfChildren = st.getChildren().size();
Optional<ChildTable> ct = st.getChildren().stream().filter(i -> i.getId().equals(20001000l)).findFirst();
st.removeChild(ct.get());
assertEquals(numberOfChildren - 1, st.getChildren().size());
em.flush();
}
/**
* add one child object
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "setup_ParentTable.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "expect_ChildTable_created.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testCreateChild() {
final ParentTable st = dao.findOne(10001000l);
final ChildTable newChild = new ChildTable();
newChild.setData("new child");
/*
* Since it is a new child the id property is left initial; it will be
* set by sequence later. The parent id is set by the parent entity to
* ensure consistency.
*/
st.addChild(newChild);
em.flush();
}
/**
* add parent and linked child object
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
@ExpectedDatabase(value = "expect_ParentTable_created.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
@ExpectedDatabase(value = "expect_ChildTable_created_no_IDs.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testCreateParentAndChild() {
final ParentTable newParent = new ParentTable();
newParent.setData("new entry");
final ChildTable newChild = new ChildTable();
newChild.setData("new child");
newParent.addChild(newChild);
dao.save(newParent);
em.flush();
}
/**
* Test batch fetching all parents. See FINE logging level of EclipseLink to
* verify there are only two SELECTs.
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
public void testBatchFetchAll() {
final List<ParentTable> st = dao.findAllBatchFetch();
assertEquals(3, st.size());
// Assert children are lazily loaded for each parent record. But in
// EclipseLink logging all children are loaded with one select.
// Internally
// EclipseLink stores the batch query results in session.batchQueries
// before they are used for lazy loading in next iteration.
for (ParentTable pt : st) {
assertFalse("children are not yet loaded", puu.isLoaded(pt, "children"));
assertEquals(3, pt.getChildren().size());
assertTrue("children are now loaded", puu.isLoaded(pt, "children"));
}
}
/**
* Test batch fetching parents by data. See FINE logging level of
* EclipseLink to verify there are only two SELECTs.
*/
@Test
@DatabaseSetup("setup_ParentTable.xml")
@DatabaseSetup("setup_ChildTable.xml")
public void testBatchFetchByData() {
final List<ParentTable> st = dao.findByDataBatchFetch("one thousand");
assertEquals(1, st.size());
// Assert children are lazily loaded for each parent record. But in
// EclipseLink logging all children are loaded with one select.
// Internally
// EclipseLink stores the batch query results in session.batchQueries
// before they are used for lazy loading in next iteration.
for (ParentTable pt : st) {
assertFalse("children are not yet loaded", puu.isLoaded(pt, "children"));
assertEquals(3, pt.getChildren().size());
assertTrue("children are now loaded", puu.isLoaded(pt, "children"));
}
}
}
| 36.633987
| 129
| 0.697324
|
bd7f30fa4c10cf2329195fb9600b62df5270f429
| 15,521
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.pinpoint.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Specifies the dimension settings for a segment.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/SegmentDimensions" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SegmentDimensions implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* One or more custom attributes to use as criteria for the segment.
* </p>
*/
private java.util.Map<String, AttributeDimension> attributes;
/**
* <p>
* The behavior-based criteria, such as how recently users have used your app, for the segment.
* </p>
*/
private SegmentBehaviors behavior;
/**
* <p>
* The demographic-based criteria, such as device platform, for the segment.
* </p>
*/
private SegmentDemographics demographic;
/**
* <p>
* The location-based criteria, such as region or GPS coordinates, for the segment.
* </p>
*/
private SegmentLocation location;
/**
* <p>
* One or more custom metrics to use as criteria for the segment.
* </p>
*/
private java.util.Map<String, MetricDimension> metrics;
/**
* <p>
* One or more custom user attributes to use as criteria for the segment.
* </p>
*/
private java.util.Map<String, AttributeDimension> userAttributes;
/**
* <p>
* One or more custom attributes to use as criteria for the segment.
* </p>
*
* @return One or more custom attributes to use as criteria for the segment.
*/
public java.util.Map<String, AttributeDimension> getAttributes() {
return attributes;
}
/**
* <p>
* One or more custom attributes to use as criteria for the segment.
* </p>
*
* @param attributes
* One or more custom attributes to use as criteria for the segment.
*/
public void setAttributes(java.util.Map<String, AttributeDimension> attributes) {
this.attributes = attributes;
}
/**
* <p>
* One or more custom attributes to use as criteria for the segment.
* </p>
*
* @param attributes
* One or more custom attributes to use as criteria for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withAttributes(java.util.Map<String, AttributeDimension> attributes) {
setAttributes(attributes);
return this;
}
public SegmentDimensions addAttributesEntry(String key, AttributeDimension value) {
if (null == this.attributes) {
this.attributes = new java.util.HashMap<String, AttributeDimension>();
}
if (this.attributes.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.attributes.put(key, value);
return this;
}
/**
* Removes all the entries added into Attributes.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions clearAttributesEntries() {
this.attributes = null;
return this;
}
/**
* <p>
* The behavior-based criteria, such as how recently users have used your app, for the segment.
* </p>
*
* @param behavior
* The behavior-based criteria, such as how recently users have used your app, for the segment.
*/
public void setBehavior(SegmentBehaviors behavior) {
this.behavior = behavior;
}
/**
* <p>
* The behavior-based criteria, such as how recently users have used your app, for the segment.
* </p>
*
* @return The behavior-based criteria, such as how recently users have used your app, for the segment.
*/
public SegmentBehaviors getBehavior() {
return this.behavior;
}
/**
* <p>
* The behavior-based criteria, such as how recently users have used your app, for the segment.
* </p>
*
* @param behavior
* The behavior-based criteria, such as how recently users have used your app, for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withBehavior(SegmentBehaviors behavior) {
setBehavior(behavior);
return this;
}
/**
* <p>
* The demographic-based criteria, such as device platform, for the segment.
* </p>
*
* @param demographic
* The demographic-based criteria, such as device platform, for the segment.
*/
public void setDemographic(SegmentDemographics demographic) {
this.demographic = demographic;
}
/**
* <p>
* The demographic-based criteria, such as device platform, for the segment.
* </p>
*
* @return The demographic-based criteria, such as device platform, for the segment.
*/
public SegmentDemographics getDemographic() {
return this.demographic;
}
/**
* <p>
* The demographic-based criteria, such as device platform, for the segment.
* </p>
*
* @param demographic
* The demographic-based criteria, such as device platform, for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withDemographic(SegmentDemographics demographic) {
setDemographic(demographic);
return this;
}
/**
* <p>
* The location-based criteria, such as region or GPS coordinates, for the segment.
* </p>
*
* @param location
* The location-based criteria, such as region or GPS coordinates, for the segment.
*/
public void setLocation(SegmentLocation location) {
this.location = location;
}
/**
* <p>
* The location-based criteria, such as region or GPS coordinates, for the segment.
* </p>
*
* @return The location-based criteria, such as region or GPS coordinates, for the segment.
*/
public SegmentLocation getLocation() {
return this.location;
}
/**
* <p>
* The location-based criteria, such as region or GPS coordinates, for the segment.
* </p>
*
* @param location
* The location-based criteria, such as region or GPS coordinates, for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withLocation(SegmentLocation location) {
setLocation(location);
return this;
}
/**
* <p>
* One or more custom metrics to use as criteria for the segment.
* </p>
*
* @return One or more custom metrics to use as criteria for the segment.
*/
public java.util.Map<String, MetricDimension> getMetrics() {
return metrics;
}
/**
* <p>
* One or more custom metrics to use as criteria for the segment.
* </p>
*
* @param metrics
* One or more custom metrics to use as criteria for the segment.
*/
public void setMetrics(java.util.Map<String, MetricDimension> metrics) {
this.metrics = metrics;
}
/**
* <p>
* One or more custom metrics to use as criteria for the segment.
* </p>
*
* @param metrics
* One or more custom metrics to use as criteria for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withMetrics(java.util.Map<String, MetricDimension> metrics) {
setMetrics(metrics);
return this;
}
public SegmentDimensions addMetricsEntry(String key, MetricDimension value) {
if (null == this.metrics) {
this.metrics = new java.util.HashMap<String, MetricDimension>();
}
if (this.metrics.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.metrics.put(key, value);
return this;
}
/**
* Removes all the entries added into Metrics.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions clearMetricsEntries() {
this.metrics = null;
return this;
}
/**
* <p>
* One or more custom user attributes to use as criteria for the segment.
* </p>
*
* @return One or more custom user attributes to use as criteria for the segment.
*/
public java.util.Map<String, AttributeDimension> getUserAttributes() {
return userAttributes;
}
/**
* <p>
* One or more custom user attributes to use as criteria for the segment.
* </p>
*
* @param userAttributes
* One or more custom user attributes to use as criteria for the segment.
*/
public void setUserAttributes(java.util.Map<String, AttributeDimension> userAttributes) {
this.userAttributes = userAttributes;
}
/**
* <p>
* One or more custom user attributes to use as criteria for the segment.
* </p>
*
* @param userAttributes
* One or more custom user attributes to use as criteria for the segment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions withUserAttributes(java.util.Map<String, AttributeDimension> userAttributes) {
setUserAttributes(userAttributes);
return this;
}
public SegmentDimensions addUserAttributesEntry(String key, AttributeDimension value) {
if (null == this.userAttributes) {
this.userAttributes = new java.util.HashMap<String, AttributeDimension>();
}
if (this.userAttributes.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.userAttributes.put(key, value);
return this;
}
/**
* Removes all the entries added into UserAttributes.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SegmentDimensions clearUserAttributesEntries() {
this.userAttributes = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAttributes() != null)
sb.append("Attributes: ").append(getAttributes()).append(",");
if (getBehavior() != null)
sb.append("Behavior: ").append(getBehavior()).append(",");
if (getDemographic() != null)
sb.append("Demographic: ").append(getDemographic()).append(",");
if (getLocation() != null)
sb.append("Location: ").append(getLocation()).append(",");
if (getMetrics() != null)
sb.append("Metrics: ").append(getMetrics()).append(",");
if (getUserAttributes() != null)
sb.append("UserAttributes: ").append(getUserAttributes());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SegmentDimensions == false)
return false;
SegmentDimensions other = (SegmentDimensions) obj;
if (other.getAttributes() == null ^ this.getAttributes() == null)
return false;
if (other.getAttributes() != null && other.getAttributes().equals(this.getAttributes()) == false)
return false;
if (other.getBehavior() == null ^ this.getBehavior() == null)
return false;
if (other.getBehavior() != null && other.getBehavior().equals(this.getBehavior()) == false)
return false;
if (other.getDemographic() == null ^ this.getDemographic() == null)
return false;
if (other.getDemographic() != null && other.getDemographic().equals(this.getDemographic()) == false)
return false;
if (other.getLocation() == null ^ this.getLocation() == null)
return false;
if (other.getLocation() != null && other.getLocation().equals(this.getLocation()) == false)
return false;
if (other.getMetrics() == null ^ this.getMetrics() == null)
return false;
if (other.getMetrics() != null && other.getMetrics().equals(this.getMetrics()) == false)
return false;
if (other.getUserAttributes() == null ^ this.getUserAttributes() == null)
return false;
if (other.getUserAttributes() != null && other.getUserAttributes().equals(this.getUserAttributes()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAttributes() == null) ? 0 : getAttributes().hashCode());
hashCode = prime * hashCode + ((getBehavior() == null) ? 0 : getBehavior().hashCode());
hashCode = prime * hashCode + ((getDemographic() == null) ? 0 : getDemographic().hashCode());
hashCode = prime * hashCode + ((getLocation() == null) ? 0 : getLocation().hashCode());
hashCode = prime * hashCode + ((getMetrics() == null) ? 0 : getMetrics().hashCode());
hashCode = prime * hashCode + ((getUserAttributes() == null) ? 0 : getUserAttributes().hashCode());
return hashCode;
}
@Override
public SegmentDimensions clone() {
try {
return (SegmentDimensions) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.pinpoint.model.transform.SegmentDimensionsMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 33.378495
| 137
| 0.623349
|
3a5bca6d45691e78e97dd55cfefb538546f20eab
| 2,895
|
package com.lin.web.dto;
import java.io.Serializable;
public class AdvertiserTrendAnalysisHeaderDTO implements Serializable{
private String bookedImpressions;
private String impressions;
private String lifeTimeImpresions;
private String clicks;
private String lifeTimeClicks;
private String CPM;
private String CTR;
private String totalCTR;
private String revenue;
private String revenueDelivered;
private String revenueRemaining;
private String budget;
public AdvertiserTrendAnalysisHeaderDTO(){
}
public AdvertiserTrendAnalysisHeaderDTO(String bookedImpressions,
String impressions, String lifeTimeImpresions, String clicks,
String lifeTimeClicks, String cPM, String cTR, String totalCTR,
String revenue, String revenueDelivered, String revenueRemaining) {
super();
this.bookedImpressions = bookedImpressions;
this.impressions = impressions;
this.lifeTimeImpresions = lifeTimeImpresions;
this.clicks = clicks;
this.lifeTimeClicks = lifeTimeClicks;
CPM = cPM;
CTR = cTR;
this.totalCTR = totalCTR;
this.revenue = revenue;
this.revenueDelivered = revenueDelivered;
this.revenueRemaining = revenueRemaining;
}
public void setBookedImpressions(String bookedImpressions) {
this.bookedImpressions = bookedImpressions;
}
public String getBookedImpressions() {
return bookedImpressions;
}
public void setLifeTimeImpresions(String lifeTimeImpresions) {
this.lifeTimeImpresions = lifeTimeImpresions;
}
public String getLifeTimeImpresions() {
return lifeTimeImpresions;
}
public void setLifeTimeClicks(String lifeTimeClicks) {
this.lifeTimeClicks = lifeTimeClicks;
}
public String getLifeTimeClicks() {
return lifeTimeClicks;
}
public void setCPM(String cPM) {
CPM = cPM;
}
public String getCPM() {
return CPM;
}
public void setCTR(String cTR) {
CTR = cTR;
}
public String getCTR() {
return CTR;
}
public void setRevenueDelivered(String revenueDelivered) {
this.revenueDelivered = revenueDelivered;
}
public String getRevenueDelivered() {
return revenueDelivered;
}
public void setRevenueRemaining(String revenueRemaining) {
this.revenueRemaining = revenueRemaining;
}
public String getRevenueRemaining() {
return revenueRemaining;
}
public void setClicks(String clicks) {
this.clicks = clicks;
}
public String getClicks() {
return clicks;
}
public void setTotalCTR(String totalCTR) {
this.totalCTR = totalCTR;
}
public String getTotalCTR() {
return totalCTR;
}
public void setImpressions(String impressions) {
this.impressions = impressions;
}
public String getImpressions() {
return impressions;
}
public void setRevenue(String revenue) {
this.revenue = revenue;
}
public String getRevenue() {
return revenue;
}
public void setBudget(String budget) {
this.budget = budget;
}
public String getBudget() {
return budget;
}
}
| 21.444444
| 70
| 0.759585
|
044dc312f055d2f4249f1efc4d6dc820a4901762
| 1,925
|
package org.logstash.benchmark.cli;
import java.io.IOException;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import org.logstash.benchmark.cli.util.LsBenchDownloader;
/**
* JRuby Installation.
*/
public final class JRubyInstallation {
private static final String JRUBY_DEFAULT_VERSION = "9.1.10.0";
/**
* Path of the `gem` executable.
*/
private final Path gem;
/**
* Path of the `rake` executable.
*/
private final Path rake;
/**
* Path of the `ruby` executable.
*/
private final Path jruby;
/**
* Sets up a JRuby used to bootstrap a Logstash Installation.
* @param pwd Cache Directory to work in
* @return instance
* @throws IOException On I/O Error during JRuby Download or Installation
* @throws NoSuchAlgorithmException On SSL Issue during JRuby Download
*/
public static JRubyInstallation bootstrapJruby(final Path pwd)
throws IOException, NoSuchAlgorithmException {
LsBenchDownloader.downloadDecompress(
pwd.resolve("jruby").toFile(),
String.format(
"http://jruby.org.s3.amazonaws.com/downloads/%s/jruby-bin-%s.tar.gz",
JRUBY_DEFAULT_VERSION, JRUBY_DEFAULT_VERSION
)
);
return new JRubyInstallation(
pwd.resolve("jruby").resolve(String.format("jruby-%s", JRUBY_DEFAULT_VERSION))
);
}
private JRubyInstallation(final Path root) {
final Path bin = root.resolve("bin");
this.gem = bin.resolve("gem");
this.jruby = bin.resolve("jruby");
this.rake = bin.resolve("rake");
}
public String gem() {
return gem.toAbsolutePath().toString();
}
public String rake() {
return rake.toAbsolutePath().toString();
}
public String jruby() {
return jruby.toAbsolutePath().toString();
}
}
| 27.5
| 90
| 0.633766
|
b0a45e8b7a0b977cdb2793ad80de9c6508c9aee9
| 2,016
|
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.ourstreets.view;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Registers clicks on an item within a {@link RecyclerView}.
*/
public abstract class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context) {
mGestureDetector = new GestureDetector(context, new GestureDetector
.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mGestureDetector.onTouchEvent(e)) {
onItemClick(view.getChildViewHolder(childView), view.getChildAdapterPosition(childView));
}
return false;
}
/**
* Called when an item has been clicked.
*
* @param holder The holder of the clicked view.
* @param position The position of the clicked view.
*/
public abstract void onItemClick(RecyclerView.ViewHolder holder, int position);
}
| 34.169492
| 101
| 0.706845
|
c1c9e95956dcc0a2ae2790740dda8939de95bedf
| 1,231
|
package eubrazil.atmosphere.qualitymodel;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import eubrazil.atmosphere.service.SpringContextBridgedServices;
import eubrazil.atmosphere.service.TrustworthinessService;
/**
* Autowire the TrustworthinessService
* @author JorgeLuiz
*/
@Component
public class SpringContextBridge implements SpringContextBridgedServices, ApplicationContextAware {
private static ApplicationContext applicationContext;
@Autowired
private TrustworthinessService trustworthinessService; // Autowire the TrustworthinessService
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static SpringContextBridgedServices services() {
return applicationContext.getBean(SpringContextBridgedServices.class);
}
@Override
public TrustworthinessService getTrustworthinessService() {
return trustworthinessService;
}
}
| 30.775
| 99
| 0.850528
|
fd093e09c627e281fe4598302a9be6dcd2e2db9c
| 1,395
|
package vos;
import org.codehaus.jackson.annotate.JsonProperty;
public class PedidoMesa
{
@JsonProperty(value="id")
private Long id;
@JsonProperty(value="idMesa")
private Long idMesa;
@JsonProperty(value="idProducto")
private Long idProducto;
@JsonProperty(value="idMenu")
private Long idMenu;
@JsonProperty(value="idCliente")
private Long idCliente;
public PedidoMesa(@JsonProperty(value="id")Long id,@JsonProperty(value="idMesa")Long idMesa,@JsonProperty(value="idProducto")Long idProducto ,@JsonProperty(value="idMenu")Long idMenu,@JsonProperty(value="idCliente")Long idCliente)
{
this.id=id;
this.idMesa = idMesa;
this.idProducto=idProducto;
this.idMenu=idMenu;
this.idCliente=idCliente;
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdMesa() {
return idMesa;
}
public void setIdMesa(Long idMesa) {
this.idMesa = idMesa;
}
public Long getIdProducto() {
return idProducto;
}
public void setIdProducto(Long idProducto) {
this.idProducto = idProducto;
}
public Long getIdMenu() {
return idMenu;
}
public void setIdMenu(Long idMenu) {
this.idMenu = idMenu;
}
public Long getIdCliente() {
return idCliente;
}
public void setIdCliente(Long idCliente) {
this.idCliente = idCliente;
}
}
| 13.811881
| 232
| 0.705376
|
793b2e0d5959b5b081362cc4bd71bb4b42ce2b5b
| 1,633
|
public class Solution {
// 深度优先遍历(回溯算法)
private int[][] graph;
private boolean[] visited;
private int res = Integer.MAX_VALUE;
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
K = Math.min(K, n - 2);
// 建图(有向图)
this.graph = new int[n][n];
for (int[] flight : flights) {
graph[flight[0]][flight[1]] = flight[2];
}
// 图的广度优先遍历需要 visited 数组
this.visited = new boolean[n];
// 开始深度优先遍历,注意:这里传 K + 1,这是因为 K 次经停,总共 K + 1 个站
dfs(src, dst, K + 1, 0);
// 特殊判断
if (res == Integer.MAX_VALUE) {
return -1;
}
return res;
}
/**
* 从 src 出发,到 dst 为止,最多经过 k 站(这里 k 包括 src)
*
* @param src 起点站
* @param dst 终点站
* @param k 经过的站点数限制
* @param cost 已经花费的价格
*/
private void dfs(int src, int dst, int k, int cost) {
if (src == dst) {
res = cost;
return;
}
if (k == 0) {
return;
}
// 遍历 src 的邻接顶点
for (int i = 0; i < graph[src].length; i++) {
if (graph[src][i] > 0) {
// 这里 graph[src][i] 表示存在一条有向边
if (visited[i]) {
continue;
}
// 剪枝:跳过可能产生较高费用的路径,从而选出最少价格
if (cost + graph[src][i] > res) {
continue;
}
visited[i] = true;
dfs(i, dst, k - 1, cost + graph[src][i]);
// 回溯
visited[i] = false;
}
}
}
}
| 23.666667
| 83
| 0.415799
|
221dac77e1480c851aa467f7904f287d8debafbf
| 12,374
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec.net;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.BitSet;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringDecoder;
import org.apache.commons.codec.StringEncoder;
/**
* Similar to the Quoted-Printable content-transfer-encoding defined in
* <a href="http://www.ietf.org/rfc/rfc1521.txt">RFC 1521</a> and designed to allow text containing mostly ASCII
* characters to be decipherable on an ASCII terminal without decoding.
* <p>
* <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522</a> describes techniques to allow the encoding of non-ASCII
* text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message
* handling software.
* <p>
* This class is conditionally thread-safe.
* The instance field {@link #encodeBlanks} is mutable {@link #setEncodeBlanks(boolean)}
* but is not volatile, and accesses are not synchronised.
* If an instance of the class is shared between threads, the caller needs to ensure that suitable synchronisation
* is used to ensure safe publication of the value between threads, and must not invoke
* {@link #setEncodeBlanks(boolean)} after initial setup.
*
* @see <a href="http://www.ietf.org/rfc/rfc1522.txt">MIME (Multipurpose Internet Mail Extensions) Part Two: Message
* Header Extensions for Non-ASCII Text</a>
*
* @since 1.3
*/
public class QCodec extends RFC1522Codec implements StringEncoder, StringDecoder {
/**
* The default Charset used for string decoding and encoding.
*/
private final Charset charset;
/**
* BitSet of printable characters as defined in RFC 1522.
*/
private static final BitSet PRINTABLE_CHARS = new BitSet(256);
// Static initializer for printable chars collection
static {
// alpha characters
PRINTABLE_CHARS.set(' ');
PRINTABLE_CHARS.set('!');
PRINTABLE_CHARS.set('"');
PRINTABLE_CHARS.set('#');
PRINTABLE_CHARS.set('$');
PRINTABLE_CHARS.set('%');
PRINTABLE_CHARS.set('&');
PRINTABLE_CHARS.set('\'');
PRINTABLE_CHARS.set('(');
PRINTABLE_CHARS.set(')');
PRINTABLE_CHARS.set('*');
PRINTABLE_CHARS.set('+');
PRINTABLE_CHARS.set(',');
PRINTABLE_CHARS.set('-');
PRINTABLE_CHARS.set('.');
PRINTABLE_CHARS.set('/');
for (int i = '0'; i <= '9'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set(':');
PRINTABLE_CHARS.set(';');
PRINTABLE_CHARS.set('<');
PRINTABLE_CHARS.set('>');
PRINTABLE_CHARS.set('@');
for (int i = 'A'; i <= 'Z'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set('[');
PRINTABLE_CHARS.set('\\');
PRINTABLE_CHARS.set(']');
PRINTABLE_CHARS.set('^');
PRINTABLE_CHARS.set('`');
for (int i = 'a'; i <= 'z'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set('{');
PRINTABLE_CHARS.set('|');
PRINTABLE_CHARS.set('}');
PRINTABLE_CHARS.set('~');
}
private static final byte SPACE = 32;
private static final byte UNDERSCORE = 95;
private boolean encodeBlanks = false;
/**
* Default constructor.
*/
public QCodec() {
this(Charsets.UTF_8);
}
/**
* Constructor which allows for the selection of a default Charset.
*
* @param charset
* the default string Charset to use.
*
* @see <a href="http://download.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @since 1.7
*/
public QCodec(final Charset charset) {
super();
this.charset = charset;
}
/**
* Constructor which allows for the selection of a default Charset.
*
* @param charsetName
* the Charset to use.
* @throws java.nio.charset.UnsupportedCharsetException
* If the named Charset is unavailable
* @since 1.7 throws UnsupportedCharsetException if the named Charset is unavailable
* @see <a href="http://download.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
public QCodec(final String charsetName) {
this(Charset.forName(charsetName));
}
@Override
protected String getEncoding() {
return "Q";
}
@Override
protected byte[] doEncoding(final byte[] bytes) {
if (bytes == null) {
return null;
}
final byte[] data = QuotedPrintableCodec.encodeQuotedPrintable(PRINTABLE_CHARS, bytes);
if (this.encodeBlanks) {
for (int i = 0; i < data.length; i++) {
if (data[i] == SPACE) {
data[i] = UNDERSCORE;
}
}
}
return data;
}
@Override
protected byte[] doDecoding(final byte[] bytes) throws DecoderException {
if (bytes == null) {
return null;
}
boolean hasUnderscores = false;
for (final byte b : bytes) {
if (b == UNDERSCORE) {
hasUnderscores = true;
break;
}
}
if (hasUnderscores) {
final byte[] tmp = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
final byte b = bytes[i];
if (b != UNDERSCORE) {
tmp[i] = b;
} else {
tmp[i] = SPACE;
}
}
return QuotedPrintableCodec.decodeQuotedPrintable(tmp);
}
return QuotedPrintableCodec.decodeQuotedPrintable(bytes);
}
/**
* Encodes a string into its quoted-printable form using the specified Charset. Unsafe characters are escaped.
*
* @param sourceStr
* string to convert to quoted-printable form
* @param sourceCharset
* the Charset for sourceStr
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
* @since 1.7
*/
public String encode(final String sourceStr, final Charset sourceCharset) throws EncoderException {
if (sourceStr == null) {
return null;
}
return encodeText(sourceStr, sourceCharset);
}
/**
* Encodes a string into its quoted-printable form using the specified Charset. Unsafe characters are escaped.
*
* @param sourceStr
* string to convert to quoted-printable form
* @param sourceCharset
* the Charset for sourceStr
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
public String encode(final String sourceStr, final String sourceCharset) throws EncoderException {
if (sourceStr == null) {
return null;
}
try {
return encodeText(sourceStr, sourceCharset);
} catch (final UnsupportedEncodingException e) {
throw new EncoderException(e.getMessage(), e);
}
}
/**
* Encodes a string into its quoted-printable form using the default Charset. Unsafe characters are escaped.
*
* @param sourceStr
* string to convert to quoted-printable form
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
@Override
public String encode(final String sourceStr) throws EncoderException {
if (sourceStr == null) {
return null;
}
return encode(sourceStr, getCharset());
}
/**
* Decodes a quoted-printable string into its original form. Escaped characters are converted back to their original
* representation.
*
* @param str
* quoted-printable string to convert into its original form
* @return original string
* @throws DecoderException
* A decoder exception is thrown if a failure condition is encountered during the decode process.
*/
@Override
public String decode(final String str) throws DecoderException {
if (str == null) {
return null;
}
try {
return decodeText(str);
} catch (final UnsupportedEncodingException e) {
throw new DecoderException(e.getMessage(), e);
}
}
/**
* Encodes an object into its quoted-printable form using the default Charset. Unsafe characters are escaped.
*
* @param obj
* object to convert to quoted-printable form
* @return quoted-printable object
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
@Override
public Object encode(final Object obj) throws EncoderException {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return encode((String) obj);
} else {
throw new EncoderException("Objects of type " +
obj.getClass().getName() +
" cannot be encoded using Q codec");
}
}
/**
* Decodes a quoted-printable object into its original form. Escaped characters are converted back to their original
* representation.
*
* @param obj
* quoted-printable object to convert into its original form
* @return original object
* @throws DecoderException
* Thrown if the argument is not a <code>String</code>. Thrown if a failure condition is encountered
* during the decode process.
*/
@Override
public Object decode(final Object obj) throws DecoderException {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return decode((String) obj);
} else {
throw new DecoderException("Objects of type " +
obj.getClass().getName() +
" cannot be decoded using Q codec");
}
}
/**
* Gets the default Charset name used for string decoding and encoding.
*
* @return the default Charset name
* @since 1.7
*/
public Charset getCharset() {
return this.charset;
}
/**
* Gets the default Charset name used for string decoding and encoding.
*
* @return the default Charset name
*/
public String getDefaultCharset() {
return this.charset.name();
}
/**
* Tests if optional transformation of SPACE characters is to be used
*
* @return <code>true</code> if SPACE characters are to be transformed, <code>false</code> otherwise
*/
public boolean isEncodeBlanks() {
return this.encodeBlanks;
}
/**
* Defines whether optional transformation of SPACE characters is to be used
*
* @param b
* <code>true</code> if SPACE characters are to be transformed, <code>false</code> otherwise
*/
public void setEncodeBlanks(final boolean b) {
this.encodeBlanks = b;
}
}
| 34.564246
| 120
| 0.610474
|
4c29b55e2b1b47fd64eb4682c235ad7a7bcdd842
| 498
|
package com.cbeardsmore.scart.domain.commands;
import com.cbeardsmore.scart.domain.command.CheckoutCommand;
import com.cbeardsmore.scart.domain.exception.CommandValidationException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CheckoutCommandTest {
@Test
void givenNullCartIdShouldThrowCommandValidationException() {
assertThrows(CommandValidationException.class,
() -> new CheckoutCommand(null));
}
}
| 31.125
| 73
| 0.779116
|
54a57b574575774bd975ca8704d272b98a4f8365
| 1,202
|
package com.thinkaurelius.titan.graphdb.loadingstatus;
import com.thinkaurelius.titan.graphdb.query.InternalTitanQuery;
import com.thinkaurelius.titan.graphdb.relations.EdgeDirection;
import com.thinkaurelius.titan.util.datastructures.BitMap;
public class DirectionTypeEncoder {
public static final boolean hasAllCovered(byte code, InternalTitanQuery query) {
for (EdgeDirection dir : EdgeDirection.values()) {
if (!query.hasDirectionCondition() || query.isAllowedDirection(dir)) {
if (dir==EdgeDirection.OUT && query.queryProperties()) {
if (!BitMap.readBitb(code, dir.getID()*2+1)) return false;
}
if (query.queryRelationships()){
if (!BitMap.readBitb(code, dir.getID()*2)) return false;
}
}
}
return true;
}
public static final byte loaded(byte code, InternalTitanQuery query) {
for (EdgeDirection dir : EdgeDirection.values()) {
if (!query.hasDirectionCondition() || query.isAllowedDirection(dir)) {
if (dir==EdgeDirection.OUT && query.queryProperties()) {
code = BitMap.setBitb(code, dir.getID()*2+1);
}
if (query.queryRelationships()){
code = BitMap.setBitb(code, dir.getID() * 2);
}
}
}
return code;
}
}
| 30.05
| 81
| 0.704659
|
94be312ab5fc2d7309ec9ca91c3cc6218ac9d5c9
| 13,359
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.usergrid.services;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.usergrid.ServiceITSetup;
import org.apache.usergrid.ServiceITSetupImpl;
import org.apache.usergrid.ServiceITSuite;
import org.apache.usergrid.cassandra.ClearShiroSubject;
import org.apache.usergrid.cassandra.Concurrent;
import org.apache.usergrid.management.ApplicationInfo;
import org.apache.usergrid.management.OrganizationOwnerInfo;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityManager;
import org.apache.usergrid.persistence.EntityRef;
import org.apache.usergrid.persistence.SimpleEntityRef;
import org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils;
import org.apache.usergrid.persistence.cassandra.CassandraService;
import org.apache.usergrid.persistence.entities.User;
import org.apache.usergrid.persistence.exceptions.DuplicateUniquePropertyExistsException;
import org.apache.usergrid.utils.UUIDUtils;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.mutation.Mutator;
import static me.prettyprint.hector.api.factory.HFactory.createMutator;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_UNIQUE;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addInsertToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.createTimestamp;
import static org.apache.usergrid.persistence.cassandra.CassandraService.DEFAULT_APPLICATION_ID;
import static org.apache.usergrid.persistence.cassandra.Serializers.be;
import static org.apache.usergrid.services.ServiceParameter.filter;
import static org.apache.usergrid.services.ServiceParameter.parameters;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
@NotThreadSafe()
public class ServiceRequestIT {
private static final Logger logger = LoggerFactory.getLogger( ServiceRequestIT.class );
@Rule
public ClearShiroSubject clearShiroSubject = new ClearShiroSubject();
@Rule
public ServiceITSetup setup = new ServiceITSetupImpl( ServiceITSuite.cassandraResource );
@Test
public void testPaths() throws Exception {
UUID applicationId = DEFAULT_APPLICATION_ID;
ServiceManager services = setup.getSmf().getServiceManager( applicationId );
ServiceRequest path = services.newRequest( ServiceAction.GET, parameters( "users", "bob" ), null );
// path = path.addSegment("users", "bob");
logger.info( "" + path.getParameters() );
Map<List<String>, List<String>> replaceParameters = new LinkedHashMap<List<String>, List<String>>();
replaceParameters.put( Arrays.asList( "users" ), Arrays.asList( "connecting", "users" ) );
List<ServiceParameter> p = filter( path.getParameters(), replaceParameters );
// path = path.addSegment("messages", "bob");
logger.info( "" + p );
path = services.newRequest( ServiceAction.GET, parameters( "users", UUID.randomUUID(), "messages" ), null );
logger.info( "" + path.getParameters() );
logger.info( "\\1" );
replaceParameters = new LinkedHashMap<List<String>, List<String>>();
replaceParameters.put( Arrays.asList( "users", "$id" ), Arrays.asList( "connecting", "\\1", "users" ) );
p = filter( path.getParameters(), replaceParameters );
logger.info( "" + p );
}
//Verify that entity read repair is functioning as intended.
@Ignore("Temporarily disabled as read repair is disabled temporarily in EntityManagerImpl.")
@Test
public void testRepairOfSingleEntity() throws Exception{
String rand = RandomStringUtils.randomAlphanumeric( 10 );
String orgName = "org_" + rand;
String appName = "app_" +rand;
String username = "username_" + rand;
String adminUsername = "admin_"+rand;
String email = username+"@derp.com";
String password = username;
String collectionName = "users";
OrganizationOwnerInfo organizationOwnerInfo = setup.getMgmtSvc().createOwnerAndOrganization( orgName,adminUsername,adminUsername,email,password );
ApplicationInfo applicationInfo = setup.getMgmtSvc().createApplication( organizationOwnerInfo.getOrganization().getUuid(),appName );
EntityManager entityManager = setup.getEmf().getEntityManager( applicationInfo.getId() );
Map<String,Object> userInfo = new HashMap<String, Object>( );
userInfo.put( "username",username );
//Entity entityToBeCorrupted = entityManager.create( collectionName,userInfo );
CassandraService cass = setup.getCassSvc();
Object key = CassandraPersistenceUtils.key( applicationInfo.getId(), collectionName, "username", username );
Keyspace ko = cass.getApplicationKeyspace( applicationInfo.getId() );
Mutator<ByteBuffer> m = createMutator( ko, be );
UUID testEntityUUID = UUIDUtils.newTimeUUID();
//this below calll should make the column family AND the column name
addInsertToMutator( m,ENTITY_UNIQUE,key, testEntityUUID,0,createTimestamp());
m.execute();
//verify that there is no corresponding entity with the uuid or alias provided
//verify it returns null.
assertNull(entityManager.get( testEntityUUID ));
//the below works but not needed for this test.
//assertNull( entityManager.getAlias("user",username));
//verify that we cannot recreate the entity due to duplicate unique property exception
Entity entityToBeCorrupted = null;
try {
entityToBeCorrupted = entityManager.create( collectionName, userInfo );
}catch(Exception e){
fail("Create call should have worked");
}
assertNotNull( entityToBeCorrupted );
assertEquals( username,( ( User ) entityToBeCorrupted ).getUsername() );
}
@Ignore("Temporarily disabled as read repair is disabled temporarily in EntityManagerImpl.")
@Test
public void testRepairOfOnlyOneOfTwoColumns() throws Exception{
String rand = RandomStringUtils.randomAlphanumeric( 10 );
String orgName = "org_" + rand;
String appName = "app_" +rand;
String username = "username_" + rand;
String adminUsername = "admin_"+rand;
String email = username+"@derp.com";
String password = username;
String collectionName = "users";
OrganizationOwnerInfo organizationOwnerInfo = setup.getMgmtSvc().createOwnerAndOrganization( orgName,adminUsername,adminUsername,email,password );
ApplicationInfo applicationInfo = setup.getMgmtSvc().createApplication( organizationOwnerInfo.getOrganization().getUuid(),appName );
EntityManager entityManager = setup.getEmf().getEntityManager( applicationInfo.getId() );
Map<String,Object> userInfo = new HashMap<String, Object>( );
userInfo.put( "username",username );
//Entity entityToBeCorrupted = entityManager.create( collectionName,userInfo );
CassandraService cass = setup.getCassSvc();
Object key = CassandraPersistenceUtils.key( applicationInfo.getId(), collectionName, "username", username );
Keyspace ko = cass.getApplicationKeyspace( applicationInfo.getId() );
Mutator<ByteBuffer> m = createMutator( ko, be );
//create a new column
Entity validCoexistingEntity = entityManager.create( collectionName, userInfo );
UUID testEntityUUID = UUIDUtils.newTimeUUID();
//this below calll should make the column family AND the column name for an already existing column thus adding one legit and one dummy value.
addInsertToMutator( m,ENTITY_UNIQUE,key, testEntityUUID,0,createTimestamp());
m.execute();
//verify that there is no corresponding entity with the uuid or alias provided
//verify it returns null.
assertNull(entityManager.get( testEntityUUID ));
//the below works but not needed for this test.
//assertNull( entityManager.getAlias("user",username));
//verify that we cannot recreate the entity due to duplicate unique property exception
Entity entityToBeCorrupted = null;
try {
entityToBeCorrupted = entityManager.create( collectionName, userInfo );
fail();
}catch(DuplicateUniquePropertyExistsException dup){
}
catch(Exception e){
throw e;
}
//verifies it works when doing a get/read repair
assertNotNull( entityManager
.get( entityManager.getAlias( applicationInfo.getId(), collectionName, username ).getUuid() ) );
}
//For this test you need to insert a dummy key with a dummy column that leads to nowhere
//then run the unique index cleanup.
//checks for bug when only column doesn't exist make sure to delete the row as well.
@Ignore("Temporarily disabled as read repair is disabled temporarily in EntityManagerImpl.")
@Test
public void testRepairOfMultipleEntitiesAndRemainingEntities() throws Exception{
String rand = RandomStringUtils.randomAlphanumeric( 10 );
int numberOfEntitiesToCreate = 1000;
String orgName = "org_" + rand;
String appName = "app_" +rand;
String username = "username_" + rand;
String adminUsername = "admin_"+rand;
String email = username+"@derp.com";
String password = username;
String collectionName = "users";
OrganizationOwnerInfo organizationOwnerInfo = setup.getMgmtSvc().createOwnerAndOrganization( orgName,adminUsername,adminUsername,email,password );
ApplicationInfo applicationInfo = setup.getMgmtSvc().createApplication( organizationOwnerInfo.getOrganization().getUuid(),appName );
EntityManager entityManager = setup.getEmf().getEntityManager( applicationInfo.getId() );
String[] usernames = new String[numberOfEntitiesToCreate];
Entity[] entities = new Entity[numberOfEntitiesToCreate];
int index = 0;
while(index < numberOfEntitiesToCreate) {
usernames[index]=username+index;
Map<String, Object> userInfo = new HashMap<String, Object>();
userInfo.put( "username", usernames[index] );
CassandraService cass = setup.getCassSvc();
entities[index] = entityManager.create( collectionName,userInfo );
Object key = CassandraPersistenceUtils.key( applicationInfo.getId(), collectionName, "username", usernames[index] );
Keyspace ko = cass.getApplicationKeyspace( applicationInfo.getId() );
Mutator<ByteBuffer> m = createMutator( ko, be );
UUID testEntityUUID = UUIDUtils.newTimeUUID();
//this below calll should make the column family AND the column name
addInsertToMutator( m, ENTITY_UNIQUE, key, testEntityUUID, 0, createTimestamp() );
m.execute();
index++;
//the below works but not needed for this test.
//assertNull( entityManager.getAlias("user",username));
//verify that we cannot recreate the entity due to duplicate unique property exception
Entity entityToBeCorrupted = null;
try {
entityToBeCorrupted = entityManager.create( collectionName, userInfo );
fail();
}catch(DuplicateUniquePropertyExistsException dup){
}
catch(Exception e){
fail("shouldn't throw something else i think");
}
}
for(String user:usernames ) {
Map<String, Object> userInfo = new HashMap<String, Object>();
userInfo.put( "username", user);
EntityRef entityRef = entityManager.getAlias( collectionName,user );
Entity entityToBeCorrupted = entityManager.get( entityRef );
assertNotNull( entityToBeCorrupted );
assertEquals( user, ( ( User ) entityToBeCorrupted ).getUsername() );
}
}
}
| 41.616822
| 154
| 0.706191
|
3512b26a63ee62ddaeda992caa47d18d26a2284a
| 4,554
|
/*
*
* *
* * * Copyright 2015 Skymind,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.canova.api.records.reader.impl;
import org.canova.api.conf.Configuration;
import org.canova.api.io.data.DoubleWritable;
import org.canova.api.io.data.IntWritable;
import org.canova.api.io.data.Text;
import org.canova.api.records.reader.LibSvm;
import org.canova.api.split.InputSplit;
import org.canova.api.writable.Writable;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Adam Gibson
*/
public class LibSvmRecordReader extends LineRecordReader implements LibSvm {
public static final String NAME_SPACE = LibSvmRecordReader.class.getName();
public static final String NUM_FEATURES = NAME_SPACE + ".numfeatures";
private boolean appendLabel = false;
private boolean classification = true;
private int numFeatures;
@Override
public void initialize(InputSplit split) throws IOException, InterruptedException {
super.initialize(split);
}
@Override
public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException {
super.initialize(conf, split);
appendLabel = conf.getBoolean(APPEND_LABEL,false);
classification = conf.getBoolean(CLASSIFICATION,true);
numFeatures = conf.getInt(NUM_FEATURES, 0);
}
@Override
public Collection<Writable> next() {
Text record2 = (Text) super.next().iterator().next();
String line = record2.toString();
String[] tokens = line.trim().split("\\s+");
Double response;
try {
response = Integer.valueOf(tokens[0]).doubleValue();
} catch (NumberFormatException e) {
try {
response = Double.valueOf(tokens[0]);
classification = false;
} catch (NumberFormatException ex) {
System.err.println(ex);
throw new NumberFormatException("Unrecognized response variable value: " + tokens[0]);
}
}
tokens = line.trim().split("\\s+");
Collection<Writable> record = new ArrayList<>();
int read = 0;
for (int k = 1; k < tokens.length; k++) {
String[] pair = tokens[k].split(":");
if (pair.length != 2) {
throw new NumberFormatException("Invalid data: " + tokens[k]);
}
int j = Integer.valueOf(pair[0]) - 1;
while(j != read){
record.add(new DoubleWritable(0.0));
read++;
}
try {
int x = Integer.valueOf(pair[1]);
record.add(new IntWritable(x));
}catch(NumberFormatException e) {
double x = Double.valueOf(pair[1]);
record.add(new DoubleWritable(x));
}
read++;
}
while( read < numFeatures ){
record.add(new DoubleWritable(0.0));
read++;
}
if(classification && appendLabel || !classification) {
record.add(new DoubleWritable(response));
}
return record;
}
@Override
public boolean hasNext() {
return super.hasNext();
}
@Override
public void close() throws IOException {
super.close();
}
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
}
@Override
public Configuration getConf() {
return super.getConf();
}
@Override
public Collection<Writable> record(URI uri, DataInputStream dataInputStream) throws IOException {
//Here: we are reading a single line from the DataInputStream. How to handle headers?
throw new UnsupportedOperationException("Reading LibSVM data from DataInputStream not yet implemented");
}
}
| 30.979592
| 112
| 0.612429
|
f394b1323855afa10eaf69858c114ba94007897c
| 581
|
package frc.robot.commands.intake;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.IntakeSubsystem;
public class RunIntake extends CommandBase {
// The subsystem the command runs on
private final IntakeSubsystem m_intakeSubsystem;
public RunIntake(IntakeSubsystem subsystem) {
m_intakeSubsystem = subsystem;
addRequirements(m_intakeSubsystem);
}
@Override
public void initialize() {
m_intakeSubsystem.runIntake();
}
@Override
public boolean isFinished() {
return true;
}
}
| 23.24
| 52
| 0.710843
|
e7532ffd4dd5ae3c271144a0575a02d5b3eedef6
| 83,360
|
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.X11;
public interface XKeySymConstants {
public static final long XK_VoidSymbol = 0xFFFFFF ; /* void symbol */
/*
* TTY Functions, cleverly chosen to map to ascii, for convenience of
* programming, but could have been arbitrary (at the cost of lookup
* tables in client code.
*/
public static final long XK_BackSpace = 0xFF08 ; /* back space, back char */
public static final long XK_Tab = 0xFF09 ;
public static final long XK_Linefeed = 0xFF0A ; /* Linefeed, LF */
public static final long XK_Clear = 0xFF0B ;
public static final long XK_Return = 0xFF0D ; /* Return, enter */
public static final long XK_Pause = 0xFF13 ; /* Pause, hold */
public static final long XK_Scroll_Lock = 0xFF14 ;
public static final long XK_Sys_Req = 0xFF15 ;
public static final long XK_Escape = 0xFF1B ;
public static final long XK_Delete = 0xFFFF ; /* Delete, rubout */
/* International & multi-key character composition */
public static final long XK_Multi_key = 0xFF20 ; /* Multi-key character compose */
public static final long XK_Codeinput = 0xFF37 ;
public static final long XK_SingleCandidate = 0xFF3C ;
public static final long XK_MultipleCandidate = 0xFF3D ;
public static final long XK_PreviousCandidate = 0xFF3E ;
/* Japanese keyboard support */
public static final long XK_Kanji = 0xFF21 ; /* Kanji, Kanji convert */
public static final long XK_Muhenkan = 0xFF22 ; /* Cancel Conversion */
public static final long XK_Henkan_Mode = 0xFF23 ; /* Start/Stop Conversion */
public static final long XK_Henkan = 0xFF23 ; /* Alias for Henkan_Mode */
public static final long XK_Romaji = 0xFF24 ; /* to Romaji */
public static final long XK_Hiragana = 0xFF25 ; /* to Hiragana */
public static final long XK_Katakana = 0xFF26 ; /* to Katakana */
public static final long XK_Hiragana_Katakana = 0xFF27 ; /* Hiragana/Katakana toggle */
public static final long XK_Zenkaku = 0xFF28 ; /* to Zenkaku */
public static final long XK_Hankaku = 0xFF29 ; /* to Hankaku */
public static final long XK_Zenkaku_Hankaku = 0xFF2A ; /* Zenkaku/Hankaku toggle */
public static final long XK_Touroku = 0xFF2B ; /* Add to Dictionary */
public static final long XK_Massyo = 0xFF2C ; /* Delete from Dictionary */
public static final long XK_Kana_Lock = 0xFF2D ; /* Kana Lock */
public static final long XK_Kana_Shift = 0xFF2E ; /* Kana Shift */
public static final long XK_Eisu_Shift = 0xFF2F ; /* Alphanumeric Shift */
public static final long XK_Eisu_toggle = 0xFF30 ; /* Alphanumeric toggle */
public static final long XK_Kanji_Bangou = 0xFF37 ; /* Codeinput */
public static final long XK_Zen_Koho = 0xFF3D ; /* Multiple/All Candidate(s) */
public static final long XK_Mae_Koho = 0xFF3E ; /* Previous Candidate */
/* 0xFF31 thru 0xFF3F are under XK_KOREAN */
/* Cursor control & motion */
public static final long XK_Home = 0xFF50 ;
public static final long XK_Left = 0xFF51 ; /* Move left, left arrow */
public static final long XK_Up = 0xFF52 ; /* Move up, up arrow */
public static final long XK_Right = 0xFF53 ; /* Move right, right arrow */
public static final long XK_Down = 0xFF54 ; /* Move down, down arrow */
public static final long XK_Prior = 0xFF55 ; /* Prior, previous */
public static final long XK_Page_Up = 0xFF55 ;
public static final long XK_Next = 0xFF56 ; /* Next */
public static final long XK_Page_Down = 0xFF56 ;
public static final long XK_End = 0xFF57 ; /* EOL */
public static final long XK_Begin = 0xFF58 ; /* BOL */
/* Misc Functions */
public static final long XK_Select = 0xFF60 ; /* Select, mark */
public static final long XK_Print = 0xFF61 ;
public static final long XK_Execute = 0xFF62 ; /* Execute, run, do */
public static final long XK_Insert = 0xFF63 ; /* Insert, insert here */
public static final long XK_Undo = 0xFF65 ; /* Undo, oops */
public static final long XK_Redo = 0xFF66 ; /* redo, again */
public static final long XK_Menu = 0xFF67 ;
public static final long XK_Find = 0xFF68 ; /* Find, search */
public static final long XK_Cancel = 0xFF69 ; /* Cancel, stop, abort, exit */
public static final long XK_Help = 0xFF6A ; /* Help */
public static final long XK_Break = 0xFF6B ;
public static final long XK_Mode_switch = 0xFF7E ; /* Character set switch */
public static final long XK_script_switch = 0xFF7E ; /* Alias for mode_switch */
public static final long XK_Num_Lock = 0xFF7F ;
/* Keypad Functions, keypad numbers cleverly chosen to map to ascii */
public static final long XK_KP_Space = 0xFF80 ; /* space */
public static final long XK_KP_Tab = 0xFF89 ;
public static final long XK_KP_Enter = 0xFF8D ; /* enter */
public static final long XK_KP_F1 = 0xFF91 ; /* PF1, KP_A, ... */
public static final long XK_KP_F2 = 0xFF92 ;
public static final long XK_KP_F3 = 0xFF93 ;
public static final long XK_KP_F4 = 0xFF94 ;
public static final long XK_KP_Home = 0xFF95 ;
public static final long XK_KP_Left = 0xFF96 ;
public static final long XK_KP_Up = 0xFF97 ;
public static final long XK_KP_Right = 0xFF98 ;
public static final long XK_KP_Down = 0xFF99 ;
public static final long XK_KP_Prior = 0xFF9A ;
public static final long XK_KP_Page_Up = 0xFF9A ;
public static final long XK_KP_Next = 0xFF9B ;
public static final long XK_KP_Page_Down = 0xFF9B ;
public static final long XK_KP_End = 0xFF9C ;
public static final long XK_KP_Begin = 0xFF9D ;
public static final long XK_KP_Insert = 0xFF9E ;
public static final long XK_KP_Delete = 0xFF9F ;
public static final long XK_KP_Equal = 0xFFBD ; /* equals */
public static final long XK_KP_Multiply = 0xFFAA ;
public static final long XK_KP_Add = 0xFFAB ;
public static final long XK_KP_Separator = 0xFFAC ; /* separator, often comma */
public static final long XK_KP_Subtract = 0xFFAD ;
public static final long XK_KP_Decimal = 0xFFAE ;
public static final long XK_KP_Divide = 0xFFAF ;
public static final long XK_KP_0 = 0xFFB0 ;
public static final long XK_KP_1 = 0xFFB1 ;
public static final long XK_KP_2 = 0xFFB2 ;
public static final long XK_KP_3 = 0xFFB3 ;
public static final long XK_KP_4 = 0xFFB4 ;
public static final long XK_KP_5 = 0xFFB5 ;
public static final long XK_KP_6 = 0xFFB6 ;
public static final long XK_KP_7 = 0xFFB7 ;
public static final long XK_KP_8 = 0xFFB8 ;
public static final long XK_KP_9 = 0xFFB9 ;
/*
* Auxilliary Functions; note the duplicate definitions for left and right
* function keys; Sun keyboards and a few other manufactures have such
* function key groups on the left and/or right sides of the keyboard.
* We've not found a keyboard with more than 35 function keys total.
*/
public static final long XK_F1 = 0xFFBE ;
public static final long XK_F2 = 0xFFBF ;
public static final long XK_F3 = 0xFFC0 ;
public static final long XK_F4 = 0xFFC1 ;
public static final long XK_F5 = 0xFFC2 ;
public static final long XK_F6 = 0xFFC3 ;
public static final long XK_F7 = 0xFFC4 ;
public static final long XK_F8 = 0xFFC5 ;
public static final long XK_F9 = 0xFFC6 ;
public static final long XK_F10 = 0xFFC7 ;
public static final long XK_F11 = 0xFFC8 ;
public static final long XK_L1 = 0xFFC8 ;
public static final long XK_F12 = 0xFFC9 ;
public static final long XK_L2 = 0xFFC9 ;
public static final long XK_F13 = 0xFFCA ;
public static final long XK_L3 = 0xFFCA ;
public static final long XK_F14 = 0xFFCB ;
public static final long XK_L4 = 0xFFCB ;
public static final long XK_F15 = 0xFFCC ;
public static final long XK_L5 = 0xFFCC ;
public static final long XK_F16 = 0xFFCD ;
public static final long XK_L6 = 0xFFCD ;
public static final long XK_F17 = 0xFFCE ;
public static final long XK_L7 = 0xFFCE ;
public static final long XK_F18 = 0xFFCF ;
public static final long XK_L8 = 0xFFCF ;
public static final long XK_F19 = 0xFFD0 ;
public static final long XK_L9 = 0xFFD0 ;
public static final long XK_F20 = 0xFFD1 ;
public static final long XK_L10 = 0xFFD1 ;
public static final long XK_F21 = 0xFFD2 ;
public static final long XK_R1 = 0xFFD2 ;
public static final long XK_F22 = 0xFFD3 ;
public static final long XK_R2 = 0xFFD3 ;
public static final long XK_F23 = 0xFFD4 ;
public static final long XK_R3 = 0xFFD4 ;
public static final long XK_F24 = 0xFFD5 ;
public static final long XK_R4 = 0xFFD5 ;
public static final long XK_F25 = 0xFFD6 ;
public static final long XK_R5 = 0xFFD6 ;
public static final long XK_F26 = 0xFFD7 ;
public static final long XK_R6 = 0xFFD7 ;
public static final long XK_F27 = 0xFFD8 ;
public static final long XK_R7 = 0xFFD8 ;
public static final long XK_F28 = 0xFFD9 ;
public static final long XK_R8 = 0xFFD9 ;
public static final long XK_F29 = 0xFFDA ;
public static final long XK_R9 = 0xFFDA ;
public static final long XK_F30 = 0xFFDB ;
public static final long XK_R10 = 0xFFDB ;
public static final long XK_F31 = 0xFFDC ;
public static final long XK_R11 = 0xFFDC ;
public static final long XK_F32 = 0xFFDD ;
public static final long XK_R12 = 0xFFDD ;
public static final long XK_F33 = 0xFFDE ;
public static final long XK_R13 = 0xFFDE ;
public static final long XK_F34 = 0xFFDF ;
public static final long XK_R14 = 0xFFDF ;
public static final long XK_F35 = 0xFFE0 ;
public static final long XK_R15 = 0xFFE0 ;
/* Modifiers */
public static final long XK_Shift_L = 0xFFE1 ; /* Left shift */
public static final long XK_Shift_R = 0xFFE2 ; /* Right shift */
public static final long XK_Control_L = 0xFFE3 ; /* Left control */
public static final long XK_Control_R = 0xFFE4 ; /* Right control */
public static final long XK_Caps_Lock = 0xFFE5 ; /* Caps lock */
public static final long XK_Shift_Lock = 0xFFE6 ; /* Shift lock */
public static final long XK_Meta_L = 0xFFE7 ; /* Left meta */
public static final long XK_Meta_R = 0xFFE8 ; /* Right meta */
public static final long XK_Alt_L = 0xFFE9 ; /* Left alt */
public static final long XK_Alt_R = 0xFFEA ; /* Right alt */
public static final long XK_Super_L = 0xFFEB ; /* Left super */
public static final long XK_Super_R = 0xFFEC ; /* Right super */
public static final long XK_Hyper_L = 0xFFED ; /* Left hyper */
public static final long XK_Hyper_R = 0xFFEE ; /* Right hyper */
/*
* ISO 9995 Function and Modifier Keys
* Byte 3 = 0xFE
*/
public static final long XK_ISO_Lock = 0xFE01 ;
public static final long XK_ISO_Level2_Latch = 0xFE02 ;
public static final long XK_ISO_Level3_Shift = 0xFE03 ;
public static final long XK_ISO_Level3_Latch = 0xFE04 ;
public static final long XK_ISO_Level3_Lock = 0xFE05 ;
public static final long XK_ISO_Group_Shift = 0xFF7E ; /* Alias for mode_switch */
public static final long XK_ISO_Group_Latch = 0xFE06 ;
public static final long XK_ISO_Group_Lock = 0xFE07 ;
public static final long XK_ISO_Next_Group = 0xFE08 ;
public static final long XK_ISO_Next_Group_Lock = 0xFE09 ;
public static final long XK_ISO_Prev_Group = 0xFE0A ;
public static final long XK_ISO_Prev_Group_Lock = 0xFE0B ;
public static final long XK_ISO_First_Group = 0xFE0C ;
public static final long XK_ISO_First_Group_Lock = 0xFE0D ;
public static final long XK_ISO_Last_Group = 0xFE0E ;
public static final long XK_ISO_Last_Group_Lock = 0xFE0F ;
public static final long XK_ISO_Left_Tab = 0xFE20 ;
public static final long XK_ISO_Move_Line_Up = 0xFE21 ;
public static final long XK_ISO_Move_Line_Down = 0xFE22 ;
public static final long XK_ISO_Partial_Line_Up = 0xFE23 ;
public static final long XK_ISO_Partial_Line_Down = 0xFE24 ;
public static final long XK_ISO_Partial_Space_Left = 0xFE25 ;
public static final long XK_ISO_Partial_Space_Right = 0xFE26 ;
public static final long XK_ISO_Set_Margin_Left = 0xFE27 ;
public static final long XK_ISO_Set_Margin_Right = 0xFE28 ;
public static final long XK_ISO_Release_Margin_Left = 0xFE29 ;
public static final long XK_ISO_Release_Margin_Right = 0xFE2A ;
public static final long XK_ISO_Release_Both_Margins = 0xFE2B ;
public static final long XK_ISO_Fast_Cursor_Left = 0xFE2C ;
public static final long XK_ISO_Fast_Cursor_Right = 0xFE2D ;
public static final long XK_ISO_Fast_Cursor_Up = 0xFE2E ;
public static final long XK_ISO_Fast_Cursor_Down = 0xFE2F ;
public static final long XK_ISO_Continuous_Underline = 0xFE30 ;
public static final long XK_ISO_Discontinuous_Underline = 0xFE31 ;
public static final long XK_ISO_Emphasize = 0xFE32 ;
public static final long XK_ISO_Center_Object = 0xFE33 ;
public static final long XK_ISO_Enter = 0xFE34 ;
public static final long XK_dead_grave = 0xFE50 ;
public static final long XK_dead_acute = 0xFE51 ;
public static final long XK_dead_circumflex = 0xFE52 ;
public static final long XK_dead_tilde = 0xFE53 ;
public static final long XK_dead_macron = 0xFE54 ;
public static final long XK_dead_breve = 0xFE55 ;
public static final long XK_dead_abovedot = 0xFE56 ;
public static final long XK_dead_diaeresis = 0xFE57 ;
public static final long XK_dead_abovering = 0xFE58 ;
public static final long XK_dead_doubleacute = 0xFE59 ;
public static final long XK_dead_caron = 0xFE5A ;
public static final long XK_dead_cedilla = 0xFE5B ;
public static final long XK_dead_ogonek = 0xFE5C ;
public static final long XK_dead_iota = 0xFE5D ;
public static final long XK_dead_voiced_sound = 0xFE5E ;
public static final long XK_dead_semivoiced_sound = 0xFE5F ;
public static final long XK_dead_belowdot = 0xFE60 ;
public static final long XK_First_Virtual_Screen = 0xFED0 ;
public static final long XK_Prev_Virtual_Screen = 0xFED1 ;
public static final long XK_Next_Virtual_Screen = 0xFED2 ;
public static final long XK_Last_Virtual_Screen = 0xFED4 ;
public static final long XK_Terminate_Server = 0xFED5 ;
public static final long XK_AccessX_Enable = 0xFE70 ;
public static final long XK_AccessX_Feedback_Enable = 0xFE71 ;
public static final long XK_RepeatKeys_Enable = 0xFE72 ;
public static final long XK_SlowKeys_Enable = 0xFE73 ;
public static final long XK_BounceKeys_Enable = 0xFE74 ;
public static final long XK_StickyKeys_Enable = 0xFE75 ;
public static final long XK_MouseKeys_Enable = 0xFE76 ;
public static final long XK_MouseKeys_Accel_Enable = 0xFE77 ;
public static final long XK_Overlay1_Enable = 0xFE78 ;
public static final long XK_Overlay2_Enable = 0xFE79 ;
public static final long XK_AudibleBell_Enable = 0xFE7A ;
public static final long XK_Pointer_Left = 0xFEE0 ;
public static final long XK_Pointer_Right = 0xFEE1 ;
public static final long XK_Pointer_Up = 0xFEE2 ;
public static final long XK_Pointer_Down = 0xFEE3 ;
public static final long XK_Pointer_UpLeft = 0xFEE4 ;
public static final long XK_Pointer_UpRight = 0xFEE5 ;
public static final long XK_Pointer_DownLeft = 0xFEE6 ;
public static final long XK_Pointer_DownRight = 0xFEE7 ;
public static final long XK_Pointer_Button_Dflt = 0xFEE8 ;
public static final long XK_Pointer_Button1 = 0xFEE9 ;
public static final long XK_Pointer_Button2 = 0xFEEA ;
public static final long XK_Pointer_Button3 = 0xFEEB ;
public static final long XK_Pointer_Button4 = 0xFEEC ;
public static final long XK_Pointer_Button5 = 0xFEED ;
public static final long XK_Pointer_DblClick_Dflt = 0xFEEE ;
public static final long XK_Pointer_DblClick1 = 0xFEEF ;
public static final long XK_Pointer_DblClick2 = 0xFEF0 ;
public static final long XK_Pointer_DblClick3 = 0xFEF1 ;
public static final long XK_Pointer_DblClick4 = 0xFEF2 ;
public static final long XK_Pointer_DblClick5 = 0xFEF3 ;
public static final long XK_Pointer_Drag_Dflt = 0xFEF4 ;
public static final long XK_Pointer_Drag1 = 0xFEF5 ;
public static final long XK_Pointer_Drag2 = 0xFEF6 ;
public static final long XK_Pointer_Drag3 = 0xFEF7 ;
public static final long XK_Pointer_Drag4 = 0xFEF8 ;
public static final long XK_Pointer_Drag5 = 0xFEFD ;
public static final long XK_Pointer_EnableKeys = 0xFEF9 ;
public static final long XK_Pointer_Accelerate = 0xFEFA ;
public static final long XK_Pointer_DfltBtnNext = 0xFEFB ;
public static final long XK_Pointer_DfltBtnPrev = 0xFEFC ;
/*
* 3270 Terminal Keys
* Byte 3 = 0xFD
*/
public static final long XK_3270_Duplicate = 0xFD01 ;
public static final long XK_3270_FieldMark = 0xFD02 ;
public static final long XK_3270_Right2 = 0xFD03 ;
public static final long XK_3270_Left2 = 0xFD04 ;
public static final long XK_3270_BackTab = 0xFD05 ;
public static final long XK_3270_EraseEOF = 0xFD06 ;
public static final long XK_3270_EraseInput = 0xFD07 ;
public static final long XK_3270_Reset = 0xFD08 ;
public static final long XK_3270_Quit = 0xFD09 ;
public static final long XK_3270_PA1 = 0xFD0A ;
public static final long XK_3270_PA2 = 0xFD0B ;
public static final long XK_3270_PA3 = 0xFD0C ;
public static final long XK_3270_Test = 0xFD0D ;
public static final long XK_3270_Attn = 0xFD0E ;
public static final long XK_3270_CursorBlink = 0xFD0F ;
public static final long XK_3270_AltCursor = 0xFD10 ;
public static final long XK_3270_KeyClick = 0xFD11 ;
public static final long XK_3270_Jump = 0xFD12 ;
public static final long XK_3270_Ident = 0xFD13 ;
public static final long XK_3270_Rule = 0xFD14 ;
public static final long XK_3270_Copy = 0xFD15 ;
public static final long XK_3270_Play = 0xFD16 ;
public static final long XK_3270_Setup = 0xFD17 ;
public static final long XK_3270_Record = 0xFD18 ;
public static final long XK_3270_ChangeScreen = 0xFD19 ;
public static final long XK_3270_DeleteWord = 0xFD1A ;
public static final long XK_3270_ExSelect = 0xFD1B ;
public static final long XK_3270_CursorSelect = 0xFD1C ;
public static final long XK_3270_PrintScreen = 0xFD1D ;
public static final long XK_3270_Enter = 0xFD1E ;
/*
* Latin 1
* Byte 3 = 0
*/
public static final long XK_space = 0x020 ;
public static final long XK_exclam = 0x021 ;
public static final long XK_quotedbl = 0x022 ;
public static final long XK_numbersign = 0x023 ;
public static final long XK_dollar = 0x024 ;
public static final long XK_percent = 0x025 ;
public static final long XK_ampersand = 0x026 ;
public static final long XK_apostrophe = 0x027 ;
public static final long XK_quoteright = 0x027 ; /* deprecated */
public static final long XK_parenleft = 0x028 ;
public static final long XK_parenright = 0x029 ;
public static final long XK_asterisk = 0x02a ;
public static final long XK_plus = 0x02b ;
public static final long XK_comma = 0x02c ;
public static final long XK_minus = 0x02d ;
public static final long XK_period = 0x02e ;
public static final long XK_slash = 0x02f ;
public static final long XK_0 = 0x030 ;
public static final long XK_1 = 0x031 ;
public static final long XK_2 = 0x032 ;
public static final long XK_3 = 0x033 ;
public static final long XK_4 = 0x034 ;
public static final long XK_5 = 0x035 ;
public static final long XK_6 = 0x036 ;
public static final long XK_7 = 0x037 ;
public static final long XK_8 = 0x038 ;
public static final long XK_9 = 0x039 ;
public static final long XK_colon = 0x03a ;
public static final long XK_semicolon = 0x03b ;
public static final long XK_less = 0x03c ;
public static final long XK_equal = 0x03d ;
public static final long XK_greater = 0x03e ;
public static final long XK_question = 0x03f ;
public static final long XK_at = 0x040 ;
public static final long XK_A = 0x041 ;
public static final long XK_B = 0x042 ;
public static final long XK_C = 0x043 ;
public static final long XK_D = 0x044 ;
public static final long XK_E = 0x045 ;
public static final long XK_F = 0x046 ;
public static final long XK_G = 0x047 ;
public static final long XK_H = 0x048 ;
public static final long XK_I = 0x049 ;
public static final long XK_J = 0x04a ;
public static final long XK_K = 0x04b ;
public static final long XK_L = 0x04c ;
public static final long XK_M = 0x04d ;
public static final long XK_N = 0x04e ;
public static final long XK_O = 0x04f ;
public static final long XK_P = 0x050 ;
public static final long XK_Q = 0x051 ;
public static final long XK_R = 0x052 ;
public static final long XK_S = 0x053 ;
public static final long XK_T = 0x054 ;
public static final long XK_U = 0x055 ;
public static final long XK_V = 0x056 ;
public static final long XK_W = 0x057 ;
public static final long XK_X = 0x058 ;
public static final long XK_Y = 0x059 ;
public static final long XK_Z = 0x05a ;
public static final long XK_bracketleft = 0x05b ;
public static final long XK_backslash = 0x05c ;
public static final long XK_bracketright = 0x05d ;
public static final long XK_asciicircum = 0x05e ;
public static final long XK_underscore = 0x05f ;
public static final long XK_grave = 0x060 ;
public static final long XK_quoteleft = 0x060 ; /* deprecated */
public static final long XK_a = 0x061 ;
public static final long XK_b = 0x062 ;
public static final long XK_c = 0x063 ;
public static final long XK_d = 0x064 ;
public static final long XK_e = 0x065 ;
public static final long XK_f = 0x066 ;
public static final long XK_g = 0x067 ;
public static final long XK_h = 0x068 ;
public static final long XK_i = 0x069 ;
public static final long XK_j = 0x06a ;
public static final long XK_k = 0x06b ;
public static final long XK_l = 0x06c ;
public static final long XK_m = 0x06d ;
public static final long XK_n = 0x06e ;
public static final long XK_o = 0x06f ;
public static final long XK_p = 0x070 ;
public static final long XK_q = 0x071 ;
public static final long XK_r = 0x072 ;
public static final long XK_s = 0x073 ;
public static final long XK_t = 0x074 ;
public static final long XK_u = 0x075 ;
public static final long XK_v = 0x076 ;
public static final long XK_w = 0x077 ;
public static final long XK_x = 0x078 ;
public static final long XK_y = 0x079 ;
public static final long XK_z = 0x07a ;
public static final long XK_braceleft = 0x07b ;
public static final long XK_bar = 0x07c ;
public static final long XK_braceright = 0x07d ;
public static final long XK_asciitilde = 0x07e ;
public static final long XK_nobreakspace = 0x0a0 ;
public static final long XK_exclamdown = 0x0a1 ;
public static final long XK_cent = 0x0a2 ;
public static final long XK_sterling = 0x0a3 ;
public static final long XK_currency = 0x0a4 ;
public static final long XK_yen = 0x0a5 ;
public static final long XK_brokenbar = 0x0a6 ;
public static final long XK_section = 0x0a7 ;
public static final long XK_diaeresis = 0x0a8 ;
public static final long XK_copyright = 0x0a9 ;
public static final long XK_ordfeminine = 0x0aa ;
public static final long XK_guillemotleft = 0x0ab ; /* left angle quotation mark */
public static final long XK_notsign = 0x0ac ;
public static final long XK_hyphen = 0x0ad ;
public static final long XK_registered = 0x0ae ;
public static final long XK_macron = 0x0af ;
public static final long XK_degree = 0x0b0 ;
public static final long XK_plusminus = 0x0b1 ;
public static final long XK_twosuperior = 0x0b2 ;
public static final long XK_threesuperior = 0x0b3 ;
public static final long XK_acute = 0x0b4 ;
public static final long XK_mu = 0x0b5 ;
public static final long XK_paragraph = 0x0b6 ;
public static final long XK_periodcentered = 0x0b7 ;
public static final long XK_cedilla = 0x0b8 ;
public static final long XK_onesuperior = 0x0b9 ;
public static final long XK_masculine = 0x0ba ;
public static final long XK_guillemotright = 0x0bb ; /* right angle quotation mark */
public static final long XK_onequarter = 0x0bc ;
public static final long XK_onehalf = 0x0bd ;
public static final long XK_threequarters = 0x0be ;
public static final long XK_questiondown = 0x0bf ;
public static final long XK_Agrave = 0x0c0 ;
public static final long XK_Aacute = 0x0c1 ;
public static final long XK_Acircumflex = 0x0c2 ;
public static final long XK_Atilde = 0x0c3 ;
public static final long XK_Adiaeresis = 0x0c4 ;
public static final long XK_Aring = 0x0c5 ;
public static final long XK_AE = 0x0c6 ;
public static final long XK_Ccedilla = 0x0c7 ;
public static final long XK_Egrave = 0x0c8 ;
public static final long XK_Eacute = 0x0c9 ;
public static final long XK_Ecircumflex = 0x0ca ;
public static final long XK_Ediaeresis = 0x0cb ;
public static final long XK_Igrave = 0x0cc ;
public static final long XK_Iacute = 0x0cd ;
public static final long XK_Icircumflex = 0x0ce ;
public static final long XK_Idiaeresis = 0x0cf ;
public static final long XK_ETH = 0x0d0 ;
public static final long XK_Eth = 0x0d0 ; /* deprecated */
public static final long XK_Ntilde = 0x0d1 ;
public static final long XK_Ograve = 0x0d2 ;
public static final long XK_Oacute = 0x0d3 ;
public static final long XK_Ocircumflex = 0x0d4 ;
public static final long XK_Otilde = 0x0d5 ;
public static final long XK_Odiaeresis = 0x0d6 ;
public static final long XK_multiply = 0x0d7 ;
public static final long XK_Ooblique = 0x0d8 ;
public static final long XK_Ugrave = 0x0d9 ;
public static final long XK_Uacute = 0x0da ;
public static final long XK_Ucircumflex = 0x0db ;
public static final long XK_Udiaeresis = 0x0dc ;
public static final long XK_Yacute = 0x0dd ;
public static final long XK_THORN = 0x0de ;
public static final long XK_Thorn = 0x0de ; /* deprecated */
public static final long XK_ssharp = 0x0df ;
public static final long XK_agrave = 0x0e0 ;
public static final long XK_aacute = 0x0e1 ;
public static final long XK_acircumflex = 0x0e2 ;
public static final long XK_atilde = 0x0e3 ;
public static final long XK_adiaeresis = 0x0e4 ;
public static final long XK_aring = 0x0e5 ;
public static final long XK_ae = 0x0e6 ;
public static final long XK_ccedilla = 0x0e7 ;
public static final long XK_egrave = 0x0e8 ;
public static final long XK_eacute = 0x0e9 ;
public static final long XK_ecircumflex = 0x0ea ;
public static final long XK_ediaeresis = 0x0eb ;
public static final long XK_igrave = 0x0ec ;
public static final long XK_iacute = 0x0ed ;
public static final long XK_icircumflex = 0x0ee ;
public static final long XK_idiaeresis = 0x0ef ;
public static final long XK_eth = 0x0f0 ;
public static final long XK_ntilde = 0x0f1 ;
public static final long XK_ograve = 0x0f2 ;
public static final long XK_oacute = 0x0f3 ;
public static final long XK_ocircumflex = 0x0f4 ;
public static final long XK_otilde = 0x0f5 ;
public static final long XK_odiaeresis = 0x0f6 ;
public static final long XK_division = 0x0f7 ;
public static final long XK_oslash = 0x0f8 ;
public static final long XK_ugrave = 0x0f9 ;
public static final long XK_uacute = 0x0fa ;
public static final long XK_ucircumflex = 0x0fb ;
public static final long XK_udiaeresis = 0x0fc ;
public static final long XK_yacute = 0x0fd ;
public static final long XK_thorn = 0x0fe ;
public static final long XK_ydiaeresis = 0x0ff ;
/*
* Latin 2
* Byte 3 = 1
*/
public static final long XK_Aogonek = 0x1a1 ;
public static final long XK_breve = 0x1a2 ;
public static final long XK_Lstroke = 0x1a3 ;
public static final long XK_Lcaron = 0x1a5 ;
public static final long XK_Sacute = 0x1a6 ;
public static final long XK_Scaron = 0x1a9 ;
public static final long XK_Scedilla = 0x1aa ;
public static final long XK_Tcaron = 0x1ab ;
public static final long XK_Zacute = 0x1ac ;
public static final long XK_Zcaron = 0x1ae ;
public static final long XK_Zabovedot = 0x1af ;
public static final long XK_aogonek = 0x1b1 ;
public static final long XK_ogonek = 0x1b2 ;
public static final long XK_lstroke = 0x1b3 ;
public static final long XK_lcaron = 0x1b5 ;
public static final long XK_sacute = 0x1b6 ;
public static final long XK_caron = 0x1b7 ;
public static final long XK_scaron = 0x1b9 ;
public static final long XK_scedilla = 0x1ba ;
public static final long XK_tcaron = 0x1bb ;
public static final long XK_zacute = 0x1bc ;
public static final long XK_doubleacute = 0x1bd ;
public static final long XK_zcaron = 0x1be ;
public static final long XK_zabovedot = 0x1bf ;
public static final long XK_Racute = 0x1c0 ;
public static final long XK_Abreve = 0x1c3 ;
public static final long XK_Lacute = 0x1c5 ;
public static final long XK_Cacute = 0x1c6 ;
public static final long XK_Ccaron = 0x1c8 ;
public static final long XK_Eogonek = 0x1ca ;
public static final long XK_Ecaron = 0x1cc ;
public static final long XK_Dcaron = 0x1cf ;
public static final long XK_Dstroke = 0x1d0 ;
public static final long XK_Nacute = 0x1d1 ;
public static final long XK_Ncaron = 0x1d2 ;
public static final long XK_Odoubleacute = 0x1d5 ;
public static final long XK_Rcaron = 0x1d8 ;
public static final long XK_Uring = 0x1d9 ;
public static final long XK_Udoubleacute = 0x1db ;
public static final long XK_Tcedilla = 0x1de ;
public static final long XK_racute = 0x1e0 ;
public static final long XK_abreve = 0x1e3 ;
public static final long XK_lacute = 0x1e5 ;
public static final long XK_cacute = 0x1e6 ;
public static final long XK_ccaron = 0x1e8 ;
public static final long XK_eogonek = 0x1ea ;
public static final long XK_ecaron = 0x1ec ;
public static final long XK_dcaron = 0x1ef ;
public static final long XK_dstroke = 0x1f0 ;
public static final long XK_nacute = 0x1f1 ;
public static final long XK_ncaron = 0x1f2 ;
public static final long XK_odoubleacute = 0x1f5 ;
public static final long XK_udoubleacute = 0x1fb ;
public static final long XK_rcaron = 0x1f8 ;
public static final long XK_uring = 0x1f9 ;
public static final long XK_tcedilla = 0x1fe ;
public static final long XK_abovedot = 0x1ff ;
/*
* Latin 3
* Byte 3 = 2
*/
public static final long XK_Hstroke = 0x2a1 ;
public static final long XK_Hcircumflex = 0x2a6 ;
public static final long XK_Iabovedot = 0x2a9 ;
public static final long XK_Gbreve = 0x2ab ;
public static final long XK_Jcircumflex = 0x2ac ;
public static final long XK_hstroke = 0x2b1 ;
public static final long XK_hcircumflex = 0x2b6 ;
public static final long XK_idotless = 0x2b9 ;
public static final long XK_gbreve = 0x2bb ;
public static final long XK_jcircumflex = 0x2bc ;
public static final long XK_Cabovedot = 0x2c5 ;
public static final long XK_Ccircumflex = 0x2c6 ;
public static final long XK_Gabovedot = 0x2d5 ;
public static final long XK_Gcircumflex = 0x2d8 ;
public static final long XK_Ubreve = 0x2dd ;
public static final long XK_Scircumflex = 0x2de ;
public static final long XK_cabovedot = 0x2e5 ;
public static final long XK_ccircumflex = 0x2e6 ;
public static final long XK_gabovedot = 0x2f5 ;
public static final long XK_gcircumflex = 0x2f8 ;
public static final long XK_ubreve = 0x2fd ;
public static final long XK_scircumflex = 0x2fe ;
/*
* Latin 4
* Byte 3 = 3
*/
public static final long XK_kra = 0x3a2 ;
public static final long XK_kappa = 0x3a2 ; /* deprecated */
public static final long XK_Rcedilla = 0x3a3 ;
public static final long XK_Itilde = 0x3a5 ;
public static final long XK_Lcedilla = 0x3a6 ;
public static final long XK_Emacron = 0x3aa ;
public static final long XK_Gcedilla = 0x3ab ;
public static final long XK_Tslash = 0x3ac ;
public static final long XK_rcedilla = 0x3b3 ;
public static final long XK_itilde = 0x3b5 ;
public static final long XK_lcedilla = 0x3b6 ;
public static final long XK_emacron = 0x3ba ;
public static final long XK_gcedilla = 0x3bb ;
public static final long XK_tslash = 0x3bc ;
public static final long XK_ENG = 0x3bd ;
public static final long XK_eng = 0x3bf ;
public static final long XK_Amacron = 0x3c0 ;
public static final long XK_Iogonek = 0x3c7 ;
public static final long XK_Eabovedot = 0x3cc ;
public static final long XK_Imacron = 0x3cf ;
public static final long XK_Ncedilla = 0x3d1 ;
public static final long XK_Omacron = 0x3d2 ;
public static final long XK_Kcedilla = 0x3d3 ;
public static final long XK_Uogonek = 0x3d9 ;
public static final long XK_Utilde = 0x3dd ;
public static final long XK_Umacron = 0x3de ;
public static final long XK_amacron = 0x3e0 ;
public static final long XK_iogonek = 0x3e7 ;
public static final long XK_eabovedot = 0x3ec ;
public static final long XK_imacron = 0x3ef ;
public static final long XK_ncedilla = 0x3f1 ;
public static final long XK_omacron = 0x3f2 ;
public static final long XK_kcedilla = 0x3f3 ;
public static final long XK_uogonek = 0x3f9 ;
public static final long XK_utilde = 0x3fd ;
public static final long XK_umacron = 0x3fe ;
/*
* Latin-9 (a.k.a. Latin-0)
* Byte 3 = 19
*/
public static final long XK_OE = 0x13bc ;
public static final long XK_oe = 0x13bd ;
public static final long XK_Ydiaeresis = 0x13be ;
/*
* Katakana
* Byte 3 = 4
*/
public static final long XK_overline = 0x47e ;
public static final long XK_kana_fullstop = 0x4a1 ;
public static final long XK_kana_openingbracket = 0x4a2 ;
public static final long XK_kana_closingbracket = 0x4a3 ;
public static final long XK_kana_comma = 0x4a4 ;
public static final long XK_kana_conjunctive = 0x4a5 ;
public static final long XK_kana_middledot = 0x4a5 ; /* deprecated */
public static final long XK_kana_WO = 0x4a6 ;
public static final long XK_kana_a = 0x4a7 ;
public static final long XK_kana_i = 0x4a8 ;
public static final long XK_kana_u = 0x4a9 ;
public static final long XK_kana_e = 0x4aa ;
public static final long XK_kana_o = 0x4ab ;
public static final long XK_kana_ya = 0x4ac ;
public static final long XK_kana_yu = 0x4ad ;
public static final long XK_kana_yo = 0x4ae ;
public static final long XK_kana_tsu = 0x4af ;
public static final long XK_kana_tu = 0x4af ; /* deprecated */
public static final long XK_prolongedsound = 0x4b0 ;
public static final long XK_kana_A = 0x4b1 ;
public static final long XK_kana_I = 0x4b2 ;
public static final long XK_kana_U = 0x4b3 ;
public static final long XK_kana_E = 0x4b4 ;
public static final long XK_kana_O = 0x4b5 ;
public static final long XK_kana_KA = 0x4b6 ;
public static final long XK_kana_KI = 0x4b7 ;
public static final long XK_kana_KU = 0x4b8 ;
public static final long XK_kana_KE = 0x4b9 ;
public static final long XK_kana_KO = 0x4ba ;
public static final long XK_kana_SA = 0x4bb ;
public static final long XK_kana_SHI = 0x4bc ;
public static final long XK_kana_SU = 0x4bd ;
public static final long XK_kana_SE = 0x4be ;
public static final long XK_kana_SO = 0x4bf ;
public static final long XK_kana_TA = 0x4c0 ;
public static final long XK_kana_CHI = 0x4c1 ;
public static final long XK_kana_TI = 0x4c1 ; /* deprecated */
public static final long XK_kana_TSU = 0x4c2 ;
public static final long XK_kana_TU = 0x4c2 ; /* deprecated */
public static final long XK_kana_TE = 0x4c3 ;
public static final long XK_kana_TO = 0x4c4 ;
public static final long XK_kana_NA = 0x4c5 ;
public static final long XK_kana_NI = 0x4c6 ;
public static final long XK_kana_NU = 0x4c7 ;
public static final long XK_kana_NE = 0x4c8 ;
public static final long XK_kana_NO = 0x4c9 ;
public static final long XK_kana_HA = 0x4ca ;
public static final long XK_kana_HI = 0x4cb ;
public static final long XK_kana_FU = 0x4cc ;
public static final long XK_kana_HU = 0x4cc ; /* deprecated */
public static final long XK_kana_HE = 0x4cd ;
public static final long XK_kana_HO = 0x4ce ;
public static final long XK_kana_MA = 0x4cf ;
public static final long XK_kana_MI = 0x4d0 ;
public static final long XK_kana_MU = 0x4d1 ;
public static final long XK_kana_ME = 0x4d2 ;
public static final long XK_kana_MO = 0x4d3 ;
public static final long XK_kana_YA = 0x4d4 ;
public static final long XK_kana_YU = 0x4d5 ;
public static final long XK_kana_YO = 0x4d6 ;
public static final long XK_kana_RA = 0x4d7 ;
public static final long XK_kana_RI = 0x4d8 ;
public static final long XK_kana_RU = 0x4d9 ;
public static final long XK_kana_RE = 0x4da ;
public static final long XK_kana_RO = 0x4db ;
public static final long XK_kana_WA = 0x4dc ;
public static final long XK_kana_N = 0x4dd ;
public static final long XK_voicedsound = 0x4de ;
public static final long XK_semivoicedsound = 0x4df ;
public static final long XK_kana_switch = 0xFF7E ; /* Alias for mode_switch */
/*
* Arabic
* Byte 3 = 5
*/
public static final long XK_Arabic_comma = 0x5ac ;
public static final long XK_Arabic_semicolon = 0x5bb ;
public static final long XK_Arabic_question_mark = 0x5bf ;
public static final long XK_Arabic_hamza = 0x5c1 ;
public static final long XK_Arabic_maddaonalef = 0x5c2 ;
public static final long XK_Arabic_hamzaonalef = 0x5c3 ;
public static final long XK_Arabic_hamzaonwaw = 0x5c4 ;
public static final long XK_Arabic_hamzaunderalef = 0x5c5 ;
public static final long XK_Arabic_hamzaonyeh = 0x5c6 ;
public static final long XK_Arabic_alef = 0x5c7 ;
public static final long XK_Arabic_beh = 0x5c8 ;
public static final long XK_Arabic_tehmarbuta = 0x5c9 ;
public static final long XK_Arabic_teh = 0x5ca ;
public static final long XK_Arabic_theh = 0x5cb ;
public static final long XK_Arabic_jeem = 0x5cc ;
public static final long XK_Arabic_hah = 0x5cd ;
public static final long XK_Arabic_khah = 0x5ce ;
public static final long XK_Arabic_dal = 0x5cf ;
public static final long XK_Arabic_thal = 0x5d0 ;
public static final long XK_Arabic_ra = 0x5d1 ;
public static final long XK_Arabic_zain = 0x5d2 ;
public static final long XK_Arabic_seen = 0x5d3 ;
public static final long XK_Arabic_sheen = 0x5d4 ;
public static final long XK_Arabic_sad = 0x5d5 ;
public static final long XK_Arabic_dad = 0x5d6 ;
public static final long XK_Arabic_tah = 0x5d7 ;
public static final long XK_Arabic_zah = 0x5d8 ;
public static final long XK_Arabic_ain = 0x5d9 ;
public static final long XK_Arabic_ghain = 0x5da ;
public static final long XK_Arabic_tatweel = 0x5e0 ;
public static final long XK_Arabic_feh = 0x5e1 ;
public static final long XK_Arabic_qaf = 0x5e2 ;
public static final long XK_Arabic_kaf = 0x5e3 ;
public static final long XK_Arabic_lam = 0x5e4 ;
public static final long XK_Arabic_meem = 0x5e5 ;
public static final long XK_Arabic_noon = 0x5e6 ;
public static final long XK_Arabic_ha = 0x5e7 ;
public static final long XK_Arabic_heh = 0x5e7 ; /* deprecated */
public static final long XK_Arabic_waw = 0x5e8 ;
public static final long XK_Arabic_alefmaksura = 0x5e9 ;
public static final long XK_Arabic_yeh = 0x5ea ;
public static final long XK_Arabic_fathatan = 0x5eb ;
public static final long XK_Arabic_dammatan = 0x5ec ;
public static final long XK_Arabic_kasratan = 0x5ed ;
public static final long XK_Arabic_fatha = 0x5ee ;
public static final long XK_Arabic_damma = 0x5ef ;
public static final long XK_Arabic_kasra = 0x5f0 ;
public static final long XK_Arabic_shadda = 0x5f1 ;
public static final long XK_Arabic_sukun = 0x5f2 ;
public static final long XK_Arabic_switch = 0xFF7E ; /* Alias for mode_switch */
/*
* Cyrillic
* Byte 3 = 6
*/
public static final long XK_Serbian_dje = 0x6a1 ;
public static final long XK_Macedonia_gje = 0x6a2 ;
public static final long XK_Cyrillic_io = 0x6a3 ;
public static final long XK_Ukrainian_ie = 0x6a4 ;
public static final long XK_Ukranian_je = 0x6a4 ; /* deprecated */
public static final long XK_Macedonia_dse = 0x6a5 ;
public static final long XK_Ukrainian_i = 0x6a6 ;
public static final long XK_Ukranian_i = 0x6a6 ; /* deprecated */
public static final long XK_Ukrainian_yi = 0x6a7 ;
public static final long XK_Ukranian_yi = 0x6a7 ; /* deprecated */
public static final long XK_Cyrillic_je = 0x6a8 ;
public static final long XK_Serbian_je = 0x6a8 ; /* deprecated */
public static final long XK_Cyrillic_lje = 0x6a9 ;
public static final long XK_Serbian_lje = 0x6a9 ; /* deprecated */
public static final long XK_Cyrillic_nje = 0x6aa ;
public static final long XK_Serbian_nje = 0x6aa ; /* deprecated */
public static final long XK_Serbian_tshe = 0x6ab ;
public static final long XK_Macedonia_kje = 0x6ac ;
public static final long XK_Byelorussian_shortu = 0x6ae ;
public static final long XK_Cyrillic_dzhe = 0x6af ;
public static final long XK_Serbian_dze = 0x6af ; /* deprecated */
public static final long XK_numerosign = 0x6b0 ;
public static final long XK_Serbian_DJE = 0x6b1 ;
public static final long XK_Macedonia_GJE = 0x6b2 ;
public static final long XK_Cyrillic_IO = 0x6b3 ;
public static final long XK_Ukrainian_IE = 0x6b4 ;
public static final long XK_Ukranian_JE = 0x6b4 ; /* deprecated */
public static final long XK_Macedonia_DSE = 0x6b5 ;
public static final long XK_Ukrainian_I = 0x6b6 ;
public static final long XK_Ukranian_I = 0x6b6 ; /* deprecated */
public static final long XK_Ukrainian_YI = 0x6b7 ;
public static final long XK_Ukranian_YI = 0x6b7 ; /* deprecated */
public static final long XK_Cyrillic_JE = 0x6b8 ;
public static final long XK_Serbian_JE = 0x6b8 ; /* deprecated */
public static final long XK_Cyrillic_LJE = 0x6b9 ;
public static final long XK_Serbian_LJE = 0x6b9 ; /* deprecated */
public static final long XK_Cyrillic_NJE = 0x6ba ;
public static final long XK_Serbian_NJE = 0x6ba ; /* deprecated */
public static final long XK_Serbian_TSHE = 0x6bb ;
public static final long XK_Macedonia_KJE = 0x6bc ;
public static final long XK_Byelorussian_SHORTU = 0x6be ;
public static final long XK_Cyrillic_DZHE = 0x6bf ;
public static final long XK_Serbian_DZE = 0x6bf ; /* deprecated */
public static final long XK_Cyrillic_yu = 0x6c0 ;
public static final long XK_Cyrillic_a = 0x6c1 ;
public static final long XK_Cyrillic_be = 0x6c2 ;
public static final long XK_Cyrillic_tse = 0x6c3 ;
public static final long XK_Cyrillic_de = 0x6c4 ;
public static final long XK_Cyrillic_ie = 0x6c5 ;
public static final long XK_Cyrillic_ef = 0x6c6 ;
public static final long XK_Cyrillic_ghe = 0x6c7 ;
public static final long XK_Cyrillic_ha = 0x6c8 ;
public static final long XK_Cyrillic_i = 0x6c9 ;
public static final long XK_Cyrillic_shorti = 0x6ca ;
public static final long XK_Cyrillic_ka = 0x6cb ;
public static final long XK_Cyrillic_el = 0x6cc ;
public static final long XK_Cyrillic_em = 0x6cd ;
public static final long XK_Cyrillic_en = 0x6ce ;
public static final long XK_Cyrillic_o = 0x6cf ;
public static final long XK_Cyrillic_pe = 0x6d0 ;
public static final long XK_Cyrillic_ya = 0x6d1 ;
public static final long XK_Cyrillic_er = 0x6d2 ;
public static final long XK_Cyrillic_es = 0x6d3 ;
public static final long XK_Cyrillic_te = 0x6d4 ;
public static final long XK_Cyrillic_u = 0x6d5 ;
public static final long XK_Cyrillic_zhe = 0x6d6 ;
public static final long XK_Cyrillic_ve = 0x6d7 ;
public static final long XK_Cyrillic_softsign = 0x6d8 ;
public static final long XK_Cyrillic_yeru = 0x6d9 ;
public static final long XK_Cyrillic_ze = 0x6da ;
public static final long XK_Cyrillic_sha = 0x6db ;
public static final long XK_Cyrillic_e = 0x6dc ;
public static final long XK_Cyrillic_shcha = 0x6dd ;
public static final long XK_Cyrillic_che = 0x6de ;
public static final long XK_Cyrillic_hardsign = 0x6df ;
public static final long XK_Cyrillic_YU = 0x6e0 ;
public static final long XK_Cyrillic_A = 0x6e1 ;
public static final long XK_Cyrillic_BE = 0x6e2 ;
public static final long XK_Cyrillic_TSE = 0x6e3 ;
public static final long XK_Cyrillic_DE = 0x6e4 ;
public static final long XK_Cyrillic_IE = 0x6e5 ;
public static final long XK_Cyrillic_EF = 0x6e6 ;
public static final long XK_Cyrillic_GHE = 0x6e7 ;
public static final long XK_Cyrillic_HA = 0x6e8 ;
public static final long XK_Cyrillic_I = 0x6e9 ;
public static final long XK_Cyrillic_SHORTI = 0x6ea ;
public static final long XK_Cyrillic_KA = 0x6eb ;
public static final long XK_Cyrillic_EL = 0x6ec ;
public static final long XK_Cyrillic_EM = 0x6ed ;
public static final long XK_Cyrillic_EN = 0x6ee ;
public static final long XK_Cyrillic_O = 0x6ef ;
public static final long XK_Cyrillic_PE = 0x6f0 ;
public static final long XK_Cyrillic_YA = 0x6f1 ;
public static final long XK_Cyrillic_ER = 0x6f2 ;
public static final long XK_Cyrillic_ES = 0x6f3 ;
public static final long XK_Cyrillic_TE = 0x6f4 ;
public static final long XK_Cyrillic_U = 0x6f5 ;
public static final long XK_Cyrillic_ZHE = 0x6f6 ;
public static final long XK_Cyrillic_VE = 0x6f7 ;
public static final long XK_Cyrillic_SOFTSIGN = 0x6f8 ;
public static final long XK_Cyrillic_YERU = 0x6f9 ;
public static final long XK_Cyrillic_ZE = 0x6fa ;
public static final long XK_Cyrillic_SHA = 0x6fb ;
public static final long XK_Cyrillic_E = 0x6fc ;
public static final long XK_Cyrillic_SHCHA = 0x6fd ;
public static final long XK_Cyrillic_CHE = 0x6fe ;
public static final long XK_Cyrillic_HARDSIGN = 0x6ff ;
/*
* Greek
* Byte 3 = 7
*/
public static final long XK_Greek_ALPHAaccent = 0x7a1 ;
public static final long XK_Greek_EPSILONaccent = 0x7a2 ;
public static final long XK_Greek_ETAaccent = 0x7a3 ;
public static final long XK_Greek_IOTAaccent = 0x7a4 ;
public static final long XK_Greek_IOTAdiaeresis = 0x7a5 ;
public static final long XK_Greek_OMICRONaccent = 0x7a7 ;
public static final long XK_Greek_UPSILONaccent = 0x7a8 ;
public static final long XK_Greek_UPSILONdieresis = 0x7a9 ;
public static final long XK_Greek_OMEGAaccent = 0x7ab ;
public static final long XK_Greek_accentdieresis = 0x7ae ;
public static final long XK_Greek_horizbar = 0x7af ;
public static final long XK_Greek_alphaaccent = 0x7b1 ;
public static final long XK_Greek_epsilonaccent = 0x7b2 ;
public static final long XK_Greek_etaaccent = 0x7b3 ;
public static final long XK_Greek_iotaaccent = 0x7b4 ;
public static final long XK_Greek_iotadieresis = 0x7b5 ;
public static final long XK_Greek_iotaaccentdieresis = 0x7b6 ;
public static final long XK_Greek_omicronaccent = 0x7b7 ;
public static final long XK_Greek_upsilonaccent = 0x7b8 ;
public static final long XK_Greek_upsilondieresis = 0x7b9 ;
public static final long XK_Greek_upsilonaccentdieresis = 0x7ba ;
public static final long XK_Greek_omegaaccent = 0x7bb ;
public static final long XK_Greek_ALPHA = 0x7c1 ;
public static final long XK_Greek_BETA = 0x7c2 ;
public static final long XK_Greek_GAMMA = 0x7c3 ;
public static final long XK_Greek_DELTA = 0x7c4 ;
public static final long XK_Greek_EPSILON = 0x7c5 ;
public static final long XK_Greek_ZETA = 0x7c6 ;
public static final long XK_Greek_ETA = 0x7c7 ;
public static final long XK_Greek_THETA = 0x7c8 ;
public static final long XK_Greek_IOTA = 0x7c9 ;
public static final long XK_Greek_KAPPA = 0x7ca ;
public static final long XK_Greek_LAMDA = 0x7cb ;
public static final long XK_Greek_LAMBDA = 0x7cb ;
public static final long XK_Greek_MU = 0x7cc ;
public static final long XK_Greek_NU = 0x7cd ;
public static final long XK_Greek_XI = 0x7ce ;
public static final long XK_Greek_OMICRON = 0x7cf ;
public static final long XK_Greek_PI = 0x7d0 ;
public static final long XK_Greek_RHO = 0x7d1 ;
public static final long XK_Greek_SIGMA = 0x7d2 ;
public static final long XK_Greek_TAU = 0x7d4 ;
public static final long XK_Greek_UPSILON = 0x7d5 ;
public static final long XK_Greek_PHI = 0x7d6 ;
public static final long XK_Greek_CHI = 0x7d7 ;
public static final long XK_Greek_PSI = 0x7d8 ;
public static final long XK_Greek_OMEGA = 0x7d9 ;
public static final long XK_Greek_alpha = 0x7e1 ;
public static final long XK_Greek_beta = 0x7e2 ;
public static final long XK_Greek_gamma = 0x7e3 ;
public static final long XK_Greek_delta = 0x7e4 ;
public static final long XK_Greek_epsilon = 0x7e5 ;
public static final long XK_Greek_zeta = 0x7e6 ;
public static final long XK_Greek_eta = 0x7e7 ;
public static final long XK_Greek_theta = 0x7e8 ;
public static final long XK_Greek_iota = 0x7e9 ;
public static final long XK_Greek_kappa = 0x7ea ;
public static final long XK_Greek_lamda = 0x7eb ;
public static final long XK_Greek_lambda = 0x7eb ;
public static final long XK_Greek_mu = 0x7ec ;
public static final long XK_Greek_nu = 0x7ed ;
public static final long XK_Greek_xi = 0x7ee ;
public static final long XK_Greek_omicron = 0x7ef ;
public static final long XK_Greek_pi = 0x7f0 ;
public static final long XK_Greek_rho = 0x7f1 ;
public static final long XK_Greek_sigma = 0x7f2 ;
public static final long XK_Greek_finalsmallsigma = 0x7f3 ;
public static final long XK_Greek_tau = 0x7f4 ;
public static final long XK_Greek_upsilon = 0x7f5 ;
public static final long XK_Greek_phi = 0x7f6 ;
public static final long XK_Greek_chi = 0x7f7 ;
public static final long XK_Greek_psi = 0x7f8 ;
public static final long XK_Greek_omega = 0x7f9 ;
public static final long XK_Greek_switch = 0xFF7E ; /* Alias for mode_switch */
/*
* Technical
* Byte 3 = 8
*/
public static final long XK_leftradical = 0x8a1 ;
public static final long XK_topleftradical = 0x8a2 ;
public static final long XK_horizconnector = 0x8a3 ;
public static final long XK_topintegral = 0x8a4 ;
public static final long XK_botintegral = 0x8a5 ;
public static final long XK_vertconnector = 0x8a6 ;
public static final long XK_topleftsqbracket = 0x8a7 ;
public static final long XK_botleftsqbracket = 0x8a8 ;
public static final long XK_toprightsqbracket = 0x8a9 ;
public static final long XK_botrightsqbracket = 0x8aa ;
public static final long XK_topleftparens = 0x8ab ;
public static final long XK_botleftparens = 0x8ac ;
public static final long XK_toprightparens = 0x8ad ;
public static final long XK_botrightparens = 0x8ae ;
public static final long XK_leftmiddlecurlybrace = 0x8af ;
public static final long XK_rightmiddlecurlybrace = 0x8b0 ;
public static final long XK_topleftsummation = 0x8b1 ;
public static final long XK_botleftsummation = 0x8b2 ;
public static final long XK_topvertsummationconnector = 0x8b3 ;
public static final long XK_botvertsummationconnector = 0x8b4 ;
public static final long XK_toprightsummation = 0x8b5 ;
public static final long XK_botrightsummation = 0x8b6 ;
public static final long XK_rightmiddlesummation = 0x8b7 ;
public static final long XK_lessthanequal = 0x8bc ;
public static final long XK_notequal = 0x8bd ;
public static final long XK_greaterthanequal = 0x8be ;
public static final long XK_integral = 0x8bf ;
public static final long XK_therefore = 0x8c0 ;
public static final long XK_variation = 0x8c1 ;
public static final long XK_infinity = 0x8c2 ;
public static final long XK_nabla = 0x8c5 ;
public static final long XK_approximate = 0x8c8 ;
public static final long XK_similarequal = 0x8c9 ;
public static final long XK_ifonlyif = 0x8cd ;
public static final long XK_implies = 0x8ce ;
public static final long XK_identical = 0x8cf ;
public static final long XK_radical = 0x8d6 ;
public static final long XK_includedin = 0x8da ;
public static final long XK_includes = 0x8db ;
public static final long XK_intersection = 0x8dc ;
public static final long XK_union = 0x8dd ;
public static final long XK_logicaland = 0x8de ;
public static final long XK_logicalor = 0x8df ;
public static final long XK_partialderivative = 0x8ef ;
public static final long XK_function = 0x8f6 ;
public static final long XK_leftarrow = 0x8fb ;
public static final long XK_uparrow = 0x8fc ;
public static final long XK_rightarrow = 0x8fd ;
public static final long XK_downarrow = 0x8fe ;
/*
* Special
* Byte 3 = 9
*/
public static final long XK_blank = 0x9df ;
public static final long XK_soliddiamond = 0x9e0 ;
public static final long XK_checkerboard = 0x9e1 ;
public static final long XK_ht = 0x9e2 ;
public static final long XK_ff = 0x9e3 ;
public static final long XK_cr = 0x9e4 ;
public static final long XK_lf = 0x9e5 ;
public static final long XK_nl = 0x9e8 ;
public static final long XK_vt = 0x9e9 ;
public static final long XK_lowrightcorner = 0x9ea ;
public static final long XK_uprightcorner = 0x9eb ;
public static final long XK_upleftcorner = 0x9ec ;
public static final long XK_lowleftcorner = 0x9ed ;
public static final long XK_crossinglines = 0x9ee ;
public static final long XK_horizlinescan1 = 0x9ef ;
public static final long XK_horizlinescan3 = 0x9f0 ;
public static final long XK_horizlinescan5 = 0x9f1 ;
public static final long XK_horizlinescan7 = 0x9f2 ;
public static final long XK_horizlinescan9 = 0x9f3 ;
public static final long XK_leftt = 0x9f4 ;
public static final long XK_rightt = 0x9f5 ;
public static final long XK_bott = 0x9f6 ;
public static final long XK_topt = 0x9f7 ;
public static final long XK_vertbar = 0x9f8 ;
/*
* Publishing
* Byte 3 = a
*/
public static final long XK_emspace = 0xaa1 ;
public static final long XK_enspace = 0xaa2 ;
public static final long XK_em3space = 0xaa3 ;
public static final long XK_em4space = 0xaa4 ;
public static final long XK_digitspace = 0xaa5 ;
public static final long XK_punctspace = 0xaa6 ;
public static final long XK_thinspace = 0xaa7 ;
public static final long XK_hairspace = 0xaa8 ;
public static final long XK_emdash = 0xaa9 ;
public static final long XK_endash = 0xaaa ;
public static final long XK_signifblank = 0xaac ;
public static final long XK_ellipsis = 0xaae ;
public static final long XK_doubbaselinedot = 0xaaf ;
public static final long XK_onethird = 0xab0 ;
public static final long XK_twothirds = 0xab1 ;
public static final long XK_onefifth = 0xab2 ;
public static final long XK_twofifths = 0xab3 ;
public static final long XK_threefifths = 0xab4 ;
public static final long XK_fourfifths = 0xab5 ;
public static final long XK_onesixth = 0xab6 ;
public static final long XK_fivesixths = 0xab7 ;
public static final long XK_careof = 0xab8 ;
public static final long XK_figdash = 0xabb ;
public static final long XK_leftanglebracket = 0xabc ;
public static final long XK_decimalpoint = 0xabd ;
public static final long XK_rightanglebracket = 0xabe ;
public static final long XK_marker = 0xabf ;
public static final long XK_oneeighth = 0xac3 ;
public static final long XK_threeeighths = 0xac4 ;
public static final long XK_fiveeighths = 0xac5 ;
public static final long XK_seveneighths = 0xac6 ;
public static final long XK_trademark = 0xac9 ;
public static final long XK_signaturemark = 0xaca ;
public static final long XK_trademarkincircle = 0xacb ;
public static final long XK_leftopentriangle = 0xacc ;
public static final long XK_rightopentriangle = 0xacd ;
public static final long XK_emopencircle = 0xace ;
public static final long XK_emopenrectangle = 0xacf ;
public static final long XK_leftsinglequotemark = 0xad0 ;
public static final long XK_rightsinglequotemark = 0xad1 ;
public static final long XK_leftdoublequotemark = 0xad2 ;
public static final long XK_rightdoublequotemark = 0xad3 ;
public static final long XK_prescription = 0xad4 ;
public static final long XK_minutes = 0xad6 ;
public static final long XK_seconds = 0xad7 ;
public static final long XK_latincross = 0xad9 ;
public static final long XK_hexagram = 0xada ;
public static final long XK_filledrectbullet = 0xadb ;
public static final long XK_filledlefttribullet = 0xadc ;
public static final long XK_filledrighttribullet = 0xadd ;
public static final long XK_emfilledcircle = 0xade ;
public static final long XK_emfilledrect = 0xadf ;
public static final long XK_enopencircbullet = 0xae0 ;
public static final long XK_enopensquarebullet = 0xae1 ;
public static final long XK_openrectbullet = 0xae2 ;
public static final long XK_opentribulletup = 0xae3 ;
public static final long XK_opentribulletdown = 0xae4 ;
public static final long XK_openstar = 0xae5 ;
public static final long XK_enfilledcircbullet = 0xae6 ;
public static final long XK_enfilledsqbullet = 0xae7 ;
public static final long XK_filledtribulletup = 0xae8 ;
public static final long XK_filledtribulletdown = 0xae9 ;
public static final long XK_leftpointer = 0xaea ;
public static final long XK_rightpointer = 0xaeb ;
public static final long XK_club = 0xaec ;
public static final long XK_diamond = 0xaed ;
public static final long XK_heart = 0xaee ;
public static final long XK_maltesecross = 0xaf0 ;
public static final long XK_dagger = 0xaf1 ;
public static final long XK_doubledagger = 0xaf2 ;
public static final long XK_checkmark = 0xaf3 ;
public static final long XK_ballotcross = 0xaf4 ;
public static final long XK_musicalsharp = 0xaf5 ;
public static final long XK_musicalflat = 0xaf6 ;
public static final long XK_malesymbol = 0xaf7 ;
public static final long XK_femalesymbol = 0xaf8 ;
public static final long XK_telephone = 0xaf9 ;
public static final long XK_telephonerecorder = 0xafa ;
public static final long XK_phonographcopyright = 0xafb ;
public static final long XK_caret = 0xafc ;
public static final long XK_singlelowquotemark = 0xafd ;
public static final long XK_doublelowquotemark = 0xafe ;
public static final long XK_cursor = 0xaff ;
/*
* APL
* Byte 3 = b
*/
public static final long XK_leftcaret = 0xba3 ;
public static final long XK_rightcaret = 0xba6 ;
public static final long XK_downcaret = 0xba8 ;
public static final long XK_upcaret = 0xba9 ;
public static final long XK_overbar = 0xbc0 ;
public static final long XK_downtack = 0xbc2 ;
public static final long XK_upshoe = 0xbc3 ;
public static final long XK_downstile = 0xbc4 ;
public static final long XK_underbar = 0xbc6 ;
public static final long XK_jot = 0xbca ;
public static final long XK_quad = 0xbcc ;
public static final long XK_uptack = 0xbce ;
public static final long XK_circle = 0xbcf ;
public static final long XK_upstile = 0xbd3 ;
public static final long XK_downshoe = 0xbd6 ;
public static final long XK_rightshoe = 0xbd8 ;
public static final long XK_leftshoe = 0xbda ;
public static final long XK_lefttack = 0xbdc ;
public static final long XK_righttack = 0xbfc ;
/*
* Hebrew
* Byte 3 = c
*/
public static final long XK_hebrew_doublelowline = 0xcdf ;
public static final long XK_hebrew_aleph = 0xce0 ;
public static final long XK_hebrew_bet = 0xce1 ;
public static final long XK_hebrew_beth = 0xce1 ; /* deprecated */
public static final long XK_hebrew_gimel = 0xce2 ;
public static final long XK_hebrew_gimmel = 0xce2 ; /* deprecated */
public static final long XK_hebrew_dalet = 0xce3 ;
public static final long XK_hebrew_daleth = 0xce3 ; /* deprecated */
public static final long XK_hebrew_he = 0xce4 ;
public static final long XK_hebrew_waw = 0xce5 ;
public static final long XK_hebrew_zain = 0xce6 ;
public static final long XK_hebrew_zayin = 0xce6 ; /* deprecated */
public static final long XK_hebrew_chet = 0xce7 ;
public static final long XK_hebrew_het = 0xce7 ; /* deprecated */
public static final long XK_hebrew_tet = 0xce8 ;
public static final long XK_hebrew_teth = 0xce8 ; /* deprecated */
public static final long XK_hebrew_yod = 0xce9 ;
public static final long XK_hebrew_finalkaph = 0xcea ;
public static final long XK_hebrew_kaph = 0xceb ;
public static final long XK_hebrew_lamed = 0xcec ;
public static final long XK_hebrew_finalmem = 0xced ;
public static final long XK_hebrew_mem = 0xcee ;
public static final long XK_hebrew_finalnun = 0xcef ;
public static final long XK_hebrew_nun = 0xcf0 ;
public static final long XK_hebrew_samech = 0xcf1 ;
public static final long XK_hebrew_samekh = 0xcf1 ; /* deprecated */
public static final long XK_hebrew_ayin = 0xcf2 ;
public static final long XK_hebrew_finalpe = 0xcf3 ;
public static final long XK_hebrew_pe = 0xcf4 ;
public static final long XK_hebrew_finalzade = 0xcf5 ;
public static final long XK_hebrew_finalzadi = 0xcf5 ; /* deprecated */
public static final long XK_hebrew_zade = 0xcf6 ;
public static final long XK_hebrew_zadi = 0xcf6 ; /* deprecated */
public static final long XK_hebrew_qoph = 0xcf7 ;
public static final long XK_hebrew_kuf = 0xcf7 ; /* deprecated */
public static final long XK_hebrew_resh = 0xcf8 ;
public static final long XK_hebrew_shin = 0xcf9 ;
public static final long XK_hebrew_taw = 0xcfa ;
public static final long XK_hebrew_taf = 0xcfa ; /* deprecated */
public static final long XK_Hebrew_switch = 0xFF7E ; /* Alias for mode_switch */
/*
* Thai
* Byte 3 = d
*/
public static final long XK_Thai_kokai = 0xda1 ;
public static final long XK_Thai_khokhai = 0xda2 ;
public static final long XK_Thai_khokhuat = 0xda3 ;
public static final long XK_Thai_khokhwai = 0xda4 ;
public static final long XK_Thai_khokhon = 0xda5 ;
public static final long XK_Thai_khorakhang = 0xda6 ;
public static final long XK_Thai_ngongu = 0xda7 ;
public static final long XK_Thai_chochan = 0xda8 ;
public static final long XK_Thai_choching = 0xda9 ;
public static final long XK_Thai_chochang = 0xdaa ;
public static final long XK_Thai_soso = 0xdab ;
public static final long XK_Thai_chochoe = 0xdac ;
public static final long XK_Thai_yoying = 0xdad ;
public static final long XK_Thai_dochada = 0xdae ;
public static final long XK_Thai_topatak = 0xdaf ;
public static final long XK_Thai_thothan = 0xdb0 ;
public static final long XK_Thai_thonangmontho = 0xdb1 ;
public static final long XK_Thai_thophuthao = 0xdb2 ;
public static final long XK_Thai_nonen = 0xdb3 ;
public static final long XK_Thai_dodek = 0xdb4 ;
public static final long XK_Thai_totao = 0xdb5 ;
public static final long XK_Thai_thothung = 0xdb6 ;
public static final long XK_Thai_thothahan = 0xdb7 ;
public static final long XK_Thai_thothong = 0xdb8 ;
public static final long XK_Thai_nonu = 0xdb9 ;
public static final long XK_Thai_bobaimai = 0xdba ;
public static final long XK_Thai_popla = 0xdbb ;
public static final long XK_Thai_phophung = 0xdbc ;
public static final long XK_Thai_fofa = 0xdbd ;
public static final long XK_Thai_phophan = 0xdbe ;
public static final long XK_Thai_fofan = 0xdbf ;
public static final long XK_Thai_phosamphao = 0xdc0 ;
public static final long XK_Thai_moma = 0xdc1 ;
public static final long XK_Thai_yoyak = 0xdc2 ;
public static final long XK_Thai_rorua = 0xdc3 ;
public static final long XK_Thai_ru = 0xdc4 ;
public static final long XK_Thai_loling = 0xdc5 ;
public static final long XK_Thai_lu = 0xdc6 ;
public static final long XK_Thai_wowaen = 0xdc7 ;
public static final long XK_Thai_sosala = 0xdc8 ;
public static final long XK_Thai_sorusi = 0xdc9 ;
public static final long XK_Thai_sosua = 0xdca ;
public static final long XK_Thai_hohip = 0xdcb ;
public static final long XK_Thai_lochula = 0xdcc ;
public static final long XK_Thai_oang = 0xdcd ;
public static final long XK_Thai_honokhuk = 0xdce ;
public static final long XK_Thai_paiyannoi = 0xdcf ;
public static final long XK_Thai_saraa = 0xdd0 ;
public static final long XK_Thai_maihanakat = 0xdd1 ;
public static final long XK_Thai_saraaa = 0xdd2 ;
public static final long XK_Thai_saraam = 0xdd3 ;
public static final long XK_Thai_sarai = 0xdd4 ;
public static final long XK_Thai_saraii = 0xdd5 ;
public static final long XK_Thai_saraue = 0xdd6 ;
public static final long XK_Thai_sarauee = 0xdd7 ;
public static final long XK_Thai_sarau = 0xdd8 ;
public static final long XK_Thai_sarauu = 0xdd9 ;
public static final long XK_Thai_phinthu = 0xdda ;
public static final long XK_Thai_maihanakat_maitho = 0xdde ;
public static final long XK_Thai_baht = 0xddf ;
public static final long XK_Thai_sarae = 0xde0 ;
public static final long XK_Thai_saraae = 0xde1 ;
public static final long XK_Thai_sarao = 0xde2 ;
public static final long XK_Thai_saraaimaimuan = 0xde3 ;
public static final long XK_Thai_saraaimaimalai = 0xde4 ;
public static final long XK_Thai_lakkhangyao = 0xde5 ;
public static final long XK_Thai_maiyamok = 0xde6 ;
public static final long XK_Thai_maitaikhu = 0xde7 ;
public static final long XK_Thai_maiek = 0xde8 ;
public static final long XK_Thai_maitho = 0xde9 ;
public static final long XK_Thai_maitri = 0xdea ;
public static final long XK_Thai_maichattawa = 0xdeb ;
public static final long XK_Thai_thanthakhat = 0xdec ;
public static final long XK_Thai_nikhahit = 0xded ;
public static final long XK_Thai_leksun = 0xdf0 ;
public static final long XK_Thai_leknung = 0xdf1 ;
public static final long XK_Thai_leksong = 0xdf2 ;
public static final long XK_Thai_leksam = 0xdf3 ;
public static final long XK_Thai_leksi = 0xdf4 ;
public static final long XK_Thai_lekha = 0xdf5 ;
public static final long XK_Thai_lekhok = 0xdf6 ;
public static final long XK_Thai_lekchet = 0xdf7 ;
public static final long XK_Thai_lekpaet = 0xdf8 ;
public static final long XK_Thai_lekkao = 0xdf9 ;
/*
* Korean
* Byte 3 = e
*/
public static final long XK_Hangul = 0xff31 ; /* Hangul start/stop(toggle) */
public static final long XK_Hangul_Start = 0xff32 ; /* Hangul start */
public static final long XK_Hangul_End = 0xff33 ; /* Hangul end, English start */
public static final long XK_Hangul_Hanja = 0xff34 ; /* Start Hangul->Hanja Conversion */
public static final long XK_Hangul_Jamo = 0xff35 ; /* Hangul Jamo mode */
public static final long XK_Hangul_Romaja = 0xff36 ; /* Hangul Romaja mode */
public static final long XK_Hangul_Codeinput = 0xff37 ; /* Hangul code input mode */
public static final long XK_Hangul_Jeonja = 0xff38 ; /* Jeonja mode */
public static final long XK_Hangul_Banja = 0xff39 ; /* Banja mode */
public static final long XK_Hangul_PreHanja = 0xff3a ; /* Pre Hanja conversion */
public static final long XK_Hangul_PostHanja = 0xff3b ; /* Post Hanja conversion */
public static final long XK_Hangul_SingleCandidate = 0xff3c ; /* Single candidate */
public static final long XK_Hangul_MultipleCandidate = 0xff3d ; /* Multiple candidate */
public static final long XK_Hangul_PreviousCandidate = 0xff3e ; /* Previous candidate */
public static final long XK_Hangul_Special = 0xff3f ; /* Special symbols */
public static final long XK_Hangul_switch = 0xFF7E ; /* Alias for mode_switch */
/* Hangul Consonant Characters */
public static final long XK_Hangul_Kiyeog = 0xea1 ;
public static final long XK_Hangul_SsangKiyeog = 0xea2 ;
public static final long XK_Hangul_KiyeogSios = 0xea3 ;
public static final long XK_Hangul_Nieun = 0xea4 ;
public static final long XK_Hangul_NieunJieuj = 0xea5 ;
public static final long XK_Hangul_NieunHieuh = 0xea6 ;
public static final long XK_Hangul_Dikeud = 0xea7 ;
public static final long XK_Hangul_SsangDikeud = 0xea8 ;
public static final long XK_Hangul_Rieul = 0xea9 ;
public static final long XK_Hangul_RieulKiyeog = 0xeaa ;
public static final long XK_Hangul_RieulMieum = 0xeab ;
public static final long XK_Hangul_RieulPieub = 0xeac ;
public static final long XK_Hangul_RieulSios = 0xead ;
public static final long XK_Hangul_RieulTieut = 0xeae ;
public static final long XK_Hangul_RieulPhieuf = 0xeaf ;
public static final long XK_Hangul_RieulHieuh = 0xeb0 ;
public static final long XK_Hangul_Mieum = 0xeb1 ;
public static final long XK_Hangul_Pieub = 0xeb2 ;
public static final long XK_Hangul_SsangPieub = 0xeb3 ;
public static final long XK_Hangul_PieubSios = 0xeb4 ;
public static final long XK_Hangul_Sios = 0xeb5 ;
public static final long XK_Hangul_SsangSios = 0xeb6 ;
public static final long XK_Hangul_Ieung = 0xeb7 ;
public static final long XK_Hangul_Jieuj = 0xeb8 ;
public static final long XK_Hangul_SsangJieuj = 0xeb9 ;
public static final long XK_Hangul_Cieuc = 0xeba ;
public static final long XK_Hangul_Khieuq = 0xebb ;
public static final long XK_Hangul_Tieut = 0xebc ;
public static final long XK_Hangul_Phieuf = 0xebd ;
public static final long XK_Hangul_Hieuh = 0xebe ;
/* Hangul Vowel Characters */
public static final long XK_Hangul_A = 0xebf ;
public static final long XK_Hangul_AE = 0xec0 ;
public static final long XK_Hangul_YA = 0xec1 ;
public static final long XK_Hangul_YAE = 0xec2 ;
public static final long XK_Hangul_EO = 0xec3 ;
public static final long XK_Hangul_E = 0xec4 ;
public static final long XK_Hangul_YEO = 0xec5 ;
public static final long XK_Hangul_YE = 0xec6 ;
public static final long XK_Hangul_O = 0xec7 ;
public static final long XK_Hangul_WA = 0xec8 ;
public static final long XK_Hangul_WAE = 0xec9 ;
public static final long XK_Hangul_OE = 0xeca ;
public static final long XK_Hangul_YO = 0xecb ;
public static final long XK_Hangul_U = 0xecc ;
public static final long XK_Hangul_WEO = 0xecd ;
public static final long XK_Hangul_WE = 0xece ;
public static final long XK_Hangul_WI = 0xecf ;
public static final long XK_Hangul_YU = 0xed0 ;
public static final long XK_Hangul_EU = 0xed1 ;
public static final long XK_Hangul_YI = 0xed2 ;
public static final long XK_Hangul_I = 0xed3 ;
/* Hangul syllable-final (JongSeong) Characters */
public static final long XK_Hangul_J_Kiyeog = 0xed4 ;
public static final long XK_Hangul_J_SsangKiyeog = 0xed5 ;
public static final long XK_Hangul_J_KiyeogSios = 0xed6 ;
public static final long XK_Hangul_J_Nieun = 0xed7 ;
public static final long XK_Hangul_J_NieunJieuj = 0xed8 ;
public static final long XK_Hangul_J_NieunHieuh = 0xed9 ;
public static final long XK_Hangul_J_Dikeud = 0xeda ;
public static final long XK_Hangul_J_Rieul = 0xedb ;
public static final long XK_Hangul_J_RieulKiyeog = 0xedc ;
public static final long XK_Hangul_J_RieulMieum = 0xedd ;
public static final long XK_Hangul_J_RieulPieub = 0xede ;
public static final long XK_Hangul_J_RieulSios = 0xedf ;
public static final long XK_Hangul_J_RieulTieut = 0xee0 ;
public static final long XK_Hangul_J_RieulPhieuf = 0xee1 ;
public static final long XK_Hangul_J_RieulHieuh = 0xee2 ;
public static final long XK_Hangul_J_Mieum = 0xee3 ;
public static final long XK_Hangul_J_Pieub = 0xee4 ;
public static final long XK_Hangul_J_PieubSios = 0xee5 ;
public static final long XK_Hangul_J_Sios = 0xee6 ;
public static final long XK_Hangul_J_SsangSios = 0xee7 ;
public static final long XK_Hangul_J_Ieung = 0xee8 ;
public static final long XK_Hangul_J_Jieuj = 0xee9 ;
public static final long XK_Hangul_J_Cieuc = 0xeea ;
public static final long XK_Hangul_J_Khieuq = 0xeeb ;
public static final long XK_Hangul_J_Tieut = 0xeec ;
public static final long XK_Hangul_J_Phieuf = 0xeed ;
public static final long XK_Hangul_J_Hieuh = 0xeee ;
/* Ancient Hangul Consonant Characters */
public static final long XK_Hangul_RieulYeorinHieuh = 0xeef ;
public static final long XK_Hangul_SunkyeongeumMieum = 0xef0 ;
public static final long XK_Hangul_SunkyeongeumPieub = 0xef1 ;
public static final long XK_Hangul_PanSios = 0xef2 ;
public static final long XK_Hangul_KkogjiDalrinIeung = 0xef3 ;
public static final long XK_Hangul_SunkyeongeumPhieuf = 0xef4 ;
public static final long XK_Hangul_YeorinHieuh = 0xef5 ;
/* Ancient Hangul Vowel Characters */
public static final long XK_Hangul_AraeA = 0xef6 ;
public static final long XK_Hangul_AraeAE = 0xef7 ;
/* Ancient Hangul syllable-final (JongSeong) Characters */
public static final long XK_Hangul_J_PanSios = 0xef8 ;
public static final long XK_Hangul_J_KkogjiDalrinIeung = 0xef9 ;
public static final long XK_Hangul_J_YeorinHieuh = 0xefa ;
/* Korean currency symbol */
public static final long XK_Korean_Won = 0xeff ;
public static final long XK_EcuSign = 0x20a0 ;
public static final long XK_ColonSign = 0x20a1 ;
public static final long XK_CruzeiroSign = 0x20a2 ;
public static final long XK_FFrancSign = 0x20a3 ;
public static final long XK_LiraSign = 0x20a4 ;
public static final long XK_MillSign = 0x20a5 ;
public static final long XK_NairaSign = 0x20a6 ;
public static final long XK_PesetaSign = 0x20a7 ;
public static final long XK_RupeeSign = 0x20a8 ;
public static final long XK_WonSign = 0x20a9 ;
public static final long XK_NewSheqelSign = 0x20aa ;
public static final long XK_DongSign = 0x20ab ;
public static final long XK_EuroSign = 0x20ac ;
// vendor-specific keys from ap_keysym.h, DEC/Sun/HPkeysym.h
public static final long apXK_Copy = 0x1000FF02;
public static final long apXK_Cut = 0x1000FF03;
public static final long apXK_Paste = 0x1000FF04;
public static final long DXK_ring_accent = 0x1000FEB0;
public static final long DXK_circumflex_accent = 0x1000FE5E;
public static final long DXK_cedilla_accent = 0x1000FE2C;
public static final long DXK_acute_accent = 0x1000FE27;
public static final long DXK_grave_accent = 0x1000FE60;
public static final long DXK_tilde = 0x1000FE7E;
public static final long DXK_diaeresis = 0x1000FE22;
public static final long hpXK_ClearLine = 0x1000FF6F;
public static final long hpXK_InsertLine = 0x1000FF70;
public static final long hpXK_DeleteLine = 0x1000FF71;
public static final long hpXK_InsertChar = 0x1000FF72;
public static final long hpXK_DeleteChar = 0x1000FF73;
public static final long hpXK_BackTab = 0x1000FF74;
public static final long hpXK_KP_BackTab = 0x1000FF75;
public static final long hpXK_Modelock1 = 0x1000FF48;
public static final long hpXK_Modelock2 = 0x1000FF49;
public static final long hpXK_Reset = 0x1000FF6C;
public static final long hpXK_System = 0x1000FF6D;
public static final long hpXK_User = 0x1000FF6E;
public static final long hpXK_mute_acute = 0x100000A8;
public static final long hpXK_mute_grave = 0x100000A9;
public static final long hpXK_mute_asciicircum = 0x100000AA;
public static final long hpXK_mute_diaeresis = 0x100000AB;
public static final long hpXK_mute_asciitilde = 0x100000AC;
public static final long hpXK_lira = 0x100000AF;
public static final long hpXK_guilder = 0x100000BE;
public static final long hpXK_Ydiaeresis = 0x100000EE;
public static final long hpXK_IO = 0x100000EE;
public static final long hpXK_longminus = 0x100000F6;
public static final long hpXK_block = 0x100000FC;
public static final long osfXK_Copy = 0x1004FF02;
public static final long osfXK_Cut = 0x1004FF03;
public static final long osfXK_Paste = 0x1004FF04;
public static final long osfXK_BackTab = 0x1004FF07;
public static final long osfXK_BackSpace = 0x1004FF08;
public static final long osfXK_Clear = 0x1004FF0B;
public static final long osfXK_Escape = 0x1004FF1B;
public static final long osfXK_AddMode = 0x1004FF31;
public static final long osfXK_PrimaryPaste = 0x1004FF32;
public static final long osfXK_QuickPaste = 0x1004FF33;
public static final long osfXK_PageLeft = 0x1004FF40;
public static final long osfXK_PageUp = 0x1004FF41;
public static final long osfXK_PageDown = 0x1004FF42;
public static final long osfXK_PageRight = 0x1004FF43;
public static final long osfXK_Activate = 0x1004FF44;
public static final long osfXK_MenuBar = 0x1004FF45;
public static final long osfXK_Left = 0x1004FF51;
public static final long osfXK_Up = 0x1004FF52;
public static final long osfXK_Right = 0x1004FF53;
public static final long osfXK_Down = 0x1004FF54;
public static final long osfXK_EndLine = 0x1004FF57;
public static final long osfXK_BeginLine = 0x1004FF58;
public static final long osfXK_EndData = 0x1004FF59;
public static final long osfXK_BeginData = 0x1004FF5A;
public static final long osfXK_PrevMenu = 0x1004FF5B;
public static final long osfXK_NextMenu = 0x1004FF5C;
public static final long osfXK_PrevField = 0x1004FF5D;
public static final long osfXK_NextField = 0x1004FF5E;
public static final long osfXK_Select = 0x1004FF60;
public static final long osfXK_Insert = 0x1004FF63;
public static final long osfXK_Undo = 0x1004FF65;
public static final long osfXK_Menu = 0x1004FF67;
public static final long osfXK_Cancel = 0x1004FF69;
public static final long osfXK_Help = 0x1004FF6A;
public static final long osfXK_Delete = 0x1004FFFF;
public static final long osfXK_Prior = 0x1004FF55;
public static final long osfXK_Next = 0x1004FF56;
public static final long SunXK_FA_Grave = 0x1005FF00;
public static final long SunXK_FA_Circum = 0x1005FF01;
public static final long SunXK_FA_Tilde = 0x1005FF02;
public static final long SunXK_FA_Acute = 0x1005FF03;
public static final long SunXK_FA_Diaeresis = 0x1005FF04;
public static final long SunXK_FA_Cedilla = 0x1005FF05;
public static final long SunXK_F36 = 0x1005FF10; /* Labeled F11 */
public static final long SunXK_F37 = 0x1005FF11; /* Labeled F12 */
public static final long SunXK_Sys_Req = 0x1005FF60;
public static final long SunXK_Print_Screen = 0x0000FF61; /* Same as XK_Print */
public static final long SunXK_Compose = 0x0000FF20; /* Same as XK_Multi_key */
public static final long SunXK_AltGraph = 0x0000FF7E; /* Same as XK_Mode_switch */
public static final long SunXK_PageUp = 0x0000FF55; /* Same as XK_Prior */
public static final long SunXK_PageDown = 0x0000FF56; /* Same as XK_Next */
public static final long SunXK_Undo = 0x0000FF65; /* Same as XK_Undo */
public static final long SunXK_Again = 0x0000FF66; /* Same as XK_Redo */
public static final long SunXK_Find = 0x0000FF68; /* Same as XK_Find */
public static final long SunXK_Stop = 0x0000FF69; /* Same as XK_Cancel */
public static final long SunXK_Props = 0x1005FF70;
public static final long SunXK_Front = 0x1005FF71;
public static final long SunXK_Copy = 0x1005FF72;
public static final long SunXK_Open = 0x1005FF73;
public static final long SunXK_Paste = 0x1005FF74;
public static final long SunXK_Cut = 0x1005FF75;
public static final long SunXK_PowerSwitch = 0x1005FF76;
public static final long SunXK_AudioLowerVolume = 0x1005FF77;
public static final long SunXK_AudioMute = 0x1005FF78;
public static final long SunXK_AudioRaiseVolume = 0x1005FF79;
public static final long SunXK_VideoDegauss = 0x1005FF7A;
public static final long SunXK_VideoLowerBrightness = 0x1005FF7B;
public static final long SunXK_VideoRaiseBrightness = 0x1005FF7C;
public static final long SunXK_PowerSwitchShift = 0x1005FF7D;
}
| 50.247137
| 92
| 0.727639
|
73c19f9a2936b0cb5b8984c9b9de2cc6088dac38
| 438
|
package com.aunghan.stockmanagementsystem.service;
import com.aunghan.stockmanagementsystem.entity.Stock;
import java.util.List;
public interface StockService {
Stock saveStock(Stock stock);
List<Stock> getStocks();
Stock getStockById(int id);
String deleteStock(int id);
Stock updateStock(Stock stock);
Stock getStockByStockName(String stockName);
String setActiveStatus(int id, boolean isActive);
}
| 19.909091
| 54
| 0.753425
|
e1c059ef0e4c8c0653d1d1b05f259837cbdb57f0
| 9,068
|
/* Copyright 2005-2006 Tim Fennell
*
* 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 net.sourceforge.stripes.tag;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.controller.StripesConstants;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.util.ReflectUtil;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
import java.util.Stack;
/**
* A very basic implementation of the Tag interface that is similar in manner to the standard
* TagSupport class, but with less clutter.
*
* @author Tim Fennell
*/
public abstract class StripesTagSupport implements Tag {
private static final Log log = Log.getInstance(StripesTagSupport.class);
/** Storage for a PageContext during evaluation. */
protected PageContext pageContext;
/** Storage for the parent tag of this tag. */
protected Tag parentTag;
/**
* A map that is used to store values of page context attributes before they were
* replaced with other values for the body of the tag.
*/
private Map<String,Object> previousAttributeValues;
/** Called by the Servlet container to set the page context on the tag. */
public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
}
/** Retrieves the pageContext handed to the tag by the container. */
public PageContext getPageContext() {
return this.pageContext;
}
/** From the Tag interface - allows the container to set the parent tag on the JSP. */
public void setParent(Tag tag) {
this.parentTag = tag;
}
/** From the Tag interface - allows fetching the parent tag on the JSP. */
public Tag getParent() {
return this.parentTag;
}
/**
* Abstract method from the Tag interface. Abstract because it seems to make the
* child tags more readable if they implement their own do() methods, even when
* they just return one of the constants and do nothing else.
*/
public abstract int doStartTag() throws JspException;
/**
* Abstract method from the Tag interface. Abstract because it seems to make the
* child tags more readable if they implement their own do() methods, even when
* they just return one of the constants and do nothing else.
*/
public abstract int doEndTag() throws JspException;
/**
* No-op implementation of release().
*/
public void release() { }
/**
* Pushes new values for the attributes supplied into the page context, preserving
* the old values so that they can be put back into page context end of the tag's
* execution (usually in doEndTag). If this method is called, the tag <b>must</b>
* also call{@link #popPageContextAttributes()}.
*/
public void pushPageContextAttributes(Map<String,Object> attributes) {
this.previousAttributeValues = new HashMap<String,Object>();
for (Map.Entry<String,Object> entry : attributes.entrySet()) {
String name = entry.getKey();
this.previousAttributeValues.put(name, pageContext.getAttribute(name));
this.pageContext.setAttribute(name, entry.getValue());
}
}
/**
* Attempts to restore page context attributes to their state prior to a call to
* pushPageContextAttributes(). Attributes that had values prior to the execution of
* this tag have their values restored. Attributes that did not have values
* are removed from the page context.
*/
public void popPageContextAttributes() {
for (Map.Entry<String,Object> entry : this.previousAttributeValues.entrySet()) {
if (entry.getValue() == null) {
this.pageContext.removeAttribute(entry.getKey());
}
else {
this.pageContext.setAttribute(entry.getKey(), entry.getValue());
}
}
// Null out the map so erroneous values don't get picked up on tag pooling!
this.previousAttributeValues = null;
}
/**
* <p>Locates the enclosing tag of the type supplied. If no enclosing tag of the type supplied
* can be found anywhere in the ancestry of this tag, null is returned.</p>
*
* @return T Tag of the type supplied, or null if none can be found
*/
@SuppressWarnings("unchecked")
protected <T extends Tag> T getParentTag(Class<T> tagType) {
Tag parent = getParent();
while (parent != null) {
if (tagType.isAssignableFrom(parent.getClass())) {
return (T) parent;
}
parent = parent.getParent();
}
// If we can't find it by the normal way, try our own tag stack!
Stack<StripesTagSupport> stack = getTagStack();
ListIterator<StripesTagSupport> iterator = stack.listIterator(stack.size());
while (iterator.hasPrevious() && iterator.previous() != this) continue;
while (iterator.hasPrevious()) {
StripesTagSupport tag = iterator.previous();
if (tagType.isAssignableFrom(tag.getClass())) {
return (T) tag;
}
}
return null;
}
/**
* Fetches a tag stack that is stored in the request. This tag stack is used to help
* Stripes tags find one another when they are spread across multiple included JSPs
* and/or tag files - situations in which the usual parent tag relationship fails.
*/
@SuppressWarnings("unchecked")
protected Stack<StripesTagSupport> getTagStack() {
Stack<StripesTagSupport> stack = (Stack<StripesTagSupport>)
getPageContext().getRequest().getAttribute(StripesConstants.REQ_ATTR_TAG_STACK);
if (stack == null) {
stack = new Stack<StripesTagSupport>();
getPageContext().getRequest().setAttribute(StripesConstants.REQ_ATTR_TAG_STACK, stack);
}
return stack;
}
/**
* Helper method that takes an attribute which may be either a String class name
* or a Class object and returns the Class representing the appropriate ActionBean.
* If for any reason the Class cannot be determined, or it is not an ActionBean, null
* will be returned instead.
*
* @param nameOrClass either the String FQN of an ActionBean class, or a Class object
* @return the appropriate ActionBean class or null
*/
@SuppressWarnings("unchecked")
protected Class<? extends ActionBean> getActionBeanType(Object nameOrClass) {
Class result = null;
// Figure out if it's a String of Class (or something else?) and act appropriately
if (nameOrClass instanceof String) {
try {
result = ReflectUtil.findClass((String) nameOrClass);
}
catch (ClassNotFoundException cnfe) {
log.error(cnfe, "Could not find class of type: ", nameOrClass);
return null;
}
}
else if (nameOrClass instanceof Class) {
result = (Class) nameOrClass;
}
else {
log.error("The value supplied to getActionBeanType() was neither a String nor a " +
"Class. Cannot infer ActionBean type from value: " + nameOrClass);
return null;
}
// And for good measure, let's make sure it's an ActionBean implementation!
if (ActionBean.class.isAssignableFrom(result)) {
return result;
}
else {
log.error("Class '", result.getName(), "' specified in tag does not implement ",
"ActionBean.");
return null;
}
}
/**
* Similar to the {@link #getActionBeanType(Object)} method except that instead of
* returning the Class of ActionBean it returns the URL Binding of the ActionBean.
*
* @param nameOrClass either the String FQN of an ActionBean class, or a Class object
* @return the URL of the appropriate ActionBean class or null
*/
protected String getActionBeanUrl(Object nameOrClass) {
Class<? extends ActionBean> beanType = getActionBeanType(nameOrClass);
if (beanType != null) {
return StripesFilter.getConfiguration().getActionResolver().getUrlBinding(beanType);
}
else {
return null;
}
}
}
| 38.587234
| 99
| 0.656815
|
6a0d750df782e954f7c18d589fc7c0572460308b
| 1,935
|
package net.sojoner.functional;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class App
{
static void converterExample(){
System.out.println("Converter Example.");
Converter converter = new Converter();
Double tenMilesInKm = converter.apply(1.609, 10.0);
System.out.println("Apply a function to a value:: " + tenMilesInKm);
Function<Double, Double> miles2KmConverter = converter.curry1(1.609);
System.out.println("Converted curried value:: " + miles2KmConverter.apply(10.0));
List<Double> collect = Stream.of(10.0, 20.0, 50.0)
.map(new Converter().curry1(1.609))
.collect(Collectors.toList());
System.out.println("Converted curried values:: " + collect);
List<Double> collect1 = Stream.of(10.0, 20.0, 50.0)
.map(new Converter()
.curry1(9.0 / 5)
.andThen(n -> n + 32))
.collect(Collectors.toList());
System.out.println("Converted curried values with andThen step:: "+ collect1);
Function<Double, Double> f2cConverter =
new Converter()
.compose2((Double n) -> n - 32)
.curry1(5.0 / 9);
System.out.println("Converted composed values:: " + f2cConverter.apply(78.0));
}
static void salaryExample(){
System.out.println("Salary Example.");
double salary = new SalaryCalculator()
.with(SalaryRules::plusBonus)
.with(SalaryRules::plusTax)
.with(s -> s* 0.95) // Just add a new SalaryRule
.calculate(40.0);
System.out.println("The payment:: "+ salary);
}
public static void main( String[] args )
{
converterExample();
salaryExample();
}
}
| 32.79661
| 89
| 0.575194
|
cd28de42d95ea4dcddb540fbf005ef81246d1fa9
| 1,113
|
/*
* APIv3SandboxLib
*
* This file was automatically generated by APIMATIC BETA v2.0 on 03/10/2015
*/
package com.voxbone.sandbox.models;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
public class DidListModel
implements java.io.Serializable {
private List<DidModel> dids;
private int resultCount;
/** GETTER
* The list of DIDs
*/
@JsonGetter("dids")
public List<DidModel> getDids ( ) {
return this.dids;
}
/** SETTER
* The list of DIDs
*/
@JsonSetter("dids")
public void setDids (List<DidModel> value) {
this.dids = value;
}
/** GETTER
* The total amount of DIDs found
*/
@JsonGetter("resultCount")
public int getResultCount ( ) {
return this.resultCount;
}
/** SETTER
* The total amount of DIDs found
*/
@JsonSetter("resultCount")
public void setResultCount (int value) {
this.resultCount = value;
}
}
| 22.26
| 77
| 0.592992
|
83eac3e29edac1053907da2ccd30fb95c9368ce3
| 1,682
|
/* Copyright (c) 2008-2011, The University of Edinburgh.
* All Rights Reserved
*/
package uk.ac.ed.ph.snuggletex.samples;
import uk.ac.ed.ph.snuggletex.SerializationMethod;
import uk.ac.ed.ph.snuggletex.SnuggleEngine;
import uk.ac.ed.ph.snuggletex.SnuggleInput;
import uk.ac.ed.ph.snuggletex.SnuggleSession;
import uk.ac.ed.ph.snuggletex.XMLStringOutputOptions;
import java.io.IOException;
/**
* This example generalises {@link MinimalExample} to create a slightly
* more interesting output.
*
* @author David McKain
*/
public final class XMLStringOutputExample {
public static void main(String[] args) throws IOException {
/* Create vanilla SnuggleEngine and new SnuggleSession */
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
/* Parse some LaTeX input */
SnuggleInput input = new SnuggleInput("\\section*{The quadratic formula}"
+ "$$ \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a} $$");
session.parseInput(input);
/* Specify how we want the resulting XML */
XMLStringOutputOptions options = new XMLStringOutputOptions();
options.setSerializationMethod(SerializationMethod.XHTML);
options.setIndenting(true);
options.setEncoding("UTF-8");
options.setAddingMathSourceAnnotations(true);
options.setUsingNamedEntities(true); /* (Only used if caller has an XSLT 2.0 processor) */
/* Convert the results to an XML String, which in this case will
* be a single MathML <math>...</math> element. */
System.out.println(session.buildXMLString(options));
}
}
| 37.377778
| 98
| 0.681926
|
5b8d1e7e20938e0f123aec116afc2febc83a6b7f
| 602
|
@Override
public void actionPerformed(ActionEvent e) {
if (fileChooser.showOpenDialog(getMainWindow()) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
resetOutput();
try {
model.add(file.getName(), calculator.load(file));
} catch (IOException e1) {
JOptionPane.showMessageDialog(getMainWindow(), "Unable to load matrix from file: " + file.getName());
}
}
}
| 46.307692
| 125
| 0.48505
|
e062e31d19e58c543f424bab00dd0252ce11e258
| 1,025
|
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.ir.builder;
import gw.lang.ir.IRType;
import gw.lang.ir.statement.IRFieldDecl;
import gw.lang.reflect.IType;
import gw.lang.UnstableAPI;
@UnstableAPI
public class IRFieldBuilder extends IRFeatureBuilder<IRFieldBuilder> {
private IRClassBuilder _classBuilder;
private String _name;
private IRType _type;
public IRFieldBuilder(IRClassBuilder classBuilder) {
_classBuilder = classBuilder;
}
public IRFieldBuilder withName( String name ) {
_name = name;
return this;
}
public IRFieldBuilder withType( Class type ) {
return withType( getIRType( type ) );
}
public IRFieldBuilder withType( IType type ) {
return withType( getIRType( type ) );
}
public IRFieldBuilder withType( IRType type ) {
_type = type;
return this;
}
public IRFieldDecl build() {
IRFieldDecl fieldDecl = new IRFieldDecl( _modifiers, _name, _type, null );
_classBuilder.withField( fieldDecl );
return fieldDecl;
}
}
| 22.282609
| 78
| 0.72
|
df12738472f272aacf3b8c81126c2984be002150
| 811
|
package kbasesearchengine.main;
import kbasesearchengine.SearchTypesInput;
import kbasesearchengine.SearchTypesOutput;
import kbasesearchengine.SearchObjectsInput;
import kbasesearchengine.SearchObjectsOutput;
import kbasesearchengine.GetObjectsInput;
import kbasesearchengine.GetObjectsOutput;
import kbasesearchengine.TypeDescriptor;
import java.util.Map;
public interface SearchInterface {
// TODO JAVADOC
SearchTypesOutput searchTypes(SearchTypesInput params, String user) throws Exception;
SearchObjectsOutput searchObjects(SearchObjectsInput params, String user)
throws Exception;
GetObjectsOutput getObjects(GetObjectsInput params, String user)
throws Exception;
Map<String, TypeDescriptor> listTypes(String uniqueType) throws Exception;
}
| 30.037037
| 89
| 0.805179
|
52143dcc132e95c9ce87bb7c0d12493d5bee812d
| 932
|
package com.jsoniter.any;
import com.jsoniter.ValueType;
import com.jsoniter.output.JsonStream;
import java.io.IOException;
/**
* @author MaxiBon
*
*/
class TrueAny extends Any {
/**
* public final static TrueAny INSTANCE = new TrueAny();
*
* @author MaxiBon
*
*/
public final static TrueAny INSTANCE = new TrueAny();
@Override
/**
* valueType.
*/
public ValueType valueType() {
return ValueType.BOOLEAN;
}
@Override
public Boolean object() {
return Boolean.TRUE;
}
@Override
public boolean toBoolean() {
return true;
}
@Override
public int toInt() {
return 1;
}
@Override
public long toLong() {
return 1;
}
@Override
public float toFloat() {
return 1;
}
@Override
public double toDouble() {
return 1;
}
@Override
public String toString() {
return "true";
}
@Override
public void writeTo(JsonStream stream) throws IOException {
stream.writeTrue();
}
}
| 13.126761
| 60
| 0.666309
|
efd108abaefdf194b8788ae131cefaa9ee4178f7
| 410
|
package com.novoda.bonfire.channel.displayer;
public interface NewChannelDisplayer {
void attach(ChannelCreationListener channelCreationListener);
void detach(ChannelCreationListener channelCreationListener);
void showChannelCreationError();
interface ChannelCreationListener {
void onCreateChannelClicked(String channelName, boolean isPrivate);
void onCancel();
}
}
| 22.777778
| 75
| 0.770732
|
68bbd1c549c6cc61a05c590ad572395786d7df21
| 936
|
package com.itijavafinalprojectteam8.view.gamechooserscreen;
import com.itijavafinalprojectteam8.view.interfaces.GameAppView;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import java.io.IOException;
public class GameChooserController {
@FXML
private Button player;
@FXML
private Button computer;
private static GameAppView mApplicationCallback;
public static void setApplicationCallback(GameAppView callback) {
mApplicationCallback = callback;
}
@FXML
private void clickOnPlayer(ActionEvent event) throws IOException {
if (mApplicationCallback != null)
mApplicationCallback.switchToGameWithOtherPlayerScreen();
}
@FXML
private void clickOnComputer(ActionEvent event) throws IOException {
if (mApplicationCallback != null)
mApplicationCallback.switchToGameWithCpuScreen();
}
}
| 24.631579
| 72
| 0.744658
|
7b47ef484f0fe4e399ccedbd5da3856c57044b05
| 688
|
package com.example;
import io.arivera.oss.jchatops.MessageType;
import io.arivera.oss.jchatops.annotations.MessageHandler;
import io.arivera.oss.jchatops.responders.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
@Service
public class SecuredConversation {
@MessageHandler(patterns = "(.*)password(.*)?", messageTypes = {MessageType.PRIVATE, MessageType.TAGGED})
@Secured("ROLE_ADMIN")
public Response revealPassword(Response response) {
return response
.message("The password is: `" + RandomStringUtils.randomAlphanumeric(10) + "`");
}
}
| 31.272727
| 107
| 0.777616
|
f3a0f24bd3d7d6e7c2c3eab782926d4ea68b0d85
| 1,192
|
package com.classycode.nfcsockets.sockets;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.SocketFactory;
/**
* @author Alex Suzuki, Classy Code GmbH, 2017
*/
public class NFCSocketFactory extends SocketFactory {
public NFCSocketFactory() {
}
@Override
public Socket createSocket() throws IOException {
return new NFCSocket();
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return new NFCSocket(host, port);
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return new NFCSocket(host, port, localHost, localPort);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return new NFCSocket(host, port);
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return new NFCSocket(address, port, localAddress, localPort);
}
}
| 27.72093
| 134
| 0.723993
|
38aad8a0da71eb93f89ce35ea84e3ef7bf39770d
| 505
|
package pojo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
/*
请求传输的格式
服务端需要相关的信息确定调用哪个接口方法
*/
@Data
@AllArgsConstructor
@Builder
public class RpcRequestFormat implements Serializable {
//待调用的接口名
private String interFaceName;
//待调用的方法名
private String methodName;
//调用的方法参数
private Object[] parameters;
//因为在序列化的时候,Object[]数组中的数据会序列化失败,所以需要一个方法参数类型辅助序列化
//方法参数类型
private Class<?>[] paramType;
}
| 15.78125
| 55
| 0.730693
|
01073f3fc93a745b5033446a770ce2bfdeb45561
| 1,771
|
package org.displaytag.jsptests;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import org.displaytag.test.DisplaytagCase;
import org.displaytag.test.KnownTypes;
import org.apache.commons.lang.StringUtils;
/**
* @author rapruitt
* @version $Revision: 1081 $ ($Author: fgiust $)
*/
public class TotalsTest extends DisplaytagCase
{
/**
* @see org.displaytag.test.DisplaytagCase#getJspName()
*/
public String getJspName()
{
return "totals.jsp";
}
/**
* Check sorted columns.
* @param jspName jsp name, with full path
* @throws Exception any axception thrown during test.
*/
public void doTest(String jspName) throws Exception
{
WebRequest request = new GetMethodWebRequest(jspName);
WebResponse response = runner.getResponse(request);
if (log.isDebugEnabled())
{
log.debug(response.getText());
}
WebTable[] tables = response.getTables();
assertEquals("Wrong number of tables.", 1, tables.length);
assertEquals("Bad number of generated columns.", 3, tables[0].getColumnCount());
// The footer will PRECEDE the body.
assertTrue("Totals should not be calculated / present if the column is not so marked.", StringUtils
.isBlank(tables[0].getCellAsText(1, 0)));
assertEquals("Bad value in footer cell total.", "" + (KnownTypes.LONG_VALUE.doubleValue() * 2), tables[0]
.getCellAsText(1, 1));
assertEquals("Bad value in footer cell total.", "" + (KnownTypes.LONG_VALUE.doubleValue() * 2), tables[0]
.getCellAsText(1, 2));
}
}
| 31.625
| 113
| 0.663467
|
0c22a15107e3c878a077536e2035e58803093ec7
| 601
|
package org.bcos.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.bcos.web3j.abi.datatypes.Fixed;
/**
* <p>Auto generated code.<br>
* <strong>Do not modifiy!</strong><br>
* Please use {@link org.bcos.web3j.codegen.AbiTypesGenerator} to update.</p>
*/
public class Fixed160x24 extends Fixed {
public static final Fixed160x24 DEFAULT = new Fixed160x24(BigInteger.ZERO);
public Fixed160x24(BigInteger value) {
super(160, 24, value);
}
public Fixed160x24(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
super(160, 24, m, n);
}
}
| 27.318182
| 80
| 0.698835
|
68e700a0cbb10e001a683d60c7c327fb325487c3
| 6,386
|
package com.nominum.build;
import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This mojo monitors source files and recompiles and reloads the development server automatically.
*/
@Mojo(name="watch")
public class ServerMojo extends AbstractMojo implements FileListener {
/**
* The maven project.
*/
@Parameter(defaultValue="${project}",required=true,readonly=true)
public MavenProject project;
/**
* Maven ProjectHelper.
*
* @component
* @readonly
*/
public MavenProjectHelper projectHelper;
/**
* Location of the compiled templates.
*/
@Parameter(defaultValue="${project.build.directory}/generated-sources/play-templates",required=true)
private File generatedSourcesDirectory;
/**
* Location of the source files.
*/
@Parameter(defaultValue="${project.build.sourceDirectory}",required=true)
private File sourceDirectory;
/**
* Location of the play conf directory.
*/
@Parameter(defaultValue="${project.basedir}/conf",required=true)
private File confDirectory;
/**
* Directory containing the build files.
*/
@Parameter(defaultValue="${project.build.directory}")
public File buildDirectory;
/**
* Base directory of the project.
*/
@Parameter(defaultValue="${project.basedir}")
public File baseDirectory;
/** whether reverse routes are generated */
@Parameter(defaultValue="true", required=true)
private Boolean generateReverseRouter;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
setupMonitor();
} catch (FileSystemException e) {
throw new MojoExecutionException("Cannot set the file monitor on the source folder", e);
}
String MESSAGE = "You're running the watch mode. Modified templates and " +
"routes will be processed automatically. \n" +
"To leave the watch mode, just hit CTRL+C.\n";
getLog().info(MESSAGE);
try {
invokeScalaCC();
// just wait around until killed
while (true) {
Thread.sleep(10000);
}
} catch (InterruptedException e) {
/* exit normally */
}
}
class StreamConsumer extends Thread {
private Process process;
public StreamConsumer(Process process) {
this.process = process;
}
@Override
public void run() {
try {
InputStreamReader inputStream = new InputStreamReader(process.getInputStream());
BufferedReader bufferedOut = new BufferedReader(inputStream);
String line = null;
while ((line = bufferedOut.readLine()) != null) {
// HACK filter out noise from slightly broken 3.1.0 version of the plugin
if (line.equals("[INFO] wait for files to compile...")
|| line.contains("Compile success at")) continue;
System.out.println(line);
}
}
catch (IOException e) {
return;
}
}
}
private void invokeScalaCC() throws MojoExecutionException {
ProcessBuilder processBuilder = new ProcessBuilder("mvn", "scala:cc");
processBuilder.redirectErrorStream(true);
try {
final Process scalaCC = processBuilder.start();
StreamConsumer streamConsumer = new StreamConsumer(scalaCC);
streamConsumer.start();
try {
scalaCC.waitFor();
} finally {
stopProcess(scalaCC);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stopProcess(scalaCC);
}
});
} catch (IOException e) {
throw new MojoExecutionException("Unable to find or run \"mvn\" (maven executable)", e);
} catch (InterruptedException e) {
throw new MojoExecutionException("Running scala:cc Failed", e);
}
}
private void stopProcess(Process process) {
try {
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
} catch (IOException e) {
}
process.destroy();
}
private void setupMonitor() throws FileSystemException {
getLog().info("Set up file monitor on " + sourceDirectory);
FileSystemManager fsManager = VFS.getManager();
FileObject dir = fsManager.resolveFile(sourceDirectory.getAbsolutePath());
DefaultFileMonitor fm = new DefaultFileMonitor(this);
fm.setRecursive(true);
fm.addFile(dir);
FileObject routes = fsManager.resolveFile(new File(confDirectory, "routes").getAbsolutePath());
fm.addFile(routes);
fm.start();
}
private void compileTemplatesAndRoutes() throws MojoExecutionException {
TemplateCompilerMojo.compileTemplatesAndRoutes(confDirectory,
generatedSourcesDirectory, project, sourceDirectory, generateReverseRouter);
}
public void fileCreated(FileChangeEvent event) throws Exception {
getLog().debug("New file found " + event.getFile().getName().getBaseName());
compileTemplatesAndRoutes();
}
public void fileDeleted(FileChangeEvent event) throws Exception {
getLog().debug("File " + event.getFile().getName().getBaseName() + " deleted");
// TODO delete the corresponding class file
}
public void fileChanged(FileChangeEvent event) throws Exception {
getLog().debug("File changed: " + event.getFile().getName().getBaseName());
compileTemplatesAndRoutes();
}
}
| 32.090452
| 104
| 0.62684
|
9705e2e66b2950f9250879df371f3a8ee4a5b229
| 388
|
package sovsen.plejeren;
import sovsen.plejeren.view.presenter.Client;
import static org.junit.Assert.assertEquals;
public class MTest {
Client client = new Client("Mads", "Kværredevej", "12.00");
@org.junit.Test
public void TestClient() {
// Tester om navn bliver hentet som String fra task objektet
assertEquals("Mads", client.getmName());
}
}
| 17.636364
| 68
| 0.680412
|
a46fb3140c51f70bf438290270e9d7dc6d4da94b
| 3,769
|
/*
* $Id$
*/
/*
Copyright (c) 2015 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.ws.entities;
/**
* A wrapper for the result of an archival unit crawl request web service
* operation.
*/
public class RequestCrawlResult {
private String id;
private boolean success = false;
private String delayReason;
private String errorMessage;
/**
* Default constructor.
*/
public RequestCrawlResult() {
}
/**
* Constructor.
*
* @param id
* A String with the Archival Unit identifier.
* @param success
* A boolean with <code>true</code> if the request was made
* successfully, <code>false</code> otherwise.
* @param delayReason
* A String with the reason for any delay in performing the
* operation.
* @param errorMessage
* A String with any error message as a result of the operation.
*/
public RequestCrawlResult(String id, boolean success, String delayReason,
String errorMessage) {
this.id = id;
this.success = success;
this.delayReason = delayReason;
this.errorMessage = errorMessage;
}
/**
* Provides the Archival Unit identifier.
*
* @return a String with the identifier.
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Provides the indication of whether the request was made successfully.
*
* @return a boolean with <code>true</code> if the request was made
* successfully, <code>false</code> otherwise.
*/
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
/**
* Provides the reason for a in performing the operation, if any.
*
* @return a String with the message.
*/
public String getDelayReason() {
return delayReason;
}
public void setDelayReason(String delayReason) {
this.delayReason = delayReason;
}
/**
* Provides any error message as a result of the operation.
*
* @return a String with the error message.
*/
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "[RequestCrawlResult id=" + id + ", success=" + success
+ ", delayReason=" + delayReason + ", errorMessage=" + errorMessage
+ "]";
}
}
| 29.445313
| 79
| 0.697267
|
2a16dd3d4616f985744fee0805a51f0792ff5853
| 2,346
|
package com.apteligent.display;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by levy on 7/19/16.
*/
public class BreadcrumbTrail {
public enum BreadcrumbType {
UNKNOWN, NORMAL, NETWORK_CALL, FOREGROUND_BACKGROUND, NETWORK_CONNECTION_CHANGE, VIEW_CHANGE, HANDLED_EXCEPTION, CRASH
}
public static class Breadcrumb {
String deviceOccurredTs;
String type;
LinkedHashMap<String, String> payload; // {"priority":"normal","text":"MenuControlAcivity: rateAppDialogCallback()"}
BreadcrumbType typeCode; // type of breadcrumb
@Override
public String toString() {
// build payload
String payloadJson = "{";
for (Map.Entry<String, String> entry : payload.entrySet()) {
payloadJson += "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\",";
}
payloadJson = payloadJson.substring(0, payloadJson.length()-1); // remove trailing comma
payloadJson += "}";
return String.format("{\"deviceOccurredTs\":\"%s\",\"type\":\"%s\",\"payload\":%s,\"typeCode\":%d}",
deviceOccurredTs, type, payloadJson, typeCode.ordinal());
}
}
String username;
String traceTs; // ex: "2016-07-10T07:33:27.924+00:00"
ArrayList<Breadcrumb> parsedBreadcrumbs;
String appVersion;
String deviceId; // randomly generated by Apteligent
String device;
String os;
/*
Spits out valid json string
*/
@Override
public String toString() {
String breadcrumbs = "[]";
if (parsedBreadcrumbs != null && parsedBreadcrumbs.size() > 0) {
breadcrumbs = "[";
for(int i = 0; i < parsedBreadcrumbs.size(); i++) {
breadcrumbs += parsedBreadcrumbs.get(i).toString();
if(i != parsedBreadcrumbs.size() - 1) {
breadcrumbs += ",";
}
}
breadcrumbs += "]";
}
return String.format("{\"username\":\"%s\",\"traceTs\":\"%s\",\"appVersion\":\"%s\",\"deviceId\":\"%s\"" +
",\"device\":\"%s\",\"os\":\"%s\",\"parsedBreadcrumbs\":%s}",
username, traceTs, appVersion, deviceId, device, os, breadcrumbs);
}
}
| 36.65625
| 126
| 0.560529
|
1cf880c62fe71a87be01d3d036bb595e8da77415
| 1,344
|
package com.osomapps.pt.dictionary;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Getter
@Setter
@Entity
@Table(name = "dictionary_data", schema = "ptcore")
@DynamicInsert
public class DictionaryData {
@Id
@GenericGenerator(
name = "DictionaryIdSequence",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "ptcore.dictionary_data_id_seq"),
@Parameter(name = "initial_value", value = "1"),
@Parameter(name = "increment_size", value = "1")
})
@GeneratedValue(generator = "DictionaryIdSequence")
Long id;
LocalDateTime created;
String dlanguage;
Boolean valid;
LocalDateTime fromdate;
LocalDateTime todate;
String dname;
String dkey;
String dvalue;
}
| 28.595745
| 92
| 0.719494
|
6c644f3fbb88f4b3fce2e0c12ccf482a09801f1c
| 1,696
|
package org.teavm.libgdx;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import org.teavm.jso.browser.Storage;
/**
*
* @author Alexey Andreev
*/
public class TeaVMFiles implements Files {
public static final Storage localStorage = Storage.getLocalStorage();
@Override
public FileHandle getFileHandle(String path, FileType type) {
if (type != FileType.Internal) {
throw new GdxRuntimeException("FileType '" + type + "' not supported in GWT backend");
}
return new TeaVMFileHandle(path, type);
}
@Override
public FileHandle classpath(String path) {
return new TeaVMFileHandle(path, FileType.Classpath);
}
@Override
public FileHandle internal(String path) {
return new TeaVMFileHandle(path, FileType.Internal);
}
@Override
public FileHandle external(String path) {
throw new GdxRuntimeException("External files not supported in GWT backend");
}
@Override
public FileHandle absolute(String path) {
throw new GdxRuntimeException("Absolute files not supported in GWT backend");
}
@Override
public FileHandle local(String path) {
throw new GdxRuntimeException("local files not supported in GWT backend");
}
@Override
public String getExternalStoragePath() {
return null;
}
@Override
public boolean isExternalStorageAvailable() {
return false;
}
@Override
public String getLocalStoragePath() {
return null;
}
@Override
public boolean isLocalStorageAvailable() {
return false;
}
}
| 24.941176
| 98
| 0.675118
|
ac668816a11fcac8beb69ad8862c2383631185a5
| 156
|
package org.nearbyshops.enduserappnew.Interfaces;
/**
* Created by sumeet on 29/9/16.
*/
public interface NotifySort {
void notifySortChanged();
}
| 14.181818
| 49
| 0.717949
|
8e32aab8bf04c75aea8471053da2da51511d5cbc
| 325
|
package com.angkorteam.fintech.ddl;
public interface MSavingsProductCharge {
public static final String NAME = "m_savings_product_charge";
public interface Field {
public static final String CHARGE_ID = "charge_id";
public static final String SAVINGS_PRODUCT_ID = "savings_product_id";
}
}
| 20.3125
| 77
| 0.729231
|
3eda416c36e88bfebd01a2ecf8b03950cbb2a9f6
| 1,059
|
package cpw.mods.fml.common;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import cpw.mods.fml.common.modloader.BaseMod;
import cpw.mods.fml.common.modloader.ModProperty;
public interface IFMLSidedHandler
{
Logger getMinecraftLogger();
File getMinecraftRootDirectory();
boolean isModLoaderMod(Class<?> clazz);
ModContainer loadBaseModMod(Class<?> clazz, File canonicalFile);
Object getMinecraftInstance();
String getCurrentLanguage();
Properties getCurrentLanguageTable();
String getObjectName(Object minecraftObject);
ModMetadata readMetadataFrom(InputStream input, ModContainer mod) throws Exception;
void profileStart(String profileLabel);
void profileEnd();
ModProperty getModLoaderPropertyFor(Field f);
List<String> getAdditionalBrandingInformation();
Side getSide();
ProxyInjector findSidedProxyOn(BaseMod mod);
void haltGame(String message, Throwable exception);
}
| 33.09375
| 87
| 0.778093
|
a630ab804c27c72dd03338f55f992eaae1fc63a5
| 1,575
|
package dev.willbanders.storm.serializer.primitive;
import com.google.common.collect.Sets;
import dev.willbanders.storm.config.Node;
import dev.willbanders.storm.serializer.SerializationException;
import dev.willbanders.storm.serializer.Serializer;
import java.util.Set;
/**
* Serializes an {@link Enum} constant to its name. Deserialization is currently
* case-insensitive, but this may change in the future.
*/
public final class EnumSerializer<T extends Enum<T>> implements Serializer<T> {
public static final EnumSerializer<?> INSTANCE = new EnumSerializer<>(null);
private final Set<T> constants;
private EnumSerializer(Set<T> constants) {
this.constants = constants;
}
@Override
public T deserialize(Node node) throws SerializationException {
String value = node.get(StringSerializer.INSTANCE);
return constants.stream().filter(c -> c.name().equalsIgnoreCase(value)).findFirst()
.orElseThrow(() -> new SerializationException(node, "Expected the value to be one of " + constants + "."));
}
@Override
public void reserialize(Node node, T value) throws SerializationException {
if (value == null) {
throw new SerializationException(node, "Expected a non-null value.");
}
node.attach().setValue(value.name());
}
/**
* Returns a new serializer for the given enum class.
*/
public <T extends Enum<T>> EnumSerializer<T> of(Class<T> clazz) {
return new EnumSerializer<>(Sets.newHashSet(clazz.getEnumConstants()));
}
}
| 33.510638
| 123
| 0.693333
|
bc6a08d678a63095536834947803bb8fe67035e2
| 1,290
|
package cs455.scaling.task;
import cs455.scaling.threadpool.Task;
import cs455.scaling.util.LOGGER;
import java.util.concurrent.LinkedBlockingQueue;
/**
* This class is not meant to be used directly. This class is only meant to be used by the {@link BatchTaskManager}.
* This class contains a list of tasks that are to be executed when the batch task manager sends an instance of this
* class to the thread pool. The set of tasks can include either the client registration task or the read and respond
* task, or any kind of task as long as it implements the @{@link Task} interface.
*/
public class BatchTask implements Task{
// for logging
private static final LOGGER log = new LOGGER(BatchTask.class.getSimpleName(), false);
private final LinkedBlockingQueue<Task> tasks;
private final int maxSize;
public BatchTask(int maxSize) {
this.maxSize = maxSize;
this.tasks = new LinkedBlockingQueue<>();
}
public int size() {
return this.tasks.size();
}
public int maxSize() {
return this.maxSize;
}
public void addTask(Task t) throws InterruptedException {
this.tasks.put(t);
}
@Override
public void execute() {
log.info("Total tasks in this batch: "+ tasks.size());
for (Task t : tasks) {
t.execute();
}
}
}
| 26.875
| 117
| 0.709302
|
520d9a4fcfb3147712a47d96412acd8d4eddfa1b
| 2,563
|
package cn.mcmod.sakura.block.crops;
import cn.mcmod.sakura.block.BlockRegistry;
import cn.mcmod.sakura.item.ItemRegistry;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.CropBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
public class RiceCrop extends CropBlock {
public static final IntegerProperty RICE_AGE = BlockStateProperties.AGE_7;
private static final VoxelShape[] SHAPE_BY_AGE = new VoxelShape[] { Block.box(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D),
Block.box(0.0D, 0.0D, 0.0D, 16.0D, 4.0D, 16.0D), Block.box(0.0D, 0.0D, 0.0D, 16.0D, 6.0D, 16.0D),
Block.box(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D), Block.box(0.0D, 0.0D, 0.0D, 16.0D, 10.0D, 16.0D),
Block.box(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D), Block.box(0.0D, 0.0D, 0.0D, 16.0D, 14.0D, 16.0D),
Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D) };
public RiceCrop(Properties properties) {
super(properties);
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {
return SHAPE_BY_AGE[state.getValue(this.getAgeProperty())];
}
@Override
public IntegerProperty getAgeProperty() {
return RICE_AGE;
}
@Override
protected ItemLike getBaseSeedId() {
return ItemRegistry.RICE_SEEDS.get();
}
@Override
public int getMaxAge() {
return 7;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(RICE_AGE);
}
@Override
public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {
return (worldIn.getRawBrightness(pos, 0) >= 8 || worldIn.canSeeSky(pos))
&& worldIn.getBlockState(pos.below()).is(BlockRegistry.RICE_CROP_ROOT.get());
}
@Override
protected boolean mayPlaceOn(BlockState state, BlockGetter worldIn, BlockPos pos) {
return state.is(BlockRegistry.RICE_CROP_ROOT.get());
}
}
| 38.253731
| 120
| 0.704253
|
b39acd8da1d10b9d85ad35fe76167d13b8e4d78a
| 9,741
|
package com.scriptsbundle.adforest.home;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.scriptsbundle.adforest.R;
import com.scriptsbundle.adforest.adapters.ItemLocationAdapter;
import com.scriptsbundle.adforest.helper.GridSpacingItemDecoration;
import com.scriptsbundle.adforest.helper.ItemLocationOnclicklistener;
import com.scriptsbundle.adforest.home.helper.ChooseLocationModel;
import com.scriptsbundle.adforest.utills.AnalyticsTrackers;
import com.scriptsbundle.adforest.utills.Network.RestService;
import com.scriptsbundle.adforest.utills.SettingsMain;
import com.scriptsbundle.adforest.utills.UrlController;
public class ChooseLocationFragment extends Fragment {
public ChooseLocationFragment() {
// Required empty public constructor
}
SettingsMain settingsMain;
RelativeLayout relativeLayout;
TextView headingChooseLocation;
RecyclerView recyclerview;
static String image, title1, title2, title3, isMultiLine, MainHeading;
static JSONArray siteLocations;
List<ChooseLocationModel> locationModelList = new ArrayList<>();
RestService restService;
ImageButton refreshlocation;
SwipeRefreshLayout swipeRefreshLayout;
static TextView emptyView;
ChooseLocationModel chooseLocationModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static void setData(String title1, JSONArray jsonArray) {
ChooseLocationFragment.title1 = title1;
ChooseLocationFragment.siteLocations = jsonArray;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_location_layout, container, false);
settingsMain = new SettingsMain(getActivity());
if (settingsMain.getAppOpen()) {
restService = UrlController.createService(RestService.class);
} else
restService = UrlController.createService(RestService.class, settingsMain.getUserEmail(), settingsMain.getUserPassword(), getActivity());
relativeLayout = view.findViewById(R.id.location_activiy);
recyclerview = view.findViewById(R.id.recyclerview_choose_location);
recyclerview.setHasFixedSize(true);
recyclerview.setNestedScrollingEnabled(false);
ViewCompat.setNestedScrollingEnabled(recyclerview, false);
GridLayoutManager MyLayoutManager = new GridLayoutManager(getActivity(), 1);
MyLayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerview.setLayoutManager(MyLayoutManager);
int spacing = 0; // 50px
recyclerview.addItemDecoration(new GridSpacingItemDecoration(1, spacing, false));
adforest_setAllLocations();
SwipeRefreshLayout swipeRefreshLayout = getActivity().findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setEnabled(false);
return view;
}
private void adforest_setAllLocations() {
ItemLocationAdapter adapter = new ItemLocationAdapter(getActivity(), locationModelList);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
locationModelList.clear();
getActivity().setTitle(title1);
for (int i = 0; i < siteLocations.length(); i++) {
ChooseLocationModel chooseLocationModel = new ChooseLocationModel();
JSONObject jsonObject = null;
try {
jsonObject = siteLocations.getJSONObject(i);
chooseLocationModel.setLocationId(jsonObject.getString("location_id"));
chooseLocationModel.setTitle(jsonObject.getString("location_name"));
locationModelList.add(chooseLocationModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setItemLocationOnclicklistener(new ItemLocationOnclicklistener() {
@Override
public void onItemClick(ChooseLocationModel chooseLocationModel) {
adforest_PostLocationId(chooseLocationModel.getLocationId());
}
});
// refreshlocation.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// ChooseLocationModel chooseLocationModel = new ChooseLocationModel();
// chooseLocationModel.getLocationId();
// ChooseLocationFragment chooseLocationFragment = new ChooseLocationFragment();
// replaceFragment(chooseLocationFragment, "ChooseLocationFragment");
// Toast.makeText(getActivity(), "dkhaday", Toast.LENGTH_SHORT).show();
// adapter.notifyDataSetChanged();
// locationModelList.clear();
//// if (locationModelList == null) {
//// recyclerview.setVisibility(View.GONE);
//// emptyView = new TextView(getActivity());
//// emptyView.setVisibility(View.VISIBLE);
//// emptyView.setText("NO Data/Location has been cleared");
//// }
// }
// }
// );
}
public void adforest_PostLocationId(String locationId) {
if (SettingsMain.isConnectingToInternet(getActivity())) {
SettingsMain.showDilog(getActivity());
JsonObject params = new JsonObject();
params.addProperty("location_id", locationId);
Log.d("info post LocationId", "" + params.toString());
Call<ResponseBody> mycall2 = restService.postLocationID(params, UrlController.AddHeaders(getActivity()));
Log.d("resSErvice", restService.toString());
mycall2.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj) {
if (responseObj.isSuccessful()) {
Log.d("info location Resp", "" + responseObj.toString());
JSONObject response = null;
try {
response = new JSONObject(responseObj.body().string());
if (response.getBoolean("success")) {
Toast.makeText(getActivity(), response.get("message").toString(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), HomeActivity.class);
settingsMain.setLocationChanged(true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
getActivity().finish();
}
SettingsMain.hideDilog();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
public void replaceFragment(Fragment someFragment, String tag) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.right_enter, R.anim.left_out, R.anim.left_enter, R.anim.right_out);
transaction.replace(R.id.frameContainer, someFragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
}
@Override
public void onResume() {
try {
if (settingsMain.getAnalyticsShow() && !settingsMain.getAnalyticsId().equals(""))
AnalyticsTrackers.getInstance().trackScreenView("ChooseLocation");
super.onResume();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
| 43.681614
| 178
| 0.616261
|
555ec7efadc659c8478c329b3bfbdf63f7e236bf
| 211
|
package ru.protei.system.devices;
import ru.protei.system.inspection.ServerStatus;
public class SmallDevice extends Device {
public ServerStatus getStatus() {
return ServerStatus.ONLINE;
}
}
| 17.583333
| 48
| 0.739336
|
28cea3b7b47b7ca577d040ef281dee5f772e3117
| 529
|
package com.dlink.parser;
/**
* UpdateSqlParser
*
* @author wenmo
* @since 2021/6/14 16:52
*/
public class UpdateSqlParser extends BaseSingleSqlParser {
public UpdateSqlParser(String originalSql) {
super(originalSql);
}
@Override
protected void initializeSegments() {
segments.add(new SqlSegment("(update)(.+)(set)", "[,]"));
segments.add(new SqlSegment("(set)(.+?)( where | ENDOFSQL)", "[,]"));
segments.add(new SqlSegment("(where)(.+)(ENDOFSQL)", "(and|or)"));
}
}
| 22.041667
| 77
| 0.610586
|
1813e12015f422138fbfbea0d5b3b2131f7ce3fd
| 7,432
|
package org.firstinspires.ftc.teamcode;
import android.util.Log;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.TouchSensor;
import com.qualcomm.robotcore.hardware.UltrasonicSensor;
import com.qualcomm.robotcore.hardware.VoltageSensor;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import java.util.Iterator;
@TeleOp(name="Teleop", group="4507")
@Disabled
public class TeleOp4507 extends OpMode {
enum Kick {DELAYSTART, DELAYEND, KICKSTART, KICKEND, IDLE}
enum Index {DELAYSTART, DELAYEND, INDEXSTART, INDEXEND, IDLE}
Kick currentK;
Kick nextK;
Kick chooseK;
long nowK;
long delayUntilK;
long delayTimeK;
Index currentI;
Index nextI;
Index chooseI;
long nowI;
long delayUntilI;
long delayTimeI;
DcMotor leftDrive;
DcMotor rightDrive;
DcMotor kicker;
DcMotor sweeper;
DcMotor capper;
Servo indexer;
Servo beaconPusher;
Servo capBallLock;
TouchSensor kickerStop;
TouchSensor indexStart;
static final int NUM_MOTOR_CONTROLLERS = 3;
double[] minV = new double[NUM_MOTOR_CONTROLLERS];
// double[] maxV = new double[NUM_MOTOR_CONTROLLERS];
@Override
public void init() {
currentK = Kick.IDLE;
nextK = Kick.IDLE;
chooseK = Kick.IDLE;
currentI = Index.IDLE;
nextI = Index.IDLE;
chooseI = Index.IDLE;
leftDrive = hardwareMap.dcMotor.get("l");
leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightDrive = hardwareMap.dcMotor.get("r");
rightDrive.setDirection(DcMotorSimple.Direction.REVERSE);
rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
kicker = hardwareMap.dcMotor.get("kick");
kicker.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
sweeper = hardwareMap.dcMotor.get("sweep");
sweeper.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
capper = hardwareMap.dcMotor.get("cap");
capper.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
indexer = hardwareMap.servo.get("ind");
indexer.setPosition(0.35);
beaconPusher = hardwareMap.servo.get("bPu");
beaconPusher.setPosition(0.5);
capBallLock = hardwareMap.servo.get("cBL");
capBallLock.setPosition(0.92);
kickerStop = hardwareMap.touchSensor.get("kT");
indexStart = hardwareMap.touchSensor.get("iT");
Iterator<VoltageSensor> vSensorItr = hardwareMap.voltageSensor.iterator();
for (int j = 0; j < NUM_MOTOR_CONTROLLERS && vSensorItr.hasNext(); j++) {
VoltageSensor v = vSensorItr.next();
minV[j] = v.getVoltage();
Log.e("4507", String.format("minV[%d] %f", j, v.getVoltage()));
}
}
@Override
public void loop() {
double lSP = -gamepad1.left_stick_y;
double rSP = -gamepad1.right_stick_y;
double sw = gamepad2.left_stick_y;
double cap = gamepad2.right_stick_y;
lSP = Range.clip(lSP, -1.0, 1.0);
rSP = Range.clip(rSP, -1.0, 1.0);
sw = Range.clip(sw, -1.0, 1.0);
cap = Range.clip(cap, -1.0, 1.0);
if (gamepad1.dpad_up) {
lSP = 0.2;
rSP = 0.2;
} else if (gamepad1.dpad_down) {
lSP = -0.2;
rSP = -0.2;
} else if (gamepad1.dpad_right) {
lSP = -0.2;
rSP = 0.2;
} else if (gamepad1.dpad_left) {
lSP = 0.2;
rSP = -0.2;
}
if (gamepad2.a) {
sweeper.setPower(sw);
}
if (gamepad2.x && (currentK == Kick.IDLE) && (currentI == Index.IDLE) && !gamepad1.a) {
chooseI = Index.INDEXSTART;
}
if (gamepad1.a && (currentK == Kick.IDLE) && (currentI == Index.IDLE) && !gamepad2.x) {
chooseK = Kick.KICKSTART;
}
if (gamepad2.dpad_up) {
capBallLock.setPosition(0.0);
} else if (gamepad2.dpad_down) {
capBallLock.setPosition(0.63);
}
if (gamepad2.dpad_left) {
beaconPusher.setPosition(0.0);
} else if (gamepad2.dpad_right){
beaconPusher.setPosition(1.0);
} else {
beaconPusher.setPosition(0.5);
}
leftDrive.setPower(lSP);
rightDrive.setPower(rSP);
capper.setPower(cap);
switch (currentK) {
case DELAYSTART:
nowK = System.currentTimeMillis();
delayUntilK = nowK + delayTimeK;
currentK = Kick.DELAYEND;
break;
case DELAYEND:
if (System.currentTimeMillis() >= delayUntilK) {
currentK = nextK;
}
break;
case IDLE:
currentK = chooseK;
break;
case KICKSTART:
kicker.setPower(-1.0);
if (kickerStop.isPressed()) {
currentK = Kick.KICKEND;
}
break;
case KICKEND:
if (!kickerStop.isPressed()) {
kicker.setPower(0.0);
currentK = Kick.IDLE;
chooseK = Kick.IDLE;
}
break;
}
switch (currentI) {
case DELAYSTART:
nowI = System.currentTimeMillis();
delayUntilI = nowI + delayTimeI;
currentI = Index.DELAYEND;
break;
case DELAYEND:
if (System.currentTimeMillis() >= delayUntilI) {
currentI = nextI;
}
break;
case IDLE:
if (indexStart.isPressed()) {
chooseI = Index.INDEXSTART;
}
currentI = chooseI;
break;
case INDEXSTART:
indexer.setPosition(0.18);
currentI = Index.DELAYSTART;
nextI = Index.INDEXEND;
delayTimeI = 300;
break;
case INDEXEND:
indexer.setPosition(0.35);
currentI = Index.IDLE;
chooseI = Index.IDLE;
break;
}
Iterator<VoltageSensor> vSensorItr = hardwareMap.voltageSensor.iterator();
for (int j = 0; j < NUM_MOTOR_CONTROLLERS && vSensorItr.hasNext(); j++) {
VoltageSensor v = vSensorItr.next();
if (v.getVoltage() < minV[j]) {
minV[j] = v.getVoltage();
Log.e("4507", String.format("minV[%d] %f", j, v.getVoltage()));
}
telemetry.addData("minV", minV[j]);
}
telemetry.addData("right", rightDrive.getCurrentPosition());
telemetry.addData("left", leftDrive.getCurrentPosition());
// telemetry.addData("kick", currentK.toString());
// telemetry.addData("index", currentI.toString());
// telemetry.addData("indexer", indexer.getPosition());
updateTelemetry(telemetry);
}
public void stop() {
}
}
| 30.838174
| 95
| 0.560011
|
27cb84fce8c08831dacec87f4942b90ac6715b1e
| 2,142
|
package com.octoperf.metrics.iis.pdh.cache;
import com.google.common.collect.ImmutableSet;
import com.octoperf.metrics.condition.IsWindows;
import com.octoperf.metrics.iis.api.cache.WebServiceCacheMetadataMetrics;
import com.octoperf.metrics.iis.pdh.IsIIS;
import com.octoperf.metrics.windows.pdh.api.PerfmonQueryService;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.experimental.FieldDefaults;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.util.Set;
import static java.lang.String.format;
import static lombok.AccessLevel.PACKAGE;
@Component
@AllArgsConstructor(access = PACKAGE)
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@Conditional({IsWindows.class, IsIIS.class})
public final class PdhWSCacheMetadataMetrics implements WebServiceCacheMetadataMetrics {
private static final String WS_CACHE = "Web Service Cache";
private static final Set<String> FORMATTED_COUNTERS = ImmutableSet.of(
"Metadata Cache Hits %"
);
@NonNull
PerfmonQueryService perfmon;
@Override
public double getCurrentMetadataCached() {
return ws("Current Metadata Cached");
}
@Override
public double getTotalFlushedMetadata() {
return ws("Total Flushed Metadata");
}
@Override
public double getTotalMetadataCached() {
return ws("Total Metadata Cached");
}
@Override
public double getMetadataCacheHits() {
return ws("Metadata Cache Hits");
}
@Override
public double getMetadataCacheMisses() {
return ws("Metadata Cache Misses");
}
@Override
public double getMetadataCacheFlushes() {
return ws("Metadata Cache Flushes");
}
@Override
public double getPercentMetadataCacheHits() {
return formatted("Metadata Cache Hits %");
}
private double ws(final String counter) {
return perfmon.getRawValue(format(WS_CACHE, counter), counter);
}
private double formatted(final String counter) {
return perfmon
.getFormattedValues(format(WS_CACHE, counter), FORMATTED_COUNTERS)
.getOrDefault(counter, 0d);
}
}
| 27.461538
| 88
| 0.764239
|
f82a49dc179d4004898ca2de969eb7aec016c575
| 1,967
|
/*
* Copyright 2015 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.timestamp;
import java.util.concurrent.atomic.AtomicLong;
/**
* In-memory implementation of timestamp service. There are a few legitimate uses for this in
* production code, but primarily this should only be used in test code.
*
* @author bdorne
*
*/
public class InMemoryTimestampService implements TimestampService, TimestampManagementService {
private final AtomicLong counter = new AtomicLong(0);
@Override
public long getFreshTimestamp() {
return counter.incrementAndGet();
}
@Override
public TimestampRange getFreshTimestamps(int timestampsToGet) {
if (timestampsToGet <= 0) {
throw new IllegalArgumentException("Argument must be positive: " + timestampsToGet);
}
long topValue = counter.addAndGet(timestampsToGet);
return TimestampRange.createInclusiveRange(topValue - timestampsToGet + 1, topValue);
}
@Override
public void fastForwardTimestamp(long currentTimestamp) {
long latestTimestampFromService = counter.get();
while (latestTimestampFromService < currentTimestamp) {
counter.compareAndSet(latestTimestampFromService, currentTimestamp);
latestTimestampFromService = counter.get();
}
}
@Override
public String ping() {
return PING_RESPONSE;
}
}
| 33.913793
| 96
| 0.71937
|
79a4775214946f144f6f191704d49e9c63990573
| 1,532
|
package Debug;
import java.util.ArrayList;
import java.util.HashMap;
import math.Vector3;
public class Registers {
HashMap<String, String> registers, turns;
public Registers(HashMap<String, String> defaults, HashMap<String, String> turns){
this.registers = defaults;
this.turns = turns;
}
public HashMap<String, String> get(){
return registers;
}
public void setPoints (HashMap<String, String> toSet){
for(String s : toSet.keySet()){
registers.put(s, toSet.get(s));
}
}
public void setPoints(ArrayList<String> map) {
for(String s : map) {
String[] sa = s.replaceAll("\\s", "").split(":");
registers.put(sa[0], sa[1]);
}
}
public void setTurns(HashMap<String, String> map){
for(String s : map.keySet()){
turns.put(s, map.get(s));
}
}
public void setTurns(ArrayList<String> map){
for(String s : map) {
String[] sa = s.replaceAll("\\s", "").split(":");
turns.put(sa[0], sa[1]);
}
}
public Vector3 getPoint(String key){
String[] s = registers.get(key).replaceAll("\\s","").split(",");
return new Vector3(Integer.valueOf(s[0]), Integer.valueOf(s[1]), Integer.valueOf(s[2]));
}
public Vector3 getTurn(String key){
String[] s = turns.get(key).replaceAll("\\s","").split(",");
return new Vector3(Integer.valueOf(s[0]), Integer.valueOf(s[1]), Integer.valueOf(s[2]));
}
}
| 27.854545
| 96
| 0.568538
|
3ac7db843cef77ac8a3c7d2ba6ac31c1bf8d5598
| 13,212
|
package bost7517.oldprojects;
import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import bost7517.AStarGraph;
import bost7517.AStarPath;
import bost7517.AgentUtils;
import bost7517.Vertex;
import spacesettlers.actions.AbstractAction;
import spacesettlers.actions.DoNothingAction;
import spacesettlers.actions.PurchaseCosts;
import spacesettlers.actions.PurchaseTypes;
import spacesettlers.clients.ImmutableTeamInfo;
import spacesettlers.clients.TeamClient;
import spacesettlers.graphics.LineGraphics;
import spacesettlers.graphics.SpacewarGraphics;
import spacesettlers.graphics.TargetGraphics;
import spacesettlers.objects.AbstractActionableObject;
import spacesettlers.objects.AbstractObject;
import spacesettlers.objects.Base;
import spacesettlers.objects.Ship;
import spacesettlers.objects.powerups.SpaceSettlersPowerupEnum;
import spacesettlers.objects.resources.ResourcePile;
import spacesettlers.simulator.Toroidal2DPhysics;
import spacesettlers.utilities.Position;
import spacesettlers.utilities.Vector2D;
/**
* Heavily inspired by clients.examples.ExampleGAClient, written by Amy McGovern.
*
* This client is a learning agent capable of maintaining functionalities from
* previous versions while adding the ability to optimize some specific numeric
* values (genes) via a genetic algorithm.
*
* @author Joshua Atkinson, Cameron Bost
* @version 0.3
*
*/
public class AtkiGAClient extends TeamClient {
private boolean exportChromosomeData = false;
private final String fitnessOutFileName = "bdsm_fit_results.csv";
private final File fitnessOut = Paths.get(fitnessOutFileName).toFile();
/**
* How large of a population to evaluate
*/
private static final int POPULATION_SIZE = 30;
/**
* Set of graphics to be displayed. Generated during each timestep.
*/
private ArrayList<SpacewarGraphics> graphicsToAdd;
/**
* Radius of graphic used for blocked grids
*/
static final int BLOCKED_GRID_GRAPHIC_RADIUS = 15;
/**
* The current policy for the team
*/
private AtkiGAChromosome currentPolicy;
/**
* The current population (either being built or being evaluated)
*/
private AtkiGAPopulation population;
/**
* How many steps each policy is evaluated for before moving to the next one
*/
static final int EVALUATION_STEPS = 100;
/**
* Current step
*/
private int steps = 0;
/**
* AStar graph object
*/
private AStarGraph graph = null;
/**
* Local variable for AStar graph grid size (pixels)
*/
static final int ASTAR_GRID_SIZE = AStarGraph.GRID_SIZE;
private int lastKnownScore = 0;
@Override
public Map<UUID, AbstractAction> getMovementStart(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects) {
// Return value, contains an action for every actionable object associated with this team.
HashMap<UUID, AbstractAction> actions = new HashMap<UUID, AbstractAction>();
// For each object associated with this team (ship(s), base(s))
for (AbstractObject actionable : actionableObjects) {
// Decide action for ship
if (actionable instanceof Ship) {
Ship ship = (Ship) actionable;
AbstractAction action = currentPolicy.getCurrentAction(space, ship);
// Commit action for this ship.
actions.put(ship.getId(), action);
}
else {
// TODO: object is Base, need logic here
actions.put(actionable.getId(), new DoNothingAction());
}
}
// Show graphics (if indicated)
if(AgentUtils.SHOW_GRAPHICS) {
showGraphics(space);
}
return actions;
}
@Override
public void getMovementEnd(Toroidal2DPhysics space, Set<AbstractActionableObject> actionableObjects) {
// Update score in population object
for(ImmutableTeamInfo ti: space.getTeamInfo()) {
if(ti.getTeamName().equals(getTeamName())) {
lastKnownScore = (int) ti.getScore();
population.updateScore(ti.getScore());
}
}
// increment the step counter
steps++;
// if the step counter is modulo evaluationSteps, then evaluate this member and move to the next one
if (steps % EVALUATION_STEPS == 0) {
// note that this method currently scores every policy as zero as this is part of
// what the student has to do
population.evaluateFitnessForCurrentMember(space);
// move to the next member of the population
currentPolicy = population.getNextMember();
if (population.isGenerationFinished()) {
// note that this is also an empty method that a student needs to fill in
population.makeNextGeneration();
currentPolicy = population.getNextMember();
}
}
}
/**
* Initialize the population by either reading it from the file or making a new one from scratch
*
* @param space
*/
@Override
public void initialize(Toroidal2DPhysics space) {
XStream xstream = new XStream();
xstream.alias("GAPopulation", AtkiGAPopulation.class);
graph = AStarGraph.getInstance(space.getHeight(), space.getWidth(), AgentUtils.DEBUG);
// try to load the population from the existing saved file. If that fails, start from scratch
try {
population = (AtkiGAPopulation) xstream.fromXML(new File(getKnowledgeFile()));
population.initMembers();
} catch (XStreamException e) {
// if you get an error, handle it other than a null pointer because
// the error will happen the first time you run
System.out.println("No existing population found - starting a new one from scratch");
population = new AtkiGAPopulation(POPULATION_SIZE, random);
}
currentPolicy = population.getCurrentMember();
}
@Override
public void shutDown(Toroidal2DPhysics space) {
/**Output Population object*/
XStream xstream = new XStream();
xstream.alias("GAPopulation", AtkiGAPopulation.class);
xstream.processAnnotations(AtkiGAPopulation.class);
try {
// if you want to compress the file, change FileOuputStream to a GZIPOutputStream
xstream.toXML(population, new FileWriter(new File(getKnowledgeFile())));
} catch (XStreamException e) {
// if you get an error, handle it somehow as it means your knowledge didn't save
System.out.println("Can't save knowledge file in shutdown ");
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
// file is missing so start from scratch (but tell the user)
System.out.println("Can't save knowledge file in shutdown ");
System.out.println(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/***/
if(exportChromosomeData) {
try(BufferedWriter fOut = new BufferedWriter(new FileWriter(fitnessOut, fitnessOut.exists()))){
fOut.write(Integer.toString(lastKnownScore));
fOut.newLine();
} catch (IOException e) {
System.err.println("<BDSM_GA.shutDown> - Failed to write fitness data to file: "+e.getMessage());
}
}
}
/******************
* Unused methods *
******************/
@Override
public Map<UUID, SpaceSettlersPowerupEnum> getPowerups(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects) {
// TODO Currently unused
return null;
}
@Override
public Map<UUID, PurchaseTypes> getTeamPurchases(Toroidal2DPhysics space,
Set<AbstractActionableObject> actionableObjects,
ResourcePile resourcesAvailable,
PurchaseCosts purchaseCosts) {
/**
* If there is enough resourcesAvailable, buy a base. Place it by finding a ship that is sufficiently
* far away from the existing bases.
*/
HashMap<UUID, PurchaseTypes> purchases = new HashMap<UUID, PurchaseTypes>();
// TODO: Determine if base is impossible to purchase, add heuristic to purchase anyway
boolean bought_base = false;
if (purchaseCosts.canAfford(PurchaseTypes.BASE, resourcesAvailable)) {
for (AbstractActionableObject actionableObject : actionableObjects) {
if (actionableObject instanceof Ship) {
Ship ship = (Ship) actionableObject;
Set<Base> bases = space.getBases();
// how far away is this ship to a base of my team?
boolean buyBase = true;
for (Base base : bases) {
if (base.getTeamName().equalsIgnoreCase(getTeamName())) {
double distance = space.findShortestDistance(ship.getPosition(), base.getPosition());
if (distance < AgentUtils.BASE_BUYING_DISTANCE) {
buyBase = false;
}
}
}
if (buyBase) {
purchases.put(ship.getId(), PurchaseTypes.BASE);
bought_base = true;
//System.out.println("Buying a base!!");
break;
}
}
}
}
// Ship Purchase
if (bought_base == false && purchaseCosts.canAfford(PurchaseTypes.SHIP, resourcesAvailable)) {
for (AbstractActionableObject actionableObject : actionableObjects) {
// TODO: What if we chose a base to spawn our ship at for a reason, instead of the first available one?
if (actionableObject instanceof Base) {
Base base = (Base) actionableObject;
purchases.put(base.getId(), PurchaseTypes.SHIP);
break;
}
}
}
return purchases;
}
/********************
* Graphics methods *
********************/
@Override
public Set<SpacewarGraphics> getGraphics() {
// If graphics are to be drawn, return them.
if(AgentUtils.SHOW_GRAPHICS)
{
HashSet<SpacewarGraphics> graphics = new HashSet<SpacewarGraphics>();
graphics.addAll(graphicsToAdd);
graphicsToAdd.clear();
return graphics;
}
return null;
}
/**
* Shows graphics for this client.
*
* @param space physics model
*/
private void showGraphics(Toroidal2DPhysics space) {
graphicsToAdd = new ArrayList<SpacewarGraphics>();
drawGrid(space);
drawSearchTree(space);
drawBlockedGrids();
}
/**
* Draws grid used by A* search algorithm.
*
* @param space physics model
*/
private void drawGrid(Toroidal2DPhysics space) {
//create columns
Position heightBottom = new Position(0,0);
Position heightTop = new Position(0,space.getHeight());
for (int i = ASTAR_GRID_SIZE; i <= space.getWidth(); i = i + ASTAR_GRID_SIZE)
{
Vector2D te = new Vector2D(0,space.getHeight());
LineGraphics t= new LineGraphics(heightBottom,heightTop,te);
heightBottom = new Position(i,0);
heightTop = new Position(i,space.getHeight());
t.setLineColor(Color.gray);
graphicsToAdd.add(t);
}
heightBottom = new Position(0,0);
heightTop = new Position(space.getWidth(),0);
for (int i = ASTAR_GRID_SIZE; i <= space.getHeight(); i = i + ASTAR_GRID_SIZE)
{
Vector2D te = new Vector2D(space.getWidth(),0);
LineGraphics t= new LineGraphics(heightBottom,heightTop,te);
heightBottom = new Position(0,i);
heightTop = new Position(space.getWidth(),i);
t.setLineColor(Color.gray);
graphicsToAdd.add(t);
}
}
/**
* Draws search tree from most recent A* search.
*
* @param space physics model
*/
private void drawSearchTree(Toroidal2DPhysics space) {
LinkedList<AStarPath> currentSearchTree = currentPolicy.getCurrentSearchTree();
AStarPath currentPath = currentPolicy.getCurrentPath();
if (currentSearchTree != null) {
HashSet<LineGraphics> drawnPositions = new HashSet<>();
for (AStarPath path : currentSearchTree) {
Position prevPosition = null;
for (Position p : path.getPositions()) {
if (prevPosition != null) {
LineGraphics nextLine = new LineGraphics(prevPosition, p,
space.findShortestDistanceVector(prevPosition, p));
drawnPositions.add(nextLine);
}
prevPosition = p;
}
}
for (LineGraphics g : drawnPositions) {
graphicsToAdd.add(g);
}
}
if (currentPath != null) {
HashSet<LineGraphics> drawnPositions = new HashSet<>();
Position prevPosition = null;
for (Position p : currentPath.getPositions()) {
if (prevPosition != null) {
LineGraphics nextLine = new LineGraphics(prevPosition, p,
space.findShortestDistanceVector(prevPosition, p));
drawnPositions.add(nextLine);
}
prevPosition = p;
}
for (LineGraphics g : drawnPositions) {
g.setLineColor(Color.GREEN);
graphicsToAdd.add(g);
}
}
}
/**
* Draws all grids in A* graph that are blocked by obstacles.
*/
private void drawBlockedGrids() {
if(AgentUtils.SHOW_GRAPHICS) {
for(Vertex v: graph.getBlockedVertices()) {
SpacewarGraphics g = new TargetGraphics(BLOCKED_GRID_GRAPHIC_RADIUS, AStarGraph.getCentralCoordinate(v));
graphicsToAdd.add(g);
}
}
}
}
| 31.759615
| 110
| 0.691038
|
4be6ad26c5cf4c152e01f286d391df2fd8621deb
| 1,039
|
package com.eldarian.carina;
import com.eldarian.carina.gui.pages.SeleniumEasyFormPage;
import com.qaprosoft.carina.core.foundation.IAbstractTest;
import com.qaprosoft.carina.core.foundation.utils.R;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SimpleFormTest implements IAbstractTest {
@BeforeClass
public void replaceURL() {
R.CONFIG.put("url", "https://www.seleniumeasy.com/test/basic-first-form-demo.html");
}
@Test
public void assertMessageText() {
SeleniumEasyFormPage page = new SeleniumEasyFormPage(getDriver());
page.open();
page.closePopup();
String input = "Nabuho";
page.inputToSimple(input);
Assert.assertEquals(page.getMessage(), input);
}
@Test
public void assertSum() {
SeleniumEasyFormPage page = new SeleniumEasyFormPage(getDriver());
page.open();
page.closePopup();
page.inputValues(2,4);
page.getResult();
}
}
| 29.685714
| 92
| 0.688162
|
c53bfc9ee01ab786c52d17bffdd01ac2603bccc0
| 546
|
/*
SPDX-FileCopyrightText: (C)2021 SAP SE or an affiliate company and aas-transformation-library contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.sap.dsc.aas.lib.aml.placeholder.exceptions;
public class PlaceholderValueMissingException extends IllegalStateException {
private static final long serialVersionUID = 8550109938648946314L;
public PlaceholderValueMissingException(String placeholderName) {
super("No value for placeholder '" + placeholderName + "' was given.");
}
}
| 34.125
| 131
| 0.767399
|
a35f58f2a218205ec0d8f4a168c11b816c5a0a80
| 6,258
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package
///////////////
package com.hp.hpl.jena.graph.compose;
// Imports
///////////////
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.graph.impl.*;
import com.hp.hpl.jena.util.IteratorCollection;
import com.hp.hpl.jena.util.iterator.*;
import java.util.*;
/**
* <p>
* Base class for graphs that are composed of multiple sub-graphs. This is to provide
* a home for shared functionality that was previously in {@link Dyadic} before
* refactoring.
* </p>
*
* @author Ian Dickinson, moved kers' code from Dyadic to this class, added commentage
* @author Chris Dollin (kers)
* @version CVS $Id: CompositionBase.java,v 1.2 2009-10-06 13:04:43 ian_dickinson Exp $
*/
public abstract class CompositionBase extends GraphBase
{
/**
* <p>
* Answer a {@link Filter} that will reject any element that is a member of iterator i.
* As a side-effect, i will be closed.
* </p>
*
* @param i A closable iterator
* @return A Filter that will accept any object not a member of i.
*/
public static <T> Filter<T> reject( final ClosableIterator<? extends T> i )
{
final Set< ? extends T> suppress = IteratorCollection.iteratorToSet( i );
return new Filter<T>()
{ @Override public boolean accept( T o ) { return !suppress.contains( o ); } };
}
/**
* <p>
* Answer an iterator over the elements of iterator a that are not members of iterator b.
* As a side-effect, iterator b will be closed.
* </p>
*
* @param a An iterator that will be filtered by rejecting the elements of b
* @param b A closable iterator
* @return The iteration of elements in a but not in b.
*/
public static <T> ClosableIterator<T> butNot( final ClosableIterator<T> a, final ClosableIterator<? extends T> b )
{
return new FilterIterator<T>( reject( b ), a );
}
/**
* <p>
* Answer an iterator that will record every element delived by <code>next()</code> in
* the set <code>seen</code>.
* </p>
*
* @param i A closable iterator
* @param seen A set that will record each element of i in turn
* @return An iterator that records the elements of i.
*/
public static <T> ExtendedIterator<T> recording( final ClosableIterator<T> i, final Set<T> seen )
{
return new NiceIterator<T>()
{
@Override
public void remove()
{ i.remove(); }
@Override
public boolean hasNext()
{ return i.hasNext(); }
@Override
public T next()
{ T x = i.next();
try { seen.add( x ); } catch (OutOfMemoryError e) { throw e; } return x; }
@Override
public void close()
{ i.close(); }
};
}
//static final Object absent = new Object();
/**
* <p>
* Answer an iterator over the elements of iterator i that are not in the set <code>seen</code>.
* </p>
*
* @param i An extended iterator
* @param seen A set of objects
* @return An iterator over the elements of i that are not in the set <code>seen</code>.
*/
public static ExtendedIterator<Triple> rejecting( final ExtendedIterator<Triple> i, final Set<Triple> seen )
{
Filter<Triple> seenFilter = new Filter<Triple>()
{ @Override
public boolean accept( Triple x ) { return seen.contains( x ); } };
return i.filterDrop( seenFilter );
}
/**
Answer an iterator over the elements of <code>i</code> that are not in
the graph <code>seen</code>.
*/
public static ExtendedIterator<Triple> rejecting( final ExtendedIterator<Triple> i, final Graph seen )
{
Filter<Triple> seenFilter = new Filter<Triple>()
{ @Override public boolean accept( Triple x ) { return seen.contains( x ); } };
return i.filterDrop( seenFilter );
}
/**
* <p>
* Answer a {@link Filter} that will accept any object that is an element of
* iterator i. As a side-effect, i will be evaluated and closed.
* </p>
*
* @param i A closable iterator
* @return A Filter that will accept any object in iterator i.
*/
public static <T> Filter<T> ifIn( final ClosableIterator<T> i )
{
final Set<T> allow = IteratorCollection.iteratorToSet( i );
return new Filter<T>()
{ @Override public boolean accept( T x ) { return allow.contains( x ); } };
}
/**
* <p>
* Answer a {@link Filter} that will accept any triple that is an edge of
* graph g.
* </p>
*
* @param g A graph
* @return A Filter that will accept any triple that is an edge in g.
*/
public static Filter<Triple> ifIn( final Graph g )
{
return new Filter<Triple>()
{ @Override public boolean accept( Triple x ) { return g.contains( x ); } };
}
// Internal implementation methods
//////////////////////////////////
//==============================================================================
// Inner class definitions
//==============================================================================
}
| 34.196721
| 118
| 0.576542
|
9afa1b583fb473238a3da03af595a3043169d794
| 309
|
package schema.creation.abstractFactory.dao.product;
import schema.creation.abstractFactory.bean.Product;
/**
* Created by forgot on 2017/6/18.
*/
public interface IProductDao {
void addProduct(Product product);
void removeProduct(Product product);
Product getProduct(String productName);
}
| 20.6
| 52
| 0.760518
|
a2b967c1788f7d8ffa08cf7a39b2555521f64bda
| 19,277
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.minventario.vistas;
import com.minventario.modelos.algoritmos.Politica;
import com.minventario.modelos.tablas.TablaProbabilidad;
import com.minventario.modelos.variables.InventarioBase;
import java.awt.Color;
import java.text.DecimalFormat;
import java.util.ArrayList;
/**
*
* @author cisco
*/
public class VistaResultados extends javax.swing.JFrame {
private InventarioBase inventario;
private ArrayList<TablaProbabilidad> demanda = new ArrayList<>();
private ArrayList<TablaProbabilidad> entrega= new ArrayList<>();
private ArrayList<TablaProbabilidad> espera= new ArrayList<>();
private ArrayList<Integer> demandaNumerosAleatorios;
private ArrayList<Integer> entregaNumerosAleatorios;
private ArrayList<Integer> esperaNumerosAleatorios;
/**
* Creates new form VistaResultados
*/
public VistaResultados(InventarioBase inventario, ArrayList<TablaProbabilidad> demanda,
ArrayList<TablaProbabilidad> entrega, ArrayList<TablaProbabilidad> espera,
ArrayList<Integer> demandaNumerosAleatorios, ArrayList<Integer> entregaNumerosAleatorios,
ArrayList<Integer> esperaNumerosAleatorios) {
initComponents();
String PayneGrey = "#616282";
String LowGrey = "#CCCCCC";
jTableResultados.getTableHeader().setBackground(Color.decode(PayneGrey));
jTableResultados.getTableHeader().setForeground(Color.decode(LowGrey));
this.inventario = inventario;
this.demanda = demanda;
this.entrega = entrega;
this.espera = espera;
this.demandaNumerosAleatorios = demandaNumerosAleatorios;
this.entregaNumerosAleatorios = entregaNumerosAleatorios;
this.esperaNumerosAleatorios = esperaNumerosAleatorios;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTableResultados = new javax.swing.JTable();
jLabel9 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel3 = new javax.swing.JLabel();
jTextFieldCostoFaltante = new javax.swing.JTextField();
jTextFieldQ = new javax.swing.JTextField();
jTextFieldCostoInventario = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextFieldCostoOrdenar = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jTextFieldCostoTotal = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jTextFieldCostoCompra = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jTextFieldR = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(42, 42, 54));
jPanel1.setBackground(new java.awt.Color(42, 42, 54));
jScrollPane1.setBackground(new java.awt.Color(95, 80, 107));
jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 102, 153)));
jTableResultados.setBackground(new java.awt.Color(95, 80, 107));
jTableResultados.setForeground(new java.awt.Color(204, 204, 204));
jTableResultados.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Q", "R", "Costo Compra", "Costo Faltante", "Costo Ordenar", "Costo Inventario", "Costo Total"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableResultados.setFillsViewportHeight(true);
jTableResultados.setSelectionBackground(new java.awt.Color(117, 72, 94));
jTableResultados.setSelectionForeground(new java.awt.Color(204, 204, 204));
jScrollPane1.setViewportView(jTableResultados);
if (jTableResultados.getColumnModel().getColumnCount() > 0) {
jTableResultados.getColumnModel().getColumn(2).setResizable(false);
}
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel9.setForeground(new java.awt.Color(118, 132, 158));
jLabel9.setText("MInventario");
jLabel1.setForeground(new java.awt.Color(118, 132, 158));
jLabel1.setText("Cantidades optimas");
jLabel2.setForeground(new java.awt.Color(118, 132, 158));
jLabel2.setText("Costo Compra");
jLabel3.setForeground(new java.awt.Color(118, 132, 158));
jLabel3.setText("Costo Faltante");
jTextFieldCostoFaltante.setEditable(false);
jTextFieldCostoFaltante.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldCostoFaltante.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldCostoFaltante.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jTextFieldQ.setEditable(false);
jTextFieldQ.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldQ.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldQ.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jTextFieldCostoInventario.setEditable(false);
jTextFieldCostoInventario.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldCostoInventario.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldCostoInventario.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jLabel4.setForeground(new java.awt.Color(118, 132, 158));
jLabel4.setText("Costo Ordenar");
jLabel5.setForeground(new java.awt.Color(118, 132, 158));
jLabel5.setText("Costo Inventario");
jTextFieldCostoOrdenar.setEditable(false);
jTextFieldCostoOrdenar.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldCostoOrdenar.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldCostoOrdenar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setForeground(new java.awt.Color(118, 132, 158));
jLabel6.setText("Costo Total:");
jTextFieldCostoTotal.setEditable(false);
jTextFieldCostoTotal.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldCostoTotal.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldCostoTotal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jLabel7.setForeground(new java.awt.Color(118, 132, 158));
jLabel7.setText("Q");
jTextFieldCostoCompra.setEditable(false);
jTextFieldCostoCompra.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldCostoCompra.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldCostoCompra.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
jLabel8.setForeground(new java.awt.Color(118, 132, 158));
jLabel8.setText("R");
jTextFieldR.setEditable(false);
jTextFieldR.setBackground(new java.awt.Color(117, 72, 94));
jTextFieldR.setForeground(new java.awt.Color(204, 204, 204));
jTextFieldR.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(71, 0, 36)));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 741, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(264, 264, 264)
.addComponent(jLabel9))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldQ, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldR, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 721, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 721, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextFieldCostoCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldCostoOrdenar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextFieldCostoFaltante, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldCostoInventario, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldCostoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 473, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(3, 3, 3)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jTextFieldQ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(jTextFieldR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jTextFieldCostoOrdenar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCostoCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldCostoFaltante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jTextFieldCostoInventario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextFieldCostoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(22, Short.MAX_VALUE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void rellenarVista() {
DecimalFormat df2 = new DecimalFormat("#.##");
Politica pol = new Politica();
pol.obtenerValoresOptimos(inventario, demanda, entrega, espera,
demandaNumerosAleatorios, entregaNumerosAleatorios, esperaNumerosAleatorios);
jTextFieldQ.setText("" + pol.getqIdeal());
jTextFieldR.setText("" + pol.getrIdeal());
jTextFieldCostoCompra.setText(df2.format(pol.getResultadosOptimos().getCostoCompra()));
jTextFieldCostoFaltante.setText(df2.format(pol.getResultadosOptimos().getCostoFaltante()));
jTextFieldCostoInventario.setText(df2.format(pol.getResultadosOptimos().getCostoInventario()));
jTextFieldCostoOrdenar.setText(df2.format(pol.getResultadosOptimos().getCostoOrdenar()));
jTextFieldCostoTotal.setText(df2.format(pol.getResultadosOptimos().getCostoTotal()));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
public static javax.swing.JTable jTableResultados;
private javax.swing.JTextField jTextFieldCostoCompra;
private javax.swing.JTextField jTextFieldCostoFaltante;
private javax.swing.JTextField jTextFieldCostoInventario;
private javax.swing.JTextField jTextFieldCostoOrdenar;
private javax.swing.JTextField jTextFieldCostoTotal;
private javax.swing.JTextField jTextFieldQ;
private javax.swing.JTextField jTextFieldR;
// End of variables declaration//GEN-END:variables
}
| 58.95107
| 192
| 0.661462
|
35e6e3c27d9b7ae09cd913f529d69ed56fde43b6
| 120
|
package builder.components.wheels;
import builder.components.Details;
public abstract class Wheel extends Details{
}
| 15
| 44
| 0.816667
|
dfd9aabda28823176d619c80f86c8158ea07efd4
| 6,148
|
import java.util.Arrays;
public class ChatonsPhotos {
public static void main(String[] args) {
// Tableau contenant les votes de chaque chaton
int[] votes = new int[10];
// Nombre de votants total
int nombreVotants = 0;
// Tableau avec les surnoms de chaque chaton
String[] chatons = {
"Rondoudou",
"Ronflex",
"Bulbizarre",
"Salamèche",
"Pikachu",
"Ramoloss",
"Dracaufeu"
};
// Tableau avec les images de chaque chaton
String[] images = {
"rondoudou.jpg",
"ronflex.jpg",
"bulbizarre.jpg",
"salamèche.jpg",
"pikachu.jpeg",
"ramoloss.jpg",
"dracaufeu.jpg"
};
// Boucle pour toujours proposer le menu à l'utilisateur
while (true) {
System.out.println("------------------------------");
// affichage menu
menu();
// On récupère le choix de l'utilisateur sur le menu
int choixUtilisateur = Terminal.lireInt();
// Selon le choix de l'utilisateur on execute la fonction correspondant au numero de choix
switch (choixUtilisateur) {
default:
case 1:
AfficheChatons(images);
break;
case 2:
AfficheChatonsParNote(votes, images);
break;
case 3:
AfficherNoteChaton(votes, nombreVotants);
break;
case 4:
AjouteNoteChaton(votes);
// A chaque ajout d'une note on incrémente le nombre de personnes qui ont voté
nombreVotants++;
break;
case 5:
AjouterChaton(chatons);
break;
case 6:
RetirerChaton(chatons);
break;
case 7:
QuitterProgramme();
break;
}
}
}
private static void AfficheChatons(String[] images) {
// On boucle sur chaque images de chaton
for (String image : images) {
// On utilise un try/catch pour eviter de tout casser si le fichier n'est pas trouvé
try {
// On affiche l'image du chaton
AfficheImage.afficheImage(image);
// On attend que l'utilisateur appuie sur Entrée avant de fermer l'image
Terminal.lireString();
AfficheImage.fermeImage();
} catch(ImageNonTrouvee exc) {
System.out.println("Image non trouvée: " + images);
}
}
}
private static void AfficheChatonsParNote(int[] votes, String[] images) {
String[] imagesChatonsParNote = images;
// On trie le tableau des images des chatons en fonctions des votes
int n = imagesChatonsParNote.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (votes[j] > votes[j+1])
{
String temp = imagesChatonsParNote[j];
imagesChatonsParNote[j] = imagesChatonsParNote[j+1];
imagesChatonsParNote[j+1] = temp;
}
}
}
// On affiche les images ordonneés
AfficheChatons(imagesChatonsParNote);
}
private static void AfficherNoteChaton(int[] votes, int nombreVotants) {
System.out.println("Saisir le n° du chaton pour voir sa note :");
int numeroChaton = Terminal.lireInt();
// On retrouve le vote pour le chaton grâce à son numéro et l'indice dans le tableau des votes
int nombreVotes = votes[numeroChaton];
// Si le chaton n'a pas encore de vote on affiche un message
if (nombreVotes == 0) {
System.out.println("Pas de vote pour ce chaton");
return;
}
// On divise la note par le nombre de personne ayant voté puis on arrondi à la moyenne entier
double moyenne = nombreVotes/nombreVotants;
int moyenneArrondi = (int) Math.round(moyenne);
System.out.println(moyenneArrondi);
}
private static void AjouteNoteChaton(int[] votes) {
System.out.println("Pour quel chaton votez vous ? (saisir son n°) :");
int numeroChaton = Terminal.lireInt();
// On ajoute de 1 vote pour le chaton sur le tableau des votes
votes[numeroChaton]++;
}
private static void RetirerChaton(String[] chatons) {
System.out.println("N° du chaton à retirer :");
int numeroChaton = Terminal.lireInt();
// On vérifie qu'on ne supprime pas en dessous de 5 chatons
if (chatons.length > 5) {
// On enlève le chaton du tableau
System.arraycopy(chatons, numeroChaton + 1, chatons, numeroChaton, chatons.length - 1 - numeroChaton);
} else {
Terminal.ecrireException(new Exception("Pas possible d'avoir moins de 5 chatons"));
}
}
private static void AjouterChaton(String[] chatons) {
System.out.println("Surnom du chaton à ajouter :");
String surnomChaton = Terminal.lireString();
// On ajoute un chaton seulement si le tableau n'a pas déjà 10 chatons
if (chatons.length <= 10) {
// Pour ajouter un chaton, on crée une nouvelle liste plus grande d'un élément
String[] nouvelleListeChatons = new String[chatons.length + 1];
// On recopie tous les chatons du tableau "chatons" dans la nouvelle liste
for (int i = 0; i < chatons.length; i++) {
nouvelleListeChatons[i] = chatons[i];
}
// A La fin de la nouvelle liste on vient rajouter le nouveau chaton
nouvelleListeChatons[nouvelleListeChatons.length-1] = surnomChaton;
// On remplace l'ancienne liste de chatons par la nouvelle
chatons = nouvelleListeChatons;
} else {
Terminal.ecrireException(new Exception("Pas possible d'ajouter plus de 10 chatons"));
}
}
private static void QuitterProgramme() {
System.exit(0);
}
// affichage menu
public static void menu() {
System.out.println("1: afficher les chatons dans l'ordre des numéros.");
System.out.println("2: afficher les chatons par note.");
System.out.println("3: afficher la note pour un chaton.");
System.out.println("4: ajouter une note pour un chaton.");
System.out.println("5: retirer un chaton de la liste des candidats.");
System.out.println("6: ajouter un chaton à la liste des candidats.");
System.out.println("7: quitter le programme.");
System.out.print("Votre choix : ");
}
}
| 31.367347
| 108
| 0.626383
|
4c4263b04d2f0699b01c08f35ef9d20425c01f6a
| 2,699
|
package com.jsoniter.output;
import com.jsoniter.spi.TypeLiteral;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestNested extends TestCase {
private ByteArrayOutputStream baos;
private JsonStream stream;
public void setUp() {
baos = new ByteArrayOutputStream();
stream = new JsonStream(baos, 4096);
}
public static class TestObject1 {
public String field1;
public String field2;
}
public void test_array_of_objects() throws IOException {
TestObject1 obj1 = new TestObject1();
obj1.field1 = "1";
obj1.field2 = "2";
stream.writeVal(new TestObject1[]{obj1});
stream.close();
assertEquals("[{'field1':'1','field2':'2'}]".replace('\'', '"'), baos.toString());
}
public void test_collection_of_objects() throws IOException {
final TestObject1 obj1 = new TestObject1();
obj1.field1 = "1";
obj1.field2 = "2";
stream.writeVal(new TypeLiteral<List<TestObject1>>() {
}, new ArrayList() {{
add(obj1);
}});
stream.close();
assertEquals("[{'field1':'1','field2':'2'}]".replace('\'', '"'), baos.toString());
}
public static class TestObject2 {
public TestObject1[] objs;
}
public void test_object_of_array() throws IOException {
stream.indentionStep = 2;
TestObject2 obj = new TestObject2();
obj.objs = new TestObject1[1];
obj.objs[0] = new TestObject1();
obj.objs[0].field1 = "1";
obj.objs[0].field2 = "2";
stream.writeVal(obj);
stream.close();
assertEquals("{\n" +
" \"objs\":[\n" +
" {\n" +
" \"field1\":\"1\",\n" +
" \"field2\":\"2\"\n" +
" }\n" +
" ]\n" +
"}".replace('\'', '"'), baos.toString());
}
public void test_map_of_objects() throws IOException {
stream.indentionStep = 2;
final TestObject1 obj1 = new TestObject1();
obj1.field1 = "1";
obj1.field2 = "2";
stream.writeVal(new TypeLiteral<Map<String, TestObject1>>() {
}, new HashMap() {{
put("hello", obj1);
}});
stream.close();
assertEquals("{\n" +
" \"hello\":{\n" +
" \"field1\":\"1\",\n" +
" \"field2\":\"2\"\n" +
" }\n" +
"}".replace('\'', '"'), baos.toString());
}
}
| 29.988889
| 90
| 0.525009
|
27a06c109bbbecd2140402eb29fc48bf7219e947
| 481
|
package com.zookeeper.client.zkclient;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
/**
* @author Wang danning
* @since 2020-02-21 23:24
**/
public class ZkClientWatchTest {
public static void main(String[] args) {
ZkClient zkClient = new ZkClient("localhost:2181",
10000,
10000,
new SerializableSerializer());
zkClient.writeData("/data", 999);
}
}
| 22.904762
| 60
| 0.642412
|
82e49a25e2855251278cf70547926050cbac7155
| 1,183
|
/*
* 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 io.trino.testing.datatype;
import org.testng.annotations.Test;
import java.time.LocalTime;
import static io.trino.testing.datatype.DataType.timeDataType;
import static org.testng.Assert.assertEquals;
public class TestDataType
{
@Test
public void testTimeDataType()
{
assertEquals(timeDataType(0).toLiteral(LocalTime.of(23, 59, 59, 0)), "TIME '23:59:59'");
assertEquals(timeDataType(3).toLiteral(LocalTime.of(23, 59, 59, 999_000_000)), "TIME '23:59:59.999'");
assertEquals(timeDataType(6).toLiteral(LocalTime.of(23, 59, 59, 999_999_000)), "TIME '23:59:59.999999'");
}
}
| 35.848485
| 113
| 0.72612
|
d19c5ae7bbf1f855626d27ca32bb818a48f672de
| 17,056
|
package simplied.katara;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import qa.qcri.katara.dbcommon.Table;
import qa.qcri.katara.dbcommon.Tuple;
import qa.qcri.katara.kbcommon.KBReader;
import qa.qcri.katara.kbcommon.KnowledgeDatabaseConfig;
import qa.qcri.katara.kbcommon.pattern.simple.TableSemantics;
import org.apache.commons.lang3.StringUtils;
public class SimplifiedPatternDiscovery {
Table table;
KBReader reader;
static String repairvalue="";
Scanner scan =new Scanner(System.in);
//This is the result
Map<String,String> col2TypeRel = new HashMap<String,String>();
Map<String,Set<Tuple>> col2SupportingTuples = new HashMap<String,Set<Tuple>>();
public SimplifiedPatternDiscovery(Table table, KBReader reader, String domainSpecifciKBDir){
this.table = table;
this.reader = reader;
if(domainSpecifciKBDir != null){
try {
usingDomainSpecificKB(domainSpecifciKBDir,true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println("if there is no kb is still work");
if(true){
return;
}
PatternGenerationTFIDF tfidf = new PatternGenerationTFIDF(reader,table);
//get the type of columns
System.out.println("Get the candidate type of columns..." );
for (int col = 0; col < table.getNumCols(); col++) {
//if covered, skip
if(domainSpecificCoveredColumns.contains(col))
continue;
Map<String, Set<Tuple>> result = tfidf.getCandidateTypes(col);
final String colFinal = String.valueOf(col);
final Map<String,Double> type2Score = tfidf.setCandidateTypeScore(colFinal, result);
ArrayList<String> typesRanked = new ArrayList<String>(
result.keySet());
// Limit the size of each list
ArrayList<String> typesRankedLimit = new ArrayList<String>();
for (int i = 0; i < typesRanked.size(); i++) {
String type = typesRanked.get(i);
double sup = (double) result.get(type).size()
/ table.getNumRows();
if (sup >= KnowledgeDatabaseConfig.frequentPercentage) {
typesRankedLimit.add(type);
}
if(typesRankedLimit.size() > 2)
break;
}
if (typesRankedLimit.isEmpty()) {
continue; // If the candidate set is empty, do not add it to
// ranked list
}
Collections.sort(typesRankedLimit, new Comparator<String>() {
public int compare(String arg0, String arg1) {
if (type2Score.get(arg0) > type2Score.get(arg1))
return -1;
else if (type2Score.get(arg0) < type2Score.get(arg1))
return 1;
/*else
return 0;*/
else if (RankJoinKBStats.moreSpecificType(arg0, arg1)) {
return -1;
} else
return 1;
}
});
String type = user_verification_column_type(col,typesRankedLimit);
if(type != null){
col2TypeRel.put(colFinal, type);
col2SupportingTuples.put(colFinal, result.get(type));
}
}
//get relationship between column pairs
System.out.println("Get the relationship between column pairs..." );
if(true){
return;
}
for (int col1 = 0; col1 < table.getNumCols(); col1++) {
for (int col2 = col1 + 1; col2 < table.getNumCols(); col2++) {
// get the candidate rels, and the supporting type
if(domainSpecificCoveredColumns.contains(col1) && domainSpecificCoveredColumns.contains(col2))
continue;
Map<String, Set<Tuple>> result = tfidf.getCandidateRels(col1, col2);
final String colFinal = col1 + "," + col2;
if (result.isEmpty()) {
continue; // If the candidate rel for a column pair is
// empty, do not add it
}
// set the score of each candidate rels
final Map<String,Double> rel2Score = tfidf.setCandidateRelScore(colFinal, result);
// rank the candidat rel based on the score
ArrayList<String> relsRanked = new ArrayList<String>(
result.keySet());
// limit the size of each rel
ArrayList<String> relsRankedLimit = new ArrayList<String>();
for (int i = 0; i < relsRanked.size(); i++) {
String rel = relsRanked.get(i);
double sup = (double) result
.get(rel).size()
/ table.getNumRows();
// double score = col2Rel2Score.get(col1 + "," +
// col2).get(rel);
if (sup >= KnowledgeDatabaseConfig.frequentPercentage) {
relsRankedLimit.add(rel);
}
}
if (relsRankedLimit.isEmpty())
continue;
System.out.println("Columns: " + col1 + " , " + col2
+ " has # candidate rels: above minimum fre "
+ KnowledgeDatabaseConfig.frequentPercentage + " is :"
+ relsRankedLimit.size());
Collections.sort(relsRankedLimit, new Comparator<String>() {
public int compare(String arg0, String arg1) {
if (rel2Score.get(arg0) > rel2Score.get(arg1))
return -1;
else if (rel2Score.get(arg0) < rel2Score.get(arg1))
return 1;
else if (RankJoinKBStats.moreSpecificRel(arg0, arg1)) {
return -1;
} else
return 1;
}
});
String rel = user_verification_column_pair_rel(colFinal,relsRankedLimit);
if(rel != null){
col2TypeRel.put(colFinal, rel);
col2SupportingTuples.put(colFinal, result.get(rel));
}
}
}
}
public String user_verification_column_type(int col, ArrayList<String> typesRankedLimit){
System.out.println("Start User Verification for the Type of Column: " + col);
System.out.println("The types are ranked in decreasing order of likelihood");
System.out.println("Enter Y to accept this type, N to examine next type, T to terminate");
for(int i = 0; i < typesRankedLimit.size(); i++){
String type = typesRankedLimit.get(i);
System.out.println("\t Is it (Y/N/T) : " + type);
String answer = scan.nextLine();
if(answer.equalsIgnoreCase("Y")){
return type;
}else if(answer.equalsIgnoreCase("N")){
continue;
}else if(answer.equalsIgnoreCase("T")){
return null;
}else{
continue;
}
}
return null;
}
public String user_verification_column_pair_rel(String colFinal, ArrayList<String> relsRankedLimit){
System.out.println("Start User Verification for the relationship between column pair: " + colFinal);
System.out.println("The relationships are ranked in decreasing order of likelihood");
System.out.println("Enter Y to accept this, N to examine next, T to terminate");
for(int i = 0; i < relsRankedLimit.size(); i++){
String rel = relsRankedLimit.get(i);
System.out.println("\t Is it (Y/N/T) : " + rel);
String answer = scan.nextLine();
if(answer.equalsIgnoreCase("Y")){
return rel;
}else if(answer.equalsIgnoreCase("N")){
continue;
}else if(answer.equalsIgnoreCase("T")){
return null;
}else{
continue;
}
}
return null;
}
Map<String,Set<Tuple>> col2Errors = new HashMap<String,Set<Tuple>>();
Map<String,String> col2Errorsrepair = new HashMap<String,String>();
/**
* Do we allow user input for error detection
* @param userInput
*/
public void errorDetection(boolean userInput ){
for(String col: col2TypeRel.keySet()){
Set<Tuple> supportingTuples = col2SupportingTuples.get(col);
col2Errors.put(col, new HashSet<Tuple>());
if(!col.contains(",")){
String type = col2TypeRel.get(col);
Set<String> supportingValues = new HashSet<String>();
for(Tuple t: table.getTuples()){
if(supportingTuples.contains(t)){
continue;
}else{
if(userInput){
String value = t.getCell(Integer.valueOf(col)).getValue();
if(supportingValues.contains(value))
continue;
System.out.println("Is [ " + value + " ] of type [ " + type);
String answer = scan.nextLine();
if(answer.equalsIgnoreCase("Y")){
supportingValues.add(value);
}else if(answer.equalsIgnoreCase("N")){
col2Errors.get(col).add(t);
}
}else{
col2Errors.get(col).add(t);
}
}
}
}else{
String rel = col2TypeRel.get(col);
Set<String> supportingValues = new HashSet<String>();
int col1 = Integer.valueOf(col.split(",")[0]);
int col2 = Integer.valueOf(col.split(",")[1]);
if(rel.startsWith(TableSemantics.REL_REVERSED_TAG)){
col1 = Integer.valueOf(col.split(",")[1]);
col2 = Integer.valueOf(col.split(",")[0]);
rel = rel.substring(TableSemantics.REL_REVERSED_TAG.length());
}
for(Tuple t: table.getTuples()){
if(supportingTuples.contains(t)){
continue;
}else{
if(userInput){
String value1 = t.getCell(Integer.valueOf(col1)).getValue();
String value2 = t.getCell(Integer.valueOf(col2)).getValue();
if(supportingValues.contains(value1 + "," + value2))
continue;
System.out.println("Is it true that [ " + value1 + "] " + rel + " [ " + value2 + "]" );
String answer = scan.nextLine();
if(answer.equalsIgnoreCase("Y")){
supportingValues.add(value1 + "," + value2);
}else if(answer.equalsIgnoreCase("N")){
col2Errors.get(col).add(t);
}
}else{
col2Errors.get(col).add(t);
}
}
}
}
}
}
public void print_errors(String error_file) throws IOException{
/// ------------------------------------
ICsvBeanWriter supercsvWriter = null;
// //PrintWriter out = new PrintWriter(new FileWriter(error_file));
// CSVWriter out = new CSVWriter(new FileWriter(error_file),CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
try {
supercsvWriter = new CsvBeanWriter(new FileWriter(error_file), CsvPreference.STANDARD_PREFERENCE);
final String[] nameMapping = new String[] { "row", "column", "value" };
// write the beans
for(String col: col2Errors.keySet()){
for(Tuple t: col2Errors.get(col)){
if(!col.contains(",")){
int col1 = Integer.valueOf(col);
//out.println( (t.getTid() +1 ) + "," + (col1 )+ ","+ col2Errorsrepair.get(t.getTid()+","+col1));//+1
supercsvWriter.write(new PrintableError(t.getTid()+1, col1, col2Errorsrepair.get(t.getTid()+","+col1)), nameMapping);
// out.writeNext((t.getTid() +1 ) +","+ (col1 )+","+ col2Errorsrepair.get(t.getTid()+","+col1)));
//out.println("The following cell is wrong: Cell[" + t.getTid() + "]["+col+"]=" + t.getCell(Integer.valueOf(col)).getValue());
}else{
int col1 = Integer.valueOf(col.split(",")[0]);
int col2 = Integer.valueOf(col.split(",")[1]);
//out.println( (t.getTid() +1) + "," + (col1)+ ","+ col2Errorsrepair.get(t.getTid()+","+col1));//+1
//out.println( (t.getTid()+1) + "," + (col2)+ ","+ col2Errorsrepair.get(t.getTid()+","+col2));//+1
supercsvWriter.write(new PrintableError(t.getTid() +1, col1, col2Errorsrepair.get(t.getTid()+","+col1)), nameMapping);
supercsvWriter.write(new PrintableError(t.getTid() +1, col2, col2Errorsrepair.get(t.getTid()+","+col2)), nameMapping);
// out.writeNext((t.getTid() +1) +","+ (col1)+","+ col2Errorsrepair.get(t.getTid()+","+col1));
// out.writeNext((t.getTid()+1) +","+ (col2)+","+ col2Errorsrepair.get(t.getTid()+","+col2));
// out.println("There is at least one Error in the following two cells: Cell[" + t.getTid() + "]["+col1+"]=" + t.getCell(col1).getValue()
// + "\t Cell[" + t.getTid() + "]["+col2+"]=" + t.getCell(col2).getValue());
}
}
}
}
finally {
if( supercsvWriter != null ) {
supercsvWriter.close();
}
}
File file = new File(error_file);
if(file.length() == 0) {
file.delete();
System.out.println("file has been deleted");
}
}
/**
* The following is to use domain specific knowledge bases
*/
List<HashSet<String>> domainSpecificTypes = new ArrayList<HashSet<String>>();
Map<String,Map<String,String>> rel2sub2obj = new HashMap<String,Map<String,String>>();
HashSet<Integer> domainSpecificCoveredColumns = new HashSet<Integer>();
public void usingDomainSpecificKB(String kbDir, boolean ignoreCase) throws IOException{
loadDomainSpecificKB(kbDir);
for(int i = 0; i < table.getNumCols(); i++){
usingDomainSpecificKB_col_type(i,ignoreCase);
}
for(int i = 0; i < table.getNumCols(); i++)
for(int j = 0; j < table.getNumCols(); j++){
if(i == j)
continue;
usingDomainSpecificKB_colpair_rel(i,j,ignoreCase);
}
}
private void usingDomainSpecificKB_colpair_rel(int i, int j, boolean ignoreCase){
for(String rel: rel2sub2obj.keySet()){
int count = 0;
for(Tuple t: table.getTuples()){
String coli = t.getCell(i).getValue();
String colj = t.getCell(j).getValue();
if(rel2sub2obj.get(rel).containsKey(coli) && rel2sub2obj.get(rel).get(coli).equals(colj)){
count++;
}
}
double coverage = (double) count / table.getNumRows();
if(coverage >= 0.15){
HashSet<Tuple> errorTuples = new HashSet<Tuple>();
HashSet<String> errorTuplesrepair = new HashSet<String>();
//find the right domain specific type
for(Tuple t: table.getTuples()){
String coli = t.getCell(i).getValue();
String colj = t.getCell(j).getValue();
if(rel2sub2obj.get(rel).containsKey(coli) && rel2sub2obj.get(rel).get(coli).equals(colj)){
}else{
errorTuples.add(t);
// we triying to suggest the repair
if(rel2sub2obj.get(rel).containsKey(coli)) {
repairvalue=rel2sub2obj.get(rel).get(coli);
col2Errorsrepair.put(t.getTid() + "," + j,repairvalue);
}
}
}
col2Errors.put(i + "," + j, errorTuples);
}
}
}
public double compareStrings(String stringA, String stringB) {
return StringUtils.getJaroWinklerDistance(stringA, stringB);
}
private void usingDomainSpecificKB_col_type(int i, boolean ignoreCase){
List<String> values = table.getCellsinCol(i);
//check the domain KBs
int k = 0;
for(k = 0; k < domainSpecificTypes.size(); k++){
HashSet<String> domainValues = domainSpecificTypes.get(k);
HashSet<String> lowercaseDomainValues = new HashSet<String>();
for(String value: domainValues){
lowercaseDomainValues.add(value.toLowerCase());
}
int count = 0;
for(String value: values){
if(ignoreCase && lowercaseDomainValues.contains(value.toLowerCase())){
count++;
}else if(domainValues.contains(value)) {
count++;
}
}
double coverage = (double) count / values.size();
if(coverage > 0.2){
HashSet<Tuple> errorTuples = new HashSet<Tuple>();
//find the right domain specific type
for(Tuple t: table.getTuples()){
String value = t.getCell(Integer.valueOf(i)).getValue();
if(ignoreCase && lowercaseDomainValues.contains(value.toLowerCase())){
}else if(domainValues.contains(value)) {
}else{
errorTuples.add(t);
// //##################
// // we trying to report the repair
// String a = value.toLowerCase();
// double mindistance=0;
// String index="";
// int number=0;
// for (String potentialrepair:domainValues){
// String b = potentialrepair.toLowerCase();
// double ll=compareStrings(a,b);
// if (ll>=mindistance){
// mindistance=ll;
// index=potentialrepair;
// }
// }
String index="";
// index is the value that we suggest as error
col2Errorsrepair.put(t.getTid() + "," + i,index);
}
}
col2Errors.put(String.valueOf(i), errorTuples);
domainSpecificCoveredColumns.add(i);
break;
}
}
}
private void loadDomainSpecificKB(String kbDir) throws IOException{
File folder = new File(kbDir);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getAbsolutePath().endsWith(".type.txt")) {
HashSet<String> oneType = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(listOfFiles[i]));
String line = null;
while((line = reader.readLine())!=null){
oneType.add(line);
}
reader.close();
domainSpecificTypes.add(oneType);
} else if (listOfFiles[i].isFile() && listOfFiles[i].getAbsolutePath().endsWith(".rel.txt")) {
HashSet<String> oneType = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(listOfFiles[i]));
String line = null;
while((line = reader.readLine())!=null){
String[] splits = line.split("\t");
if(splits.length < 3)
continue;
String s = splits[0];
String p = splits[1];
String o = splits[2];
oneType.add(s);
if(rel2sub2obj.containsKey(p)){
rel2sub2obj.get(p).put(s, o);
}else{
HashMap<String,String> temp = new HashMap<String,String>();
temp.put(s, o);
rel2sub2obj.put(p, temp);
}
}
reader.close();
domainSpecificTypes.add(oneType);
}
else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
}
| 28.665546
| 141
| 0.644758
|
617140ca7f876793da39d335e929bbbdd1a1d69d
| 1,377
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.TreeMap;
public class PhonebookUpgrade {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
TreeMap<String,String> phonebook = new TreeMap<>();
while(!input.equals("END")){
String[] argums = input.split(" ");
String value = argums[0];
if (value.equals("A")){
String name = argums[1];
String phonenumber = argums[2];
phonebook.put(name,phonenumber);
}else if(value.equals("S")){
String name = argums[1];
if (phonebook.containsKey(name)){
System.out.printf("%s -> %s\r\n", name,phonebook.get(name));
}else{
System.out.printf("Contact %s does not exist.\r\n", name);
}
}else if (value.equals("ListAll")){
for (String key : phonebook.keySet()){
System.out.printf("%s -> %s\r\n",key, phonebook.get(key));
}
}
input = reader.readLine();
}
}
}
| 33.585366
| 86
| 0.519245
|
418b2febd802c805946b73c9a61661ffe0c7ac83
| 17,124
|
/*
* (C) Copyright IBM Corp. 2016,2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.whc.deid.providers.masking;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.ibm.whc.deid.shared.pojo.config.masking.NumberVarianceMaskingProviderConfig;
import org.junit.Test;
public class NumberVarianceMaskingProviderTest extends TestLogSetUp {
/*
* Note: In addition to default range values, also tests for 1) when limitUp is zero, 2) when
* limitDown is zero, and 3) when both limit up and down are zero (considered invalid and
* exception thrown)
*/
@Test
public void testMask() {
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider();
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble > 40.0);
assertTrue(maskedDouble < 60.0);
}
}
@Test
public void testZero() {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setMaskLimitUp(0);
configuration.setMaskLimitDown(0);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
assertEquals(value, maskedValue);
}
}
@Test
public void testLimitUpZero_LimitDownInteger() {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setMaskLimitUp(0);
configuration.setMaskLimitDown(35);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= 32.5);
assertTrue(maskedDouble <= 50.0);
// System.out.println("=======> LimitUp Zero, masked value [" +
// maskedValue + "]");
}
}
@Test
public void testLimitUpZero_LimitDownDouble() {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setMaskLimitUp(0);
configuration.setMaskLimitDown(35.5);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= 32.5);
assertTrue(maskedDouble <= 50.0);
// System.out.println("=======> LimitUp Zero, masked value [" +
// maskedValue + "]");
}
}
@Test
public void testLimitDownZero_LimitUpInteger() {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setMaskLimitUp(25);
configuration.setMaskLimitDown(0);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= 49.0);
assertTrue(maskedDouble <= 62.5);
// System.out.println("=======> LimitDwon Zero, masked value [" +
// maskedValue + "]");
}
}
@Test
public void testLimitDownZero_LimitUpDouble() {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setMaskLimitUp(25.5);
configuration.setMaskLimitDown(0);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
Double originalValue = new Double(50);
String value = originalValue.toString();
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= 49.0);
assertTrue(maskedDouble <= 62.5);
// System.out.println("=======> LimitDwon Zero, masked value [" +
// maskedValue + "]");
}
}
@Test
public void testAugmentWithNoPrecision_IntegerInput() {
Double originalValue = new Double(50);
String value = originalValue.toString();
int lowerBound = 2;
int upperBound = 4;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(false);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble == (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= originalValue + upperBound);
}
}
@Test
public void testAugmentWithNoPrecision_DoubleInput() {
Double originalValue = new Double(50.03);
String value = originalValue.toString();
double lowerBound = 2.1;
double upperBound = 4.9;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(false);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble == (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= originalValue + upperBound);
}
}
@Test
public void testAugmentWithPrecision_IntegerInput_DefaultPrecision() {
Double originalValue = new Double(50);
String value = originalValue.toString();
int lowerBound = 2;
int upperBound = 4;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
assertTrue(maskedValue.contains(".0"));
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble == (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= originalValue + upperBound + 1);
}
}
@Test
public void testAugmentWithPrecision_IntegerInput_PrecisionDigitThree() {
Double originalValue = new Double(50);
String value = originalValue.toString();
double lowerBound = 2;
double upperBound = 4;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
configuration.setPrecisionDigits(3);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
assertTrue(maskedValue.contains(".000"));
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble == (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= originalValue + upperBound + 1);
}
}
@Test
public void testAugmentWithPrecision_DoubleInput_DefaultPrecision() {
Double originalValue = new Double(50.03);
String value = originalValue.toString();
double lowerBound = 2.1;
double upperBound = 4.9;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble != (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= originalValue + upperBound + 1);
}
}
@Test
public void testAugmentWithPrecision_DoubleInput_PrecisionDigitZero() {
Double originalValue = new Double(50.03);
String value = originalValue.toString();
double lowerBound = 2.1;
double upperBound = 4.9;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
configuration.setPrecisionDigits(0);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble == (int) maskedDouble.doubleValue());
assertTrue(maskedDouble <= Math.ceil(originalValue + upperBound + 1));
}
}
@Test
public void testAugmentWithPrecision_DoubleInput_PrecisionDigitThree() {
Double originalValue = new Double(50.03);
String value = originalValue.toString();
double lowerBound = 2.1;
double upperBound = 4.9;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
configuration.setPrecisionDigits(3);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
Double maskedDouble = Double.valueOf(maskedValue);
assertTrue(maskedDouble >= originalValue);
assertTrue(maskedDouble <= Math.ceil(originalValue + upperBound + 1));
}
}
@Test
public void testAugmentWithNoPrecisionInvalidRange() {
Double originalValue = new Double(50);
String value = originalValue.toString();
int lowerBound = 2;
int upperBound = 2;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(false);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
assertNull(maskedValue);
}
}
@Test
public void testAugmentWithPrecisionInvalidRange() {
Double originalValue = new Double(50);
String value = originalValue.toString();
int lowerBound = 4;
int upperBound = 2;
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setAugmentMask(true);
configuration.setAugmentLowerBound(lowerBound);
configuration.setAugmentUpperBound(upperBound);
configuration.setResultWithPrecision(true);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
for (int i = 0; i < 100; i++) {
String maskedValue = maskingProvider.mask(value);
assertNull(maskedValue);
}
}
@Test
public void testMaskNullNumberVarianceInputReturnNull() throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = null;
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
assertEquals(null, maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
@Test
public void testMaskInvalidNumberVarianceInputValidHandlingReturnNull() throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setUnspecifiedValueHandling(1);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = "Invalid NumberVariance";
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
assertEquals(null, maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
@Test
public void testMaskInvalidNumberVarianceInputValidHandlingReturnRandom() throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setUnspecifiedValueHandling(2);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = "Invalid NumberVariance";
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
// return null for this provider
assertEquals(null, maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
@Test
public void testMaskInvalidNumberVarianceInputValidHandlingReturnDefaultCustomValue()
throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setUnspecifiedValueHandling(3);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = "Invalid NumberVariance";
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
assertEquals("OTHER", maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
@Test
public void testMaskInvalidNumberVarianceInputValidHandlingReturnNonDefaultCustomValue()
throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setUnspecifiedValueHandling(3);
configuration.setUnspecifiedValueReturnMessage("Test NumberVariance");
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = "Invalid NumberVariance";
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
assertEquals("Test NumberVariance", maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
@Test
public void testMaskInvalidNumberVarianceInputInvalidHandlingReturnNull() throws Exception {
NumberVarianceMaskingProviderConfig configuration = new NumberVarianceMaskingProviderConfig();
configuration.setUnspecifiedValueHandling(4);
MaskingProvider maskingProvider = new NumberVarianceMaskingProvider(configuration);
String invalidNumberVariance = "Invalid NumberVariance";
String maskedNumberVariance = maskingProvider.mask(invalidNumberVariance);
assertEquals(null, maskedNumberVariance);
assertThat(outContent.toString(), containsString("DEBUG - WPH1015D"));
}
}
| 40.578199
| 99
| 0.730495
|
06b1b8c88224695e56628264426e18a195f3aeea
| 6,094
|
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.abiquo.features;
import java.io.IOException;
import java.lang.reflect.Method;
import org.jclouds.abiquo.domain.CloudResources;
import org.jclouds.abiquo.domain.TemplateResources;
import org.jclouds.abiquo.functions.ReturnNullOn303;
import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
import com.abiquo.model.rest.RESTLink;
import com.abiquo.model.transport.SingleResourceTransportDto;
import com.abiquo.server.core.task.TaskDto;
import com.abiquo.server.core.task.TasksDto;
import com.google.inject.TypeLiteral;
/**
* Tests annotation parsing of {@code TaskAsyncApi}
*
* @author Ignasi Barrera
* @author Francesc Montserrat
*/
@Test(groups = "unit")
public class TaskAsyncApiTest extends BaseAbiquoAsyncApiTest<TaskAsyncApi>
{
/*********************** Task ***********************/
public void testGetTaskVirtualMachine() throws SecurityException, NoSuchMethodException,
IOException
{
Method method = TaskAsyncApi.class.getMethod("getTask", RESTLink.class);
GeneratedHttpRequest request =
processor
.createRequest(
method,
new RESTLink("task",
"http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks/169f1877-5f17-4f62-9563-974001295c54"));
assertRequestLineEquals(
request,
"GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks/169f1877-5f17-4f62-9563-974001295c54 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: " + TaskDto.BASE_MEDIA_TYPE + "\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOn303.class);
checkFilters(request);
}
public void testListTasksVirtualMachine() throws SecurityException, NoSuchMethodException,
IOException
{
Method method = TaskAsyncApi.class.getMethod("listTasks", SingleResourceTransportDto.class);
GeneratedHttpRequest request =
processor.createRequest(method, CloudResources.virtualMachinePut());
assertRequestLineEquals(
request,
"GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: " + TasksDto.BASE_MEDIA_TYPE + "\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testGetTaskVirtualMachineTemplate() throws SecurityException,
NoSuchMethodException, IOException
{
Method method = TaskAsyncApi.class.getMethod("getTask", RESTLink.class);
GeneratedHttpRequest request =
processor
.createRequest(
method,
new RESTLink("task",
"http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks/169f1877-5f17-4f62-9563-974001295c54"));
assertRequestLineEquals(
request,
"GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks/169f1877-5f17-4f62-9563-974001295c54 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: " + TaskDto.BASE_MEDIA_TYPE + "\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOn303.class);
checkFilters(request);
}
public void testListTasksVirtualMachineTemplate() throws SecurityException,
NoSuchMethodException, IOException
{
Method method = TaskAsyncApi.class.getMethod("listTasks", SingleResourceTransportDto.class);
GeneratedHttpRequest request =
processor.createRequest(method, TemplateResources.virtualMachineTemplatePut());
assertRequestLineEquals(
request,
"GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: " + TasksDto.BASE_MEDIA_TYPE + "\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
@Override
protected TypeLiteral<RestAnnotationProcessor<TaskAsyncApi>> createTypeLiteral()
{
return new TypeLiteral<RestAnnotationProcessor<TaskAsyncApi>>()
{
};
}
}
| 41.739726
| 163
| 0.714801
|
8594eeb8e68c95fc37a3fa0741665f9a08851ec9
| 895
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.core.externaltools.validators;
/**
* <p>
* Validates arguments for compare tools.
* </p>
*
* @since TEE-SDK-10.1
* @threadsafety immutable
*/
public final class CompareToolValidator extends AbstractToolValidator {
public CompareToolValidator() {
super();
}
/**
* {@inheritDoc}
*/
@Override
protected String[] getForbiddenSubstitutions() {
return new String[] {
"%3", //$NON-NLS-1$
"%4", //$NON-NLS-1$
"%8" //$NON-NLS-1$
};
}
/**
* {@inheritDoc}
*/
@Override
protected String[] getRequiredSubstitutions() {
return new String[] {
"%1", //$NON-NLS-1$
"%2" //$NON-NLS-1$
};
}
}
| 21.309524
| 74
| 0.550838
|
750805d65e71ec3672b009d27776443bbbcdd3b9
| 201
|
package com.backend.jobsity_challenge.controller;
import org.mockito.InjectMocks;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
public class OutputControllerImplTest {
}
| 20.1
| 49
| 0.820896
|
8550ad5267093a69e5ef80daefb81fea224d5c0b
| 4,898
|
package com.twu.biblioteca;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class PredefinedMenuOptionTest {
PredefinedMenuOption menu;
BibliotecaApp library = new BibliotecaApp();
Book bookProgrammingInJava = new Book("Programming in Java", "Gabriela Andrade", 2005);
Book bookProgrammingInCSharp = new Book("Programming in C#", "Gabriela Andrade", 2006);
Book bookTDD = new Book("Test Driven Development", "Gabriela Andrade", 2007);
String testOption = "Test option";
String testTitle = "Test title";
String testMessage = "Test message";
@Test
public void getRootTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
assertEquals(PredefinedMenuOption.rootMessage, option.getMessageBeforeUserInput());
}
@Test
public void getPredefinedOptionTest() {
PredefinedMenuOption option = new PredefinedMenuOption(testOption, testTitle, testMessage);
assertEquals(testOption, option.getOption());
assertEquals(testTitle, option.getTitle());
assertEquals(testMessage, option.getMessageBeforeUserInput());
}
@Test
public void returnParentOfRootOptionTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
assertNull(option.getParent());
}
@Test
public void returnParentOfOtherPredefinedOptionTest() {
PredefinedMenuOption option = new PredefinedMenuOption(testOption, testTitle, testMessage);
assertNull(option.getParent());
}
@Test
public void createQuitTest() {
PredefinedMenuOption option = PredefinedMenuOption.createQuitOption();
assertEquals(PredefinedMenuOption.quitOption, option.getOption());
assertEquals(PredefinedMenuOption.quitTitle, option.getTitle());
assertNull(option.getParent());
assertNull(option.getMessageBeforeUserInput());
}
@Test
public void createBackTest() {
PredefinedMenuOption option = PredefinedMenuOption.createBackOption();
assertEquals(PredefinedMenuOption.backOption, option.getOption());
assertEquals(PredefinedMenuOption.backTitle, option.getTitle());
assertNull(option.getParent());
assertNull(option.getMessageBeforeUserInput());
}
@Test
public void printRootOptionTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
String expected = PredefinedMenuOption.rootMessage +
"1: List Books." + "\n" +
"2: Return Books." + "\n" +
"3: List Movies." + "\n" +
"4: Return Movies." + "\n" +
PredefinedMenuOption.quitTitle;
assertEquals(expected, option.printOptions(option.generateOptions(null, null, null)));
}
@Test
public void generateOptionsFromRootTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
ArrayList<MenuOptionInterface> childOptions = option.generateOptions(null, null, null);
assertEquals("1: List Books.", childOptions.get(0).getTitle());
assertEquals("2: Return Books.", childOptions.get(1).getTitle());
assertEquals("3: List Movies.", childOptions.get(2).getTitle());
assertEquals("4: Return Movies.", childOptions.get(3).getTitle());
}
@Test
public void getOptionListBooksByUserInputTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
option.generateOptions(null, null, null);
assertEquals("Select a book to checkout.",
option.getOptionByUserInput("1", option.generateOptions(null, null, null))
.getMessageBeforeUserInput());
}
@Test
public void getOptionReturnBooksByUserInputTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
option.generateOptions(null, null, null);
assertEquals(ListItemsMenuOption.msgBooksToReturn,
option.getOptionByUserInput("2", option.generateOptions(null, null, null))
.getMessageBeforeUserInput());
}
@Test
public void getOptionListMoviesByUserInputTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
option.generateOptions(null, null, null);
assertEquals(ListItemsMenuOption.msgMoviesToCheckout,
option.getOptionByUserInput("3", option.generateOptions(null, null, null))
.getMessageBeforeUserInput());
}
@Test
public void getOptionReturnMoviesByUserInputTest() {
PredefinedMenuOption option = new PredefinedMenuOption();
option.generateOptions(null, null, null);
assertEquals(ListItemsMenuOption.msgMoviesToReturn,
option.getOptionByUserInput("4", option.generateOptions(null, null, null))
.getMessageBeforeUserInput());
}
}
| 40.479339
| 99
| 0.678849
|
aaefce5ccf6d01dad066051e079defc4e160d000
| 15,070
|
/*
* Copyright (c) Joachim Ansorg, mail@ansorg-it.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.github.antego.bashmock.lexer;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
/**
* Identifies all of the token types (at least, the ones we'll care about) in Arc.
* Used by the lexer to break a Bash source file down into tokens.
*
* @author jansorg
*/
public interface BashTokenTypes {
IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER;
// common types
IElementType WHITESPACE = TokenType.WHITE_SPACE;
TokenSet whitespaceTokens = TokenSet.create(WHITESPACE);
IElementType ARITH_NUMBER = new BashElementType("number");
IElementType WORD = new BashElementType("word");
IElementType ASSIGNMENT_WORD = new BashElementType("assignment_word"); //"a" =2
IElementType DOLLAR = new BashElementType("$");
IElementType LEFT_PAREN = new BashElementType("(");
IElementType RIGHT_PAREN = new BashElementType(")");
IElementType LEFT_CURLY = new BashElementType("{");
IElementType RIGHT_CURLY = new BashElementType("}");
IElementType LEFT_SQUARE = new BashElementType("[ (left square)");
IElementType RIGHT_SQUARE = new BashElementType("] (right square)");
TokenSet bracketSet = TokenSet.create(LEFT_SQUARE, RIGHT_SQUARE);
// comments
IElementType COMMENT = new BashElementType("Comment");
IElementType SHEBANG = new BashElementType("Shebang");
TokenSet commentTokens = TokenSet.create(COMMENT);
// bash reserved keywords, in alphabetic order
IElementType BANG_TOKEN = new BashElementType("!"); //!
IElementType CASE_KEYWORD = new BashElementType("case"); //case
IElementType DO_KEYWORD = new BashElementType("do"); //do
IElementType DONE_KEYWORD = new BashElementType("done"); //done
IElementType ELIF_KEYWORD = new BashElementType("elif");//elif
IElementType ELSE_KEYWORD = new BashElementType("else");//else
IElementType ESAC_KEYWORD = new BashElementType("esac"); //esac
IElementType FI_KEYWORD = new BashElementType("fi");//fi
IElementType FOR_KEYWORD = new BashElementType("for");//for
IElementType FUNCTION_KEYWORD = new BashElementType("function");//function
IElementType IF_KEYWORD = new BashElementType("if");//if
IElementType IN_KEYWORD = new BashElementType("in");//in
IElementType SELECT_KEYWORD = new BashElementType("select");//select
IElementType THEN_KEYWORD = new BashElementType("then");//then
IElementType UNTIL_KEYWORD = new BashElementType("until");//until
IElementType WHILE_KEYWORD = new BashElementType("while");//while
IElementType TIME_KEYWORD = new BashElementType("time");//time
IElementType TRAP_KEYWORD = new BashElementType("trap");//trap
IElementType LET_KEYWORD = new BashElementType("let");//let
IElementType BRACKET_KEYWORD = new BashElementType("[[ (left bracket)");//[[
IElementType _BRACKET_KEYWORD = new BashElementType("]] (right bracket)");//]]
//case state
IElementType CASE_END = new BashElementType(";;");//;; for case expressions
// arithmetic expressions
IElementType EXPR_ARITH = new BashElementType("((");//))
IElementType _EXPR_ARITH = new BashElementType("))");//]] after a $((
IElementType EXPR_ARITH_SQUARE = new BashElementType("[ for arithmetic");
IElementType _EXPR_ARITH_SQUARE = new BashElementType("] for arithmetic");
//conditional expressions
IElementType EXPR_CONDITIONAL = new BashElementType("[ (left conditional)");//"[ "
IElementType _EXPR_CONDITIONAL = new BashElementType(" ] (right conditional)");//" ]"
TokenSet keywords = TokenSet.create(BANG_TOKEN, CASE_KEYWORD, DO_KEYWORD, DONE_KEYWORD,
ELIF_KEYWORD, ELSE_KEYWORD, ESAC_KEYWORD, FI_KEYWORD, FOR_KEYWORD, FUNCTION_KEYWORD,
IF_KEYWORD, IN_KEYWORD, SELECT_KEYWORD, THEN_KEYWORD, UNTIL_KEYWORD, WHILE_KEYWORD,
TIME_KEYWORD, BRACKET_KEYWORD, _BRACKET_KEYWORD,
CASE_END, DOLLAR,
EXPR_ARITH, _EXPR_ARITH, EXPR_CONDITIONAL, _EXPR_CONDITIONAL);
TokenSet internalCommands = TokenSet.create(TRAP_KEYWORD, LET_KEYWORD);
//these are keyword tokens which may be used as identifiers, e.g. in a for loop
//these tokens will be remapped to word tokens if they occur at a position where a word token would be accepted
TokenSet identifierKeywords = TokenSet.create(
CASE_KEYWORD, DO_KEYWORD, DONE_KEYWORD, ELIF_KEYWORD, ELSE_KEYWORD, ESAC_KEYWORD, FI_KEYWORD, FOR_KEYWORD, FUNCTION_KEYWORD,
IF_KEYWORD, IN_KEYWORD, SELECT_KEYWORD, THEN_KEYWORD, UNTIL_KEYWORD, WHILE_KEYWORD, TIME_KEYWORD
);
// single characters
IElementType BACKSLASH = new BashElementType("\\");
IElementType AMP = new BashElementType("&");
IElementType AT = new BashElementType("@");
IElementType COLON = new BashElementType(":");
IElementType COMMA = new BashElementType(",");
IElementType EQ = new BashElementType("=");
IElementType ADD_EQ = new BashElementType("+=");
IElementType SEMI = new BashElementType(";");
IElementType SHIFT_RIGHT = new BashElementType(">>");//>>
IElementType LESS_THAN = new BashElementType("<");//>>
IElementType GREATER_THAN = new BashElementType(">");//>>
IElementType PIPE = new BashElementType("|");// }
IElementType PIPE_AMP = new BashElementType("|&"); //bash 4 only, equivalent to 2>&1 |
IElementType AND_AND = new BashElementType("&&");//!=
IElementType OR_OR = new BashElementType("||");//!=
IElementType LINE_FEED = new BashElementType("linefeed");// }
TokenSet pipeTokens = TokenSet.create(PIPE, PIPE_AMP);
//arithmetic operators: plus
IElementType ARITH_PLUS_PLUS = new BashElementType("++");//++
IElementType ARITH_PLUS = new BashElementType("+");//+
//arithmetic operators: minus
IElementType ARITH_MINUS_MINUS = new BashElementType("--");//++
IElementType ARITH_MINUS = new BashElementType("-");//+
TokenSet arithmeticPostOps = TokenSet.create(ARITH_PLUS_PLUS, ARITH_MINUS_MINUS);
TokenSet arithmeticPreOps = TokenSet.create(ARITH_PLUS_PLUS, ARITH_MINUS_MINUS);
TokenSet arithmeticAdditionOps = TokenSet.create(ARITH_PLUS, ARITH_MINUS);
//arithmetic operators: misc
IElementType ARITH_EXPONENT = new BashElementType("**");//**
IElementType ARITH_MULT = new BashElementType("*");//*
IElementType ARITH_DIV = new BashElementType("/");// /
IElementType ARITH_MOD = new BashElementType("%");//%
IElementType ARITH_SHIFT_LEFT = new BashElementType("<<");//<<
IElementType ARITH_SHIFT_RIGHT = new BashElementType(">>");//>>
IElementType ARITH_NEGATE = new BashElementType("negation !");//||
IElementType ARITH_BITWISE_NEGATE = new BashElementType("bitwise negation ~");//~
TokenSet arithmeticShiftOps = TokenSet.create(ARITH_SHIFT_LEFT, ARITH_SHIFT_RIGHT);
TokenSet arithmeticNegationOps = TokenSet.create(ARITH_NEGATE, ARITH_BITWISE_NEGATE);
TokenSet arithmeticProduct = TokenSet.create(ARITH_MULT, ARITH_DIV, ARITH_MOD);
//arithmetic operators: comparision
IElementType ARITH_LE = new BashElementType("<=");//<=
IElementType ARITH_GE = new BashElementType(">=");//>=
IElementType ARITH_GT = new BashElementType("arith >");//>=
IElementType ARITH_LT = new BashElementType("arith <");//>=
TokenSet arithmeticCmpOp = TokenSet.create(ARITH_LE, ARITH_GE, ARITH_LT, ARITH_GT);
IElementType ARITH_EQ = new BashElementType("arith ==");//==
IElementType ARITH_NE = new BashElementType("!=");//!=
TokenSet arithmeticEqualityOps = TokenSet.create(ARITH_NE, ARITH_EQ);
//arithmetic expressiong: logic
IElementType ARITH_QMARK = new BashElementType("?");//||
IElementType ARITH_COLON = new BashElementType(":");//||
IElementType ARITH_BITWISE_XOR = new BashElementType("^");//||
IElementType ARITH_BITWISE_AND = new BashElementType("&");//||
//fixme missing: |
//arithmetic operators: assign
IElementType ARITH_ASS_MUL = new BashElementType("*= arithmetic");// *=
IElementType ARITH_ASS_DIV = new BashElementType("/= arithmetic");// /=
IElementType ARITH_ASS_MOD = new BashElementType("%= arithmetic");// /=
IElementType ARITH_ASS_PLUS = new BashElementType("+= arithmetic");// /=
IElementType ARITH_ASS_MINUS = new BashElementType("-= arithmetic");// /=
IElementType ARITH_ASS_SHIFT_RIGHT = new BashElementType(">>= arithmetic");// /=
IElementType ARITH_ASS_SHIFT_LEFT = new BashElementType("<<= arithmetic");// /=
// IElementType ARITH_ASS_SHIFT_AND = new BashElementType("/=");// /=
//fixme missing: &= |= ^=, = ","
TokenSet arithmeticAssign = TokenSet.create(ARITH_ASS_MUL, ARITH_ASS_DIV, ARITH_ASS_MOD, ARITH_ASS_PLUS,
ARITH_ASS_MINUS, ARITH_ASS_SHIFT_LEFT, ARITH_ASS_SHIFT_RIGHT);
//arithmetic literals
IElementType ARITH_HEX_NUMBER = new BashElementType("0x hex literal");
IElementType ARITH_OCTAL_NUMBER = new BashElementType("octal literal");
IElementType ARITH_BASE_CHAR = new BashElementType("arithmetic base char (#)");
TokenSet arithLiterals = TokenSet.create(ARITH_NUMBER, ARITH_OCTAL_NUMBER, ARITH_HEX_NUMBER);
//builtin command
IElementType COMMAND_TOKEN = new BashElementType("command");//!=
TokenSet commands = TokenSet.create(COMMAND_TOKEN);
//variables
IElementType VARIABLE = new BashElementType("variable");
//parameter expansion
IElementType PARAM_EXPANSION_OP_UNKNOWN = new BashElementType("Parameter expansion operator (unkown)");
IElementType PARAM_EXPANSION_OP_EXCL = new BashElementType("Parameter expansion operator '!'");
IElementType PARAM_EXPANSION_OP_COLON_EQ = new BashElementType("Parameter expansion operator ':='");
IElementType PARAM_EXPANSION_OP_COLON_QMARK = new BashElementType("Parameter expansion operator ':?'");
IElementType PARAM_EXPANSION_OP_EQ = new BashElementType("Parameter expansion operator '='");
IElementType PARAM_EXPANSION_OP_COLON = new BashElementType("Parameter expansion operator ':'");
IElementType PARAM_EXPANSION_OP_COLON_MINUS = new BashElementType("Parameter expansion operator ':-'");
IElementType PARAM_EXPANSION_OP_MINUS = new BashElementType("Parameter expansion operator '-'");
IElementType PARAM_EXPANSION_OP_COLON_PLUS = new BashElementType("Parameter expansion operator ':+'");
IElementType PARAM_EXPANSION_OP_PLUS = new BashElementType("Parameter expansion operator '+'");
IElementType PARAM_EXPANSION_OP_HASH = new BashElementType("Parameter expansion operator '#'");
IElementType PARAM_EXPANSION_OP_AT = new BashElementType("Parameter expansion operator '@'");
IElementType PARAM_EXPANSION_OP_STAR = new BashElementType("Parameter expansion operator '*'");
IElementType PARAM_EXPANSION_OP_QMARK = new BashElementType("Parameter expansion operator '?'");
IElementType PARAM_EXPANSION_OP_DOT = new BashElementType("Parameter expansion operator '.'");
IElementType PARAM_EXPANSION_OP_PERCENT = new BashElementType("Parameter expansion operator '%'");
IElementType PARAM_EXPANSION_OP_SLASH = new BashElementType("Parameter expansion operator '/'");
TokenSet paramExpansionOperators = TokenSet.create(PARAM_EXPANSION_OP_UNKNOWN, PARAM_EXPANSION_OP_EXCL,
PARAM_EXPANSION_OP_COLON_EQ, PARAM_EXPANSION_OP_COLON_QMARK, PARAM_EXPANSION_OP_EQ, PARAM_EXPANSION_OP_COLON, PARAM_EXPANSION_OP_COLON_MINUS,
PARAM_EXPANSION_OP_MINUS, PARAM_EXPANSION_OP_PLUS, PARAM_EXPANSION_OP_COLON_PLUS, PARAM_EXPANSION_OP_HASH,
PARAM_EXPANSION_OP_AT, PARAM_EXPANSION_OP_STAR, PARAM_EXPANSION_OP_PERCENT, PARAM_EXPANSION_OP_QMARK, PARAM_EXPANSION_OP_DOT, PARAM_EXPANSION_OP_SLASH);
TokenSet paramExpansionAssignmentOps = TokenSet.create(PARAM_EXPANSION_OP_EQ, PARAM_EXPANSION_OP_COLON_EQ);
// Special characters
IElementType STRING_BEGIN = new BashElementType("string begin");
IElementType STRING_DATA = new BashElementType("string data");
IElementType STRING_END = new BashElementType("string end");
//mapped element type
IElementType STRING_CONTENT = new BashElementType("string content");
IElementType STRING2 = new BashElementType("unevaluated string (STRING2)");
IElementType BACKQUOTE = new BashElementType("backquote `");
IElementType INTEGER_LITERAL = new BashElementType("int literal");
TokenSet stringLiterals = TokenSet.create(WORD, STRING2, INTEGER_LITERAL, COLON);
IElementType HEREDOC_MARKER_TAG = new BashElementType("heredoc marker tag");
IElementType HEREDOC_MARKER_START = new BashElementType("heredoc start marker");
IElementType HEREDOC_MARKER_END = new BashElementType("heredoc end marker");
IElementType HEREDOC_MARKER_IGNORING_TABS_END = new BashElementType("heredoc end marker (ignoring tabs)");
IElementType HEREDOC_LINE = new BashElementType("heredoc line (temporary)");
IElementType HEREDOC_CONTENT = new BashElementType("here doc content");
// test Operators
IElementType COND_OP = new BashElementType("cond_op");//all the test operators, e.g. -z, != ...
IElementType COND_OP_EQ_EQ = new BashElementType("cond_op ==");
IElementType COND_OP_REGEX = new BashElementType("cond_op =~");
IElementType COND_OP_NOT = new BashElementType("cond_op !");
TokenSet conditionalOperators = TokenSet.create(COND_OP, OR_OR, AND_AND, BANG_TOKEN, COND_OP_EQ_EQ, COND_OP_REGEX);
//redirects
IElementType REDIRECT_LESS_LESS_LESS = new BashElementType("<<<");
IElementType REDIRECT_LESS_AMP = new BashElementType("<&");
IElementType REDIRECT_GREATER_AMP = new BashElementType(">&");
IElementType REDIRECT_LESS_GREATER = new BashElementType("<>");
IElementType REDIRECT_GREATER_BAR = new BashElementType(">|");
IElementType FILEDESCRIPTOR = new BashElementType("&[0-9] filedescriptor");
//Bash 4:
IElementType REDIRECT_AMP_GREATER_GREATER = new BashElementType("&>>");
IElementType REDIRECT_AMP_GREATER = new BashElementType("&>");
TokenSet redirectionSet = TokenSet.create(GREATER_THAN, LESS_THAN, SHIFT_RIGHT,
REDIRECT_LESS_LESS_LESS, REDIRECT_LESS_GREATER,
REDIRECT_GREATER_BAR, REDIRECT_GREATER_AMP, REDIRECT_AMP_GREATER, REDIRECT_LESS_AMP, REDIRECT_AMP_GREATER_GREATER, PIPE_AMP,
HEREDOC_MARKER_TAG);
//sets
//fixme add internal commands?
TokenSet identifierTokenSet = TokenSet.orSet(keywords, bracketSet);
TokenSet EQ_SET = TokenSet.create(EQ);
}
| 53.439716
| 164
| 0.74081
|
e8c44f9ea110ecb477237092bf8264cd6c8473eb
| 1,075
|
package ru.job4j.singletons;
import ru.job4j.models.Item;
/**
* TrackerSingletonLazy.
*
* @author Maxim Vanny.
* @version 2.0
* @since 0.1
*/
public final class TrackerSingletonLazy {
/**
* Create TrackSingletonLazy link.
*/
private static TrackerSingletonLazy instance;
/**
* Constructor.
*/
private TrackerSingletonLazy() {
}
/**
* Method get static link to object TSL.
*
* @return static link.
*/
public static TrackerSingletonLazy getInstance() {
if (instance == null) {
instance = new TrackerSingletonLazy();
}
return instance;
}
/**
* Start program.
*
* @param args string.
*/
public static void main(final String[] args) {
@SuppressWarnings("unused")
var tracker = TrackerSingletonLazy.getInstance();
}
/**
* Example method.
*
* @param model model.
* @return model.
*/
@SuppressWarnings("unused")
public Item add(final Item model) {
return model;
}
}
| 18.859649
| 57
| 0.571163
|
3961536b39cce83dd0549ca9d876ef5d168072c4
| 31,204
|
package com.wzq.jz_app.ui.fragment;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.wzq.jz_app.MyApplication;
import com.wzq.jz_app.R;
import com.wzq.jz_app.base.BaseMVPFragment;
import com.wzq.jz_app.model.bean.local.BBill;
import com.wzq.jz_app.model.bean.local.MonthChartBean;
import com.wzq.jz_app.model.bean.remote.MyUser;
import com.wzq.jz_app.model.repository.LocalRepository;
import com.wzq.jz_app.presenter.MonthChartPresenter;
import com.wzq.jz_app.presenter.contract.MonthChartContract;
import com.wzq.jz_app.ui.adapter.binder.MonthChartBillViewBinder;
import com.wzq.jz_app.ui.fragment.chart.LineChartEntity;
import com.wzq.jz_app.ui.fragment.chart.LineChartInViewPager;
import com.wzq.jz_app.ui.fragment.chart.NewMarkerView;
import com.wzq.jz_app.ui.fragment.chart.RealListEntity;
import com.wzq.jz_app.ui.fragment.chart.YoyListEntity;
import com.wzq.jz_app.utils.DateUtils;
import com.wzq.jz_app.utils.PieChartUtils;
import com.wzq.jz_app.utils.SnackbarUtils;
import com.wzq.jz_app.utils.StringUtils;
import com.wzq.jz_app.widget.CircleImageView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import cn.bmob.v3.BmobUser;
import me.drakeet.multitype.MultiTypeAdapter;
/**
* 作者:wzq
* 邮箱:wang_love152@163.com
*/
public class ChartFragment extends BaseMVPFragment<MonthChartContract.Presenter>
implements MonthChartContract.View, OnChartValueSelectedListener, View.OnClickListener {
private PieChart mChart;
private TextView centerTitle;
private TextView centerMoney;
private MyUser currentUser;
private LinearLayout layoutCenter;
private ImageView centerImg;
private CircleImageView circleBg;
private ImageView circleImg;
private RelativeLayout layoutCircle;
private TextView title;
private TextView money;
private TextView rankTitle;
private RelativeLayout layoutOther;
private TextView otherMoney;
private SwipeRefreshLayout swipe;
private RelativeLayout itemType;
private RelativeLayout itemOther;
private RecyclerView rvList;
private LinearLayout layoutTypedata;
private
ArrayList<Integer> colors = new ArrayList<>();
private boolean TYPE = true;//默认总收入true
private List<MonthChartBean.SortTypeList> tMoneyBeanList;
private String sort_image;//饼状图与之相对应的分类图片地址
private String sort_name;
private String back_color;
private String advice;
private MonthChartBean monthChartBean;
private MonthChartBean yearDateBean;
private MultiTypeAdapter adapter;
private String setYear = DateUtils.getCurYear(DateUtils.FORMAT_Y);
private String setMonth = DateUtils.getCurMonth(DateUtils.FORMAT_M);
private Toolbar toolbar;
private TextView chart_title;
private ImageView search_date;
private TextView chart_date;
private LineChartInViewPager lineChart;
private List<RealListEntity> realList;
private List<YoyListEntity> yoyList;
private PieChart mainPieChart;
private List<Entry> values1, values2, dottedLineData, solidLineData;
private List<String> dataList;
private RealListEntity realListEntity;
private YoyListEntity yoyListEntity;
private DecimalFormat mFormat;
private float maxData = 0;
ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
private PieChart mPieChart;
private TextView chart_date_year;
float maxIn = 0;
float maxOut = 0;
int timeIn;
int timeOut;
float endIn;
float endOut;
//选择时间
protected int mYear;
protected int mMonth;
protected int mDay;
protected String days;
private Button startTime;
private Button endTime;
private Button look;
private int status = 0;
/*****************************************************************************/
public void changeDate(String yyyy, String mm) {
setYear = yyyy;
setMonth = mm;
mPresenter.getMonthChart(MyApplication.getCurrentUserId(), setYear, setMonth, "1");
chart_date.setText(setYear + "-" + setMonth);
chart_date_year.setText(setYear + "");
test(yyyy);
test(yyyy);
}
public void changeDate1(String start, String end) {
chart_date.setText(start + "到" + end);
mPresenter.getMonthChart(MyApplication.getCurrentUserId(), start, end, "0");
}
/*****************************************************************************/
@Override
protected int getLayoutId() {
return R.layout.main_fragment_chart;
}
@Override
protected void initWidget(Bundle savedInstanceState) {
super.initWidget(savedInstanceState);
chart_title = getViewById(R.id.chart_title);
search_date = getViewById(R.id.toolbar_date1);
chart_date = getViewById(R.id.date_chart);
chart_date_year = getViewById(R.id.date_chart_year);
//设置日期选择器初始日期
mYear = Integer.parseInt(DateUtils.getCurYear(DateUtils.FORMAT_Y));
mMonth = Integer.parseInt(DateUtils.getCurMonth(DateUtils.FORMAT_M));
mDay = Integer.parseInt(DateUtils.getCurDay(DateUtils.FORMAT_D));
//
mChart = getViewById(R.id.chart);
centerTitle = getViewById(R.id.center_title);
centerMoney = getViewById(R.id.center_money);
layoutCenter = getViewById(R.id.layout_center);
centerImg = getViewById(R.id.center_img);
circleBg = getViewById(R.id.circle_bg);
circleImg = getViewById(R.id.circle_img);
layoutCircle = getViewById(R.id.layout_circle);
title = getViewById(R.id.title);
money = getViewById(R.id.money);
rankTitle = getViewById(R.id.rank_title);
layoutOther = getViewById(R.id.layout_other);
otherMoney = getViewById(R.id.other_money);
swipe = getViewById(R.id.swipe);
itemType = getViewById(R.id.item_type);
itemOther = getViewById(R.id.item_other);
rvList = getViewById(R.id.rv_list);
layoutTypedata = getViewById(R.id.layout_typedata);
look = getViewById(R.id.look);
startTime = getViewById(R.id.startTime);
endTime = getViewById(R.id.endTime);
//初始化饼状图
PieChartUtils.initPieChart(mChart);
//设置圆盘是否转动,默认转动
mChart.setRotationEnabled(true);
mChart.setOnChartValueSelectedListener(this);
//改变加载显示的颜色
swipe.setColorSchemeColors(getResources().getColor(R.color.text_red), getResources().getColor(R.color.text_red));
//设置向下拉多少出现刷新
swipe.setDistanceToTriggerSync(200);
//设置刷新出现的位置
swipe.setProgressViewEndTarget(false, 200);
//下拉刷新监听
swipe.setOnRefreshListener(() -> {
swipe.setRefreshing(false);
mPresenter.getMonthChart(MyApplication.getCurrentUserId(), setYear, setMonth, "1");
chart_date.setText(setYear + "-" + setMonth);
test(setYear);
test(setYear);
});
rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new MultiTypeAdapter();
adapter.register(BBill.class, new MonthChartBillViewBinder(mContext));
rvList.setAdapter(adapter);
test(setYear);
}
@Override
protected void setListener() {
}
@Override
protected void initClick() {
super.initClick();
layoutCenter.setOnClickListener(this);
itemType.setOnClickListener(this);
itemOther.setOnClickListener(this);
search_date.setOnClickListener(this);
startTime.setOnClickListener(this);
endTime.setOnClickListener(this);
look.setOnClickListener(this);
}
@Override
protected void processLogic() {
super.processLogic();
mPresenter.getMonthChart(MyApplication.getCurrentUserId(), setYear, setMonth, "1");
chart_date.setText(setYear + "-" + setMonth);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.layout_center: //图表中心键
TYPE = !TYPE;
setReportData();
break;
case R.id.item_type:
break;
case R.id.item_other:
break;
case R.id.startTime:
showTimeSelector("0");
break;
case R.id.endTime:
showTimeSelector("1");
break;
case R.id.look:
if (status == 1) {
String start = startTime.getText().toString();
String end = endTime.getText().toString();
if (start.contains("时间") || end.contains("时间")) {
Toast.makeText(getActivity(), "请先选择时间区间", Toast.LENGTH_SHORT).show();
} else {
changeDate1(start, end);
}
} else {
Toast.makeText(getActivity(), "请先选择时间区间", Toast.LENGTH_SHORT).show();
}
break;
case R.id.toolbar_date1:
currentUser = BmobUser.getCurrentUser(MyUser.class);
// if (currentUser == null)
// Toast.makeText(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT).show();
// else {
//时间选择器
new TimePickerBuilder(mContext, (Date date, View vc) -> {
chart_date.setText(DateUtils.date2Str(date, "yyyy-MM"));
// monthListFragment.changeDate(DateUtils.date2Str(date, "yyyy"), DateUtils.date2Str(date, "MM"));
changeDate(DateUtils.date2Str(date, "yyyy"), DateUtils.date2Str(date, "MM"));
}).setType(new boolean[]{true, true, false, false, false, false})
.setRangDate(null, Calendar.getInstance())
.isDialog(true)//是否显示为对话框样式
.build().show();
break;
}
}
@Override
public void onValueSelected(Entry e, Highlight h) {
if (e == null)
return;
int entryIndex = (int) h.getX();
setNoteData(entryIndex, e.getY());
}
@Override
public void onNothingSelected() {
Log.i("PieChart", "nothing selected");
}
//光滑曲线图
/**
* 下面json转实体类
*/
public void test(String year) {
try {
List<BBill> bBills = LocalRepository.getInstance().getBBillByUserIdWithYear(MyApplication.getCurrentUserId(), year);
float totalMoneyIn1 = 0, totalMoneyOut1 = 0;
float totalMoneyIn2 = 0, totalMoneyOut2 = 0;
float totalMoneyIn3 = 0, totalMoneyOut3 = 0;
float totalMoneyIn4 = 0, totalMoneyOut4 = 0;
float totalMoneyIn5 = 0, totalMoneyOut5 = 0;
float totalMoneyIn6 = 0, totalMoneyOut6 = 0;
float totalMoneyIn7 = 0, totalMoneyOut7 = 0;
float totalMoneyIn8 = 0, totalMoneyOut8 = 0;
float totalMoneyIn9 = 0, totalMoneyOut9 = 0;
float totalMoneyIn10 = 0, totalMoneyOut10 = 0;
float totalMoneyIn11 = 0, totalMoneyOut11 = 0;
float totalMoneyIn12 = 0, totalMoneyOut12 = 0;
float[] totalMoneyIn = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
float[] totalMoneyOut = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int j = 0; j < bBills.size(); j++) {
String date = String.valueOf(DateUtils.getDay(bBills.get(j).getCrdate()));
String date1 = date.substring(5, 7);
switch (date1) {
case "01":
if (bBills.get(j).getIncome()) {
totalMoneyIn1 += bBills.get(j).getCost();
} else {
totalMoneyOut1 += bBills.get(j).getCost();
}
break;
case "02":
if (bBills.get(j).getIncome()) {
totalMoneyIn2 += bBills.get(j).getCost();
} else {
totalMoneyOut2 += bBills.get(j).getCost();
}
break;
case "03":
if (bBills.get(j).getIncome()) {
totalMoneyIn3 += bBills.get(j).getCost();
} else {
totalMoneyOut3 += bBills.get(j).getCost();
}
break;
case "04":
if (bBills.get(j).getIncome()) {
float in = bBills.get(j).getCost();
totalMoneyIn4 += in;
} else {
float out = bBills.get(j).getCost();
totalMoneyOut4 += out;
}
break;
case "05":
if (bBills.get(j).getIncome()) {
totalMoneyIn5 += bBills.get(j).getCost();
} else {
totalMoneyOut5 += bBills.get(j).getCost();
}
break;
case "06":
if (bBills.get(j).getIncome()) {
totalMoneyIn6 += bBills.get(j).getCost();
} else {
totalMoneyOut6 += bBills.get(j).getCost();
}
break;
case "07":
if (bBills.get(j).getIncome()) {
totalMoneyIn7 += bBills.get(j).getCost();
} else {
totalMoneyOut7 += bBills.get(j).getCost();
}
break;
case "08":
if (bBills.get(j).getIncome()) {
totalMoneyIn8 += bBills.get(j).getCost();
} else {
totalMoneyOut8 += bBills.get(j).getCost();
}
break;
case "09":
if (bBills.get(j).getIncome()) {
totalMoneyIn9 += bBills.get(j).getCost();
} else {
totalMoneyOut9 += bBills.get(j).getCost();
}
break;
case "10":
if (bBills.get(j).getIncome()) {
totalMoneyIn10 += bBills.get(j).getCost();
} else {
totalMoneyOut10 = +bBills.get(j).getCost();
}
break;
case "11":
if (bBills.get(j).getIncome()) {
totalMoneyIn11 = +bBills.get(j).getCost();
} else {
totalMoneyOut11 += bBills.get(j).getCost();
}
break;
case "12":
if (bBills.get(j).getIncome()) {
totalMoneyIn12 += bBills.get(j).getCost();
} else {
totalMoneyOut12 += bBills.get(j).getCost();
}
break;
}
}
totalMoneyIn = new float[]{totalMoneyIn1, totalMoneyIn2, totalMoneyIn3, totalMoneyIn4, totalMoneyIn5, totalMoneyIn6, totalMoneyIn7, totalMoneyIn8, totalMoneyIn9, totalMoneyIn10, totalMoneyIn11, totalMoneyIn12};
totalMoneyOut = new float[]{totalMoneyOut1, totalMoneyOut2, totalMoneyOut3, totalMoneyOut4, totalMoneyOut5,
totalMoneyOut6, totalMoneyOut7, totalMoneyOut8, totalMoneyOut9, totalMoneyOut10, totalMoneyOut11, totalMoneyOut12};
realList = new ArrayList<>();
yoyList = new ArrayList<>();
for (int i = 0; i < 12; i++) {
RealListEntity realListEntity = new RealListEntity();
YoyListEntity yoyListEntity = new YoyListEntity();
realListEntity.setAmount(totalMoneyIn[i] + "");//收入
realListEntity.setMonth((i + 1) + "");
realListEntity.setYear("收入");
realList.add(realListEntity);
yoyListEntity.setAmount(totalMoneyOut[i] + "");//支出
yoyListEntity.setMonth((i + 1) + "");
yoyListEntity.setYear("支出");
yoyList.add(yoyListEntity);
//分析年度消费最高、收入最高
endIn += totalMoneyIn[i];
endOut += totalMoneyOut[i];
if (totalMoneyIn[i] > maxIn) { // 判断收入最大值
maxIn = totalMoneyIn[i];
timeIn = i + 1;
}
if (totalMoneyOut[i] > maxOut) {
maxOut = totalMoneyOut[i];
timeOut = i + 1;
}
}
if (endIn == 0 && endOut == 0) {
advice = "您当前没有账单记录!请开始使用APP记账吧!";
//年度分析
TextView textView = getViewById(R.id.sys);
textView.setText("分析:" + advice);
} else {
if (endOut > endIn)
advice = "收支不平衡【入不敷出】,建议您省吃俭用,少花钱!";
else if (endIn == endOut) {
advice = "收支平衡【没有存款】,建议您合理消费";
} else {
advice = "收支不平衡【您有存款了】,建议您享受生活,适当理财";
}
//年度分析
TextView textView = getViewById(R.id.sys);
textView.setText("分析:当前年度中" + timeIn + "月收入最高," + timeOut + "月消费最高!" + advice);
}
initViews();
} catch (Exception e) {
e.printStackTrace();
}
}
public void initViews() { //初始化折线图
lineChart = getViewById(R.id.new_lineChart);
mFormat = new DecimalFormat("#,###.##");
values1 = new ArrayList<>();
values2 = new ArrayList<>();
//支出
for (int i = 0; i < yoyList.size(); i++) {
yoyListEntity = yoyList.get(i);
String amount = yoyListEntity.getAmount();
if (amount != null) {
float f = 0;
try {
f = Float.parseFloat(amount);
} catch (Exception e) {
e.printStackTrace();
f = 0;
}
Entry entry = new Entry(i + 1, f);
values1.add(entry);
}
}
//收入
for (int i = 0; i < realList.size(); i++) {
realListEntity = realList.get(i);
String amount = realListEntity.getAmount();
if (amount != null) {
float f = 0;
try {
f = Float.parseFloat(amount);
} catch (Exception e) {
e.printStackTrace();
f = 0;
}
Entry entry = new Entry(i + 1, f);
values2.add(entry);
}
}
Drawable[] drawables = {
ContextCompat.getDrawable(getActivity(), R.drawable.chart_thisyear_blue),
ContextCompat.getDrawable(getActivity(), R.drawable.chart_callserice_call_casecount)
};
int[] callDurationColors = {Color.parseColor("#45A2FF"), Color.parseColor("#5fd1cc")};
String thisYear = "";
if (realList.size() > 0) {
thisYear = realList.get(0).getYear();
}
String lastYear = "";
if (yoyList.size() > 0) {
lastYear = yoyList.get(0).getYear();
}
String[] labels = new String[]{thisYear, lastYear};
updateLinehart(yoyList, realList, lineChart, callDurationColors, drawables, "", values1, values2, labels);
}
/**
* 双平滑曲线传入数据,添加markview,添加实体类单位
*
* @param yoyList 支出
* @param realList 收入
* @param lineChart
* @param colors 线的颜色
* @param drawables 间隙渲染颜色
* @param unit
* @param values2 每个月份对应的支出
* @param values1 每个月份对应的收入
* @param labels 支出还是收入字符串
*/
private void updateLinehart(final List<YoyListEntity> yoyList, final List<RealListEntity> realList,
LineChart lineChart, int[] colors, Drawable[] drawables,
final String unit, List<Entry> values2, List<Entry> values1, final String[] labels) {
List<Entry>[] entries = new ArrayList[2];
entries[0] = values1;
entries[1] = values2;
LineChartEntity lineChartEntity = new LineChartEntity(lineChart, entries, labels, colors,
Color.parseColor("#999999"), 12f);
lineChartEntity.drawCircle(true);
lineChart.setScaleMinima(1.0f, 1.0f);
toggleFilled(lineChartEntity, drawables, colors);
lineChartEntity.setLineMode(LineDataSet.Mode.CUBIC_BEZIER);//曲线
// lineChartEntity.setLineMode(LineDataSet.Mode.LINEAR);//折线
lineChartEntity.initLegend(Legend.LegendForm.CIRCLE, 12f,
Color.parseColor("#999999"));
lineChartEntity.updateLegendOrientation(Legend.LegendVerticalAlignment.TOP,
Legend.LegendHorizontalAlignment.RIGHT, Legend.LegendOrientation.HORIZONTAL);
lineChartEntity.setAxisFormatter(
new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
if (value == 1.0f) {
return mFormat.format(value) + "月";
}
String monthStr = mFormat.format(value);
if (monthStr.contains(".")) {
return "";
} else {
return monthStr;
}
// return mMonthFormat.format(value);
}
},
new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mFormat.format(value) + unit;
}
});
lineChartEntity.setDataValueFormatter(new IValueFormatter() {
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return mFormat.format(value) + unit;
}
});
final NewMarkerView markerView = new NewMarkerView(getActivity(), R.layout.custom_marker_view_layout);
markerView.setCallBack(new NewMarkerView.CallBack() {
@Override
public void onCallBack(float x, String value) {
int index = (int) (x);
if (index < 0) {
return;
}
if (index > yoyList.size() && index > realList.size()) {
return;
}
String textTemp = "";
if (index <= yoyList.size()) {
if (!StringUtils.isEmpty(textTemp)) {
}
textTemp += index + "月" + yoyList.get(index - 1).getYear() + " " + mFormat.format(Float.parseFloat(yoyList.get(index - 1).getAmount())) + unit + "元";
}
if (index <= realList.size()) {
textTemp += "\n";
textTemp += index + "月" + realList.get(index - 1).getYear() + " " + mFormat.format(Float.parseFloat(realList.get(index - 1).getAmount())) + unit + "元";
}
markerView.getTvContent().setText(textTemp);
}
});
lineChartEntity.setMarkView(markerView);
lineChart.getData().setDrawValues(false);
}
/**
* 双平滑曲线添加线下的阴影
*
* @param lineChartEntity
* @param drawables
* @param colors
*/
private void toggleFilled(LineChartEntity lineChartEntity, Drawable[] drawables, int[] colors) {
if (android.os.Build.VERSION.SDK_INT >= 18) {
lineChartEntity.toggleFilled(drawables, null, true);
} else {
lineChartEntity.toggleFilled(null, colors, true);
}
}
/**
* 报表数据
*/
private void setReportData() {
if (monthChartBean == null) {
return;
}
float totalMoney;
if (TYPE) {
centerTitle.setText("总支出");
centerImg.setImageResource(R.mipmap.tallybook_output);
tMoneyBeanList = monthChartBean.getOutSortlist();
totalMoney = monthChartBean.getTotalOut();
} else {
centerTitle.setText("总收入");
centerImg.setImageResource(R.mipmap.tallybook_input);
tMoneyBeanList = monthChartBean.getInSortlist();
totalMoney = monthChartBean.getTotalIn();
}
centerMoney.setText("" + totalMoney);
ArrayList<PieEntry> entries = new ArrayList<>();
if (tMoneyBeanList != null && tMoneyBeanList.size() > 0) {
layoutTypedata.setVisibility(View.VISIBLE);
for (int i = 0; i < tMoneyBeanList.size(); i++) {
float scale = tMoneyBeanList.get(i).getMoney() / totalMoney;
float value = (scale < 0.06f) ? 0.06f : scale;
entries.add(new PieEntry(value, PieChartUtils.getDrawable(tMoneyBeanList.get(i).getSortImg())));
colors.add(getResources().getColor(R.color.home_1));
colors.add(getResources().getColor(R.color.home_2));
colors.add(getResources().getColor(R.color.home_3));
colors.add(getResources().getColor(R.color.home_5));
colors.add(getResources().getColor(R.color.home_7));
colors.add(getResources().getColor(R.color.home_10));
colors.add(getResources().getColor(R.color.home_11));
colors.add(getResources().getColor(R.color.home_4));
colors.add(getResources().getColor(R.color.home_9));
colors.add(getResources().getColor(R.color.home_8));
colors.add(getResources().getColor(R.color.home_6));
colors.add(getResources().getColor(R.color.home_12));
colors.add(getResources().getColor(R.color.home_13));
}
setNoteData(0, entries.get(0).getY());
} else {//无数据时的显示
layoutTypedata.setVisibility(View.GONE);
entries.add(new PieEntry(1f));
colors.add(getResources().getColor(R.color.home_3));
}
PieChartUtils.setPieChartData(mChart, entries, colors);
}
/**
* 点击饼状图上区域后相应的数据设置
*
* @param index
*/
private void setNoteData(int index, float value) {
if (null == tMoneyBeanList || tMoneyBeanList.size() == 0)
return;
sort_image = tMoneyBeanList.get(index).getSortImg();
sort_name = tMoneyBeanList.get(index).getSortName();
if (TYPE) {
money.setText("-" + tMoneyBeanList.get(index).getMoney());
} else {
money.setText("+" + tMoneyBeanList.get(index).getMoney());
}
DecimalFormat df = new DecimalFormat("0.00%");
title.setText(sort_name+" : "+df.format(value));
rankTitle.setText(sort_name + "排行榜");
circleBg.setImageDrawable(new ColorDrawable(colors.get(index)));//背景色
circleImg.setImageDrawable(PieChartUtils.getDrawable(tMoneyBeanList.get(index).getSortImg()));
adapter.setItems(tMoneyBeanList.get(index).getList());
adapter.notifyDataSetChanged();
}
/*****************************************************************************/
@Override
protected MonthChartContract.Presenter bindPresenter() {
return new MonthChartPresenter();
}
@Override
public void loadDataSuccess(MonthChartBean bean) {
monthChartBean = bean;
setReportData();
}
@Override
public void onSuccess() {
}
@Override
public void onFailure(Throwable e) {
SnackbarUtils.show(mActivity, e.getMessage());
}
/**
* 显示日期选择器
*/
public void showTimeSelector(String type1) {
new DatePickerDialog(getActivity(), (DatePicker datePicker, int i, int i1, int i2) -> {
mYear = i;
mMonth = i1 + 1;
mDay = i2;
if (mMonth < 10) {
if (mDay < 10) {
days = new StringBuffer().append(mYear).append("-").append("0").
append(mMonth).append("-").append("0").append(mDay).toString();
} else {
days = new StringBuffer().append(mYear).append("-").append("0").
append(mMonth).append("-").append(mDay).toString();
}
} else {
if (mDay < 10) {
days = new StringBuffer().append(mYear).append("-").
append(mMonth).append("-").append("0").append(mDay).toString();
} else {
days = new StringBuffer().append(mYear).append("-").
append(mMonth).append("-").append(mDay).toString();
}
}
if ("0".equals(type1)) {
startTime.setText(days);
} else {
endTime.setText(days);
}
status = 1;
}, mYear, mMonth-1, mDay).show();
}
}
| 39.151819
| 222
| 0.550186
|
53d656988a5d6f9aaff6d6e19b108317e9187b9c
| 10,604
|
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7006109
* @summary Add test library to simplify the task of writing automated type-system tests
* @author mcimadamore
* @library .
* @run main CastTest
*/
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Symbol.*;
import java.lang.reflect.Array;
import static com.sun.tools.javac.code.Flags.*;
/**
* Check invariants in cast conversion involving primitive types and arrays
*/
public class CastTest extends TypeHarness {
Type[] types_no_boxing;
Type[] types_boxing;
static final boolean T = true;
static final boolean F = false;
boolean[][] cast_result_no_boxing = {
//byte, short, int, long, float, double, char, bool, C, +C, I, T, byte[], short[], int[], long[], float[], double[], char[], bool[], C[], +C[], I[], T[]
/*byte*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*short*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*int*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*long*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*float*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*double*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*char*/ { T , T , T , T , T , T , T , F , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*bool*/ { F , F , F , F , F , F , F , T , F, F , F, F, F , F , F , F , F , F , F , F , F , F , F , F },
/*C*/ { F , F , F , F , F , F , F , F , T, F , T, T, F , F , F , F , F , F , F , F , F , F , F , F },
/*+C*/ { F , F , F , F , F , F , F , F , F, T , F, T, F , F , F , F , F , F , F , F , F , F , F , F },
/*I*/ { F , F , F , F , F , F , F , F , T, F , T, T, F , F , F , F , F , F , F , F , F , F , F , F },
/*T*/ { F , F , F , F , F , F , F , F , T, T , T, T, T , T , T , T , T , T , T , T , T , T , T , T },
/*byte[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, T , F , F , F , F , F , F , F , F , F , F , F },
/*short[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , T , F , F , F , F , F , F , F , F , F , F },
/*int[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , T , F , F , F , F , F , F , F , F , F },
/*long[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , T , F , F , F , F , F , F , F , F },
/*float[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , T , F , F , F , F , F , F , F },
/*double[]*/{ F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , T , F , F , F , F , F , F },
/*char[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , T , F , F , F , F , F },
/*bool[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , F , T , F , F , F , F },
/*C[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , F , F , T , F , T , T },
/*+C[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , F , F , F , T , F , T },
/*I[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , F , F , T , F , T , T },
/*T[]*/ { F , F , F , F , F , F , F , F , F, F , F, T, F , F , F , F , F , F , F , F , T , T , T , T }};
boolean[][] cast_result_boxing = {
//byte, short, int, long, float, double, char, bool, Byte, Short, Integer, Long, Float, Double, Character, Boolean, Object
/*byte*/ { T , T , T , T , T , T , T , F , T , F , F , F , F , F , F , F , T },
/*short*/ { T , T , T , T , T , T , T , F , F , T , F , F , F , F , F , F , T },
/*int*/ { T , T , T , T , T , T , T , F , F , F , T , F , F , F , F , F , T },
/*long*/ { T , T , T , T , T , T , T , F , F , F , F , T , F , F , F , F , T },
/*float*/ { T , T , T , T , T , T , T , F , F , F , F , F , T , F , F , F , T },
/*double*/ { T , T , T , T , T , T , T , F , F , F , F , F , F , T , F , F , T },
/*char*/ { T , T , T , T , T , T , T , F , F , F , F , F , F , F , T , F , T },
/*bool*/ { F , F , F , F , F , F , F , T , F , F , F , F , F , F , F , T , T },
/*Byte*/ { T , T , T , T , T , T , F , F , T , F , F , F , F , F , F , F , T },
/*Short*/ { F , T , T , T , T , T , F , F , F , T , F , F , F , F , F , F , T },
/*Integer*/ { F , F , T , T , T , T , F , F , F , F , T , F , F , F , F , F , T },
/*Long*/ { F , F , F , T , T , T , F , F , F , F , F , T , F , F , F , F , T },
/*Float*/ { F , F , F , F , T , T , F , F , F , F , F , F , T , F , F , F , T },
/*Double*/ { F , F , F , F , F , T , F , F , F , F , F , F , F , T , F , F , T },
/*Character*/ { F , F , T , T , T , T , T , F , F , F , F , F , F , F , T , F , T },
/*Boolean*/ { F , F , F , F , F , F , F , T , F , F , F , F , F , F , F , T , T },
/*Object*/ { T , T , T , T , T , T , T , T , T , T , T , T , T , T , T , T , T }};
CastTest() {
Type[] primitiveTypes = {
predef.byteType,
predef.shortType,
predef.intType,
predef.longType,
predef.floatType,
predef.doubleType,
predef.charType,
predef.booleanType };
Type[] boxedTypes = new Type[primitiveTypes.length + 1];
for (int i = 0 ; i < primitiveTypes.length ; i++) {
boxedTypes[i] = box(primitiveTypes[i]);
}
boxedTypes[primitiveTypes.length] = predef.objectType;
types_boxing = join(Type.class, primitiveTypes, boxedTypes);
Type[] referenceTypes = {
fac.Class(),
fac.Class(FINAL),
fac.Interface(),
fac.TypeVariable() };
Type[] arrayTypes = new Type[primitiveTypes.length + referenceTypes.length];
int idx = 0;
for (Type t : join(Type.class, primitiveTypes, referenceTypes)) {
arrayTypes[idx++] = fac.Array(t);
}
types_no_boxing = join(Type.class, primitiveTypes, referenceTypes, arrayTypes);
}
void test(Type[] all_types, boolean[][] cast_result) {
for (int i = 0; i < all_types.length ; i++) {
for (int j = 0; j < all_types.length ; j++) {
assertCastable(all_types[i], all_types[j], cast_result[i][j]);
}
}
}
void runTests() {
test(types_no_boxing, cast_result_no_boxing);
test(types_boxing, cast_result_boxing);
}
@SuppressWarnings("unchecked")
<T> T[] join(Class<T> type, T[]... args) {
int totalLength = 0;
for (T[] arr : args) {
totalLength += arr.length;
}
T[] new_arr = (T[])Array.newInstance(type, totalLength);
int idx = 0;
for (T[] arr : args) {
System.arraycopy(arr, 0, new_arr, idx, arr.length);
idx += arr.length;
}
return new_arr;
}
public static void main(String[] args) {
new CastTest().runTests();
}
}
| 64.658537
| 170
| 0.338834
|
6cc18e587fb157dd08002804058eb56ea55144a0
| 183
|
package SemantifyingBPMN;
public enum ActivityType {
Task , SendTask , ReceiveTask , ManualTask , Compensation ,
SendTaskWithBoundaryRollback , ManualTaskWithBoundaryRollback;
}
| 22.875
| 64
| 0.808743
|
083ca6f5ee82899fde52783a2bda3d661204bec9
| 227
|
import java.io.Serializable;
public class SQLTimePair implements Serializable {
public Long timeStamp;
public String clause;
public SQLTimePair(Long a,String b){
timeStamp = a;
clause = b;
}
}
| 18.916667
| 50
| 0.665198
|
182bef806116934427c870062a4671dfa963372e
| 523
|
package br.com.zup.bootcamp.ecommerce.product;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.web.multipart.MultipartFile;
class ImageFile {
private final MultipartFile file;
ImageFile(MultipartFile file) {
this.file = file;
}
String getName() {
return file.getName();
}
URL writeTo(Path dest) throws IOException {
file.transferTo(dest);
return dest.toUri().toURL();
}
}
| 18.678571
| 55
| 0.676864
|
e7ea53fc41f3557c9fbb04f2ad92950adb0ac16a
| 418
|
package bayern.steinbrecher.dbConnector;
/**
* @author Stefan Huber
* @since 0.1
*/
public class AuthException extends Exception {
public AuthException() {
}
public AuthException(String message) {
super(message);
}
public AuthException(String message, Throwable cause) {
super(message, cause);
}
public AuthException(Throwable cause) {
super(cause);
}
}
| 17.416667
| 59
| 0.643541
|
5c052f840e7f2acd36f772242cf6a91dd8e3b5ce
| 2,085
|
/*
Copyright 2015 David Standish
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.wtdiff.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wtdiff.util.ErrorHandler;
import org.wtdiff.util.LoggingErrorHandler;
public class TestLoggingErrorHandler {
private static final Logger logger = LogManager.getRootLogger();
@Test
public void testHandlerLog() {
ErrorHandler h = new LoggingErrorHandler(logger, false);
assertFalse(h.encounteredError());
h.logError(new Exception("exception"));
assertTrue(h.encounteredError());
}
@Test
public void testHandlerNoIgnore() {
ErrorHandler h = new LoggingErrorHandler(logger, false);
assertFalse(h.encounteredError());
h.reset();
assertFalse(h.encounteredError());
assertFalse(h.handleError(new Exception("exception")));
assertTrue(h.encounteredError());
h.reset();
assertFalse(h.encounteredError());
}
@Test
public void testHandlerIgnore() {
ErrorHandler h = new LoggingErrorHandler(logger, true);
assertFalse(h.encounteredError());
h.reset();
assertFalse(h.encounteredError());
assertTrue(h.handleError(new Exception("exception")));
assertTrue(h.encounteredError());
h.reset();
assertFalse(h.encounteredError());
}
}
| 28.561644
| 72
| 0.680096
|
24843b438a7fe682104536939d66cb2685fd7346
| 795
|
package offer55_2;
// 平衡二叉树
public class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public boolean isBalanced(TreeNode root) {
return recur(root) != -1;
}
private int recur(TreeNode root) {
// 用 left,right记录root左右子节点的深度,避免遍历的时候
// 对左右节点的深度进行重复计算
// 对于当前遍历到的节点,先递归判断左右子树是否平衡 再判断以当前节点为根的子树是否平衡,
// 如果一棵树是平衡的,则返回其高度,否则返回-1 如果存在一棵子树不平衡 则整个二叉树不平衡
if (root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
// 如果满足二者之差小于2就返回高度,否则返回-1
}
}
| 27.413793
| 75
| 0.577358
|
90ab51243d40d53821966d84d21ee4a7b99f3cec
| 5,712
|
/*
* Copyright © 2022 JINSPIRED B.V.
*/
package io.humainary.devkit.perfkit;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.results.AverageTimeResult;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import static java.lang.System.getProperty;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.openjdk.jmh.runner.options.TimeValue.seconds;
public final class PerfKit {
/**
* The Benchmark marker interface.
*/
public interface Driver {
String ALL = "*";
void setup () throws Exception;
default UnaryOperator< String > configuration ()
throws IOException {
final var properties =
new Properties ();
properties.load (
getClass ()
.getResourceAsStream (
"/" +
getProperty (
"io.humainary.devkit.perfkit.profile",
"spi"
) + ".properties"
)
);
return
properties::getProperty;
}
}
public static Target target (
final Class< ? extends Driver > benchmark,
final String api,
final String spi
) {
return
new Target (
benchmark,
api,
spi
);
}
public static final class Target {
private final Class< ? extends Driver > benchmark;
private final String api;
private final String spi;
private Target (
final Class< ? extends Driver > benchmark,
final String api,
final String spi
) {
this.benchmark = benchmark;
this.api = api;
this.spi = spi;
}
}
public static void execute (
final Target target,
final String profile,
final String pattern,
final int threads,
final double threshold,
final Consumer< ? super String > consumer
) {
try {
Launcher.inspect (
target,
Launcher.run (
Launcher.options (
target,
profile,
pattern,
threads
)
),
threshold,
consumer
);
} catch (
final Throwable error
) {
consumer.accept (
error.toString ()
);
}
}
private static final class Launcher {
private static final String NEWLINE = getProperty ( "line.separator" );
private static final char SEMICOLON = ':';
private static final char SPACE = ' ';
private static final int ITERATIONS = 2;
private static final TimeValue TIME = seconds ( 2L );
private static final TimeValue WARMUP_TIME = seconds ( 1L );
private static final int WARM_ITERATIONS = 2;
private static final boolean GC_ENABLED = true;
private static final int FORK_COUNT = 2;
private static final boolean FAIL_ON_ERROR = true;
private static Collection< RunResult > run (
final Options options
) throws RunnerException {
return
new Runner (
options
).run ();
}
private static Options options (
final Target target,
final String profile,
final String pattern,
final int threads
) {
return
new OptionsBuilder ()
.include ( target.benchmark.getSimpleName () + "." + pattern )
.mode ( Mode.AverageTime )
.timeUnit ( NANOSECONDS )
.warmupTime ( WARMUP_TIME )
.warmupIterations ( WARM_ITERATIONS )
.measurementTime ( TIME )
.measurementIterations ( ITERATIONS )
.threads ( threads )
.shouldFailOnError ( FAIL_ON_ERROR )
.shouldDoGC ( GC_ENABLED )
.forks ( FORK_COUNT )
.jvmArgsAppend (
"-server",
"-Dio.humainary." + target.api + ".spi.factory=" + target.spi,
"-D" + "io.humainary.devkit.perfkit.profile" + "=" + profile
).build ();
}
private static void inspect (
final Target target,
final Collection< ? extends RunResult > results,
final double threshold,
final Consumer< ? super String > consumer
) {
final var list =
results
.stream ()
.flatMap (
run ->
run.getBenchmarkResults ().stream () )
.map ( BenchmarkResult::getPrimaryResult )
.map ( AverageTimeResult.class::cast )
.filter (
result ->
result.getScore () > threshold
).toList ();
if ( !list.isEmpty () ) {
final var message =
new StringBuilder ( list.size () * 100 );
message.append (
"provider"
).append (
SEMICOLON
).append (
SPACE
).append (
target.spi
).append (
NEWLINE
);
list.forEach (
result ->
message.append (
result.getLabel ()
).append (
SEMICOLON
).append (
SPACE
).append (
result.getScore ()
).append (
NEWLINE
)
);
consumer.accept (
message.toString ()
);
}
}
}
}
| 22.756972
| 86
| 0.556022
|
6737274d95747c79b93312ea56453dcc8280f30c
| 441
|
package com.nsyw.routerdemo.module_chat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.nsyw.routerdemo.router_compiler.annotation.Route;
@Route(path = "/chat/two")
public class ChatTwoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_two);
}
}
| 24.5
| 60
| 0.770975
|
5bf9af860eb9c651bcab4f38d0d4b262eea1941e
| 2,646
|
package org.jsoup.parser;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.InOrder;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.times;
@ExtendWith(MockitoExtension.class)
public class TokenizerTransitionsTest {
public Tokeniser setup(String input) {
Tokeniser tokeniser = new Tokeniser(new CharacterReader(input), ParseErrorList.noTracking());
return Mockito.spy(tokeniser);
}
public Tokeniser setup(String input, TokeniserState state) {
Tokeniser tokeniser = new Tokeniser(new CharacterReader(input), ParseErrorList.noTracking());
tokeniser.transition(state);
return Mockito.spy(tokeniser);
}
@Test
public void testTokeniserNormalTag() {
Tokeniser tokeniser = setup("<p>");
InOrder inOrder = Mockito.inOrder(tokeniser);
tokeniser.read();
inOrder.verify(tokeniser, times(1)).advanceTransition(TokeniserState.TagOpen);
inOrder.verify(tokeniser, times(1)).transition(TokeniserState.TagName);
}
@Test
public void testMissingTagBracket() {
Tokeniser tokeniser = setup("p>", TokeniserState.TagOpen);
tokeniser.read();
Mockito.verify(tokeniser).transition(TokeniserState.TagName);
}
@Test
public void testNoTextTag() {
Tokeniser tokeniser = setup("</>", TokeniserState.Data);
InOrder inOrder = Mockito.inOrder(tokeniser);
tokeniser.read();
inOrder.verify(tokeniser).advanceTransition(TokeniserState.TagOpen);
inOrder.verify(tokeniser).advanceTransition(TokeniserState.EndTagOpen);
inOrder.verify(tokeniser).advanceTransition(TokeniserState.Data);
}
@Test
public void testSelfClosingTag() {
Tokeniser tokeniser = setup("<input/>", TokeniserState.Data);
InOrder inOrder = Mockito.inOrder(tokeniser);
tokeniser.read();
inOrder.verify(tokeniser).advanceTransition(TokeniserState.TagOpen);
inOrder.verify(tokeniser).transition(TokeniserState.TagName);
inOrder.verify(tokeniser).transition(TokeniserState.SelfClosingStartTag);
inOrder.verify(tokeniser).transition(TokeniserState.Data);
}
@Test
public void testAttributeNameAfterTag() {
Tokeniser tokeniser = setup("color", TokeniserState.AfterAttributeName);
InOrder inOrder = Mockito.inOrder(tokeniser);
tokeniser.createTagPending(true);
tokeniser.read();
inOrder.verify(tokeniser).transition(TokeniserState.AttributeName);
}
}
| 37.267606
| 101
| 0.704082
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.