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 |
|---|---|---|---|---|---|
1797204347a9dba692d44ae15229a4bb0d2100ee | 1,071 | package TwoDimensionalArray;
/**
* @author Muhammad Elgendi
**/
public class TwoDimensionalArray {
public static void main(String[] args) {
//intialization process
int arr1[][]=new int[][]{
{1,2,3},
{5,6,7},
{8,9,11}
};
int arr2[][]=new int[][]{
{5,5,3},
{4,7,7},
{3,5,11}
};
int result[][]=new int[3][3];
//multipling array's elemwnts
for (int row=0;row<arr1.length;row++){
for(int col2=0;col2<arr2[0].length;col2++){
for(int col1=0;col1<arr1[0].length;col1++){
result[row][col2]+=(arr1[row][col1]*arr2[col1][col2]);
}
}
}
//display the Result
for (int row2=0;row2<arr1.length;row2++){
for(int coloum2=0;coloum2<arr1[row2].length;coloum2++){
System.out.print(result[row2][coloum2]+" ");
}
System.out.print("\n");
}
}
}
| 26.775 | 77 | 0.437908 |
0cf37e84d1512c0b70b4493fae34ef0bf3d31a97 | 1,753 | package seedu.knowitall.storage.csvmanager;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents a Csv file for either import or export
*/
public class CsvFile {
public static final String MESSAGE_CONSTRAINTS = "File name should not be left blank and should have"
+ ".csv format";
public static final String FILENAME_CONSTRAINTS = "file name must only contain letters, "
+ "numbers and whitespaces,\nshould not be left blank"
+ " and should be between 1 and 50 characters";
public static final String FILE_EXT_REGEX = "\\.(?=[^.]+$)";
public final String filename;
public CsvFile(String filename) {
this.filename = filename;
}
public static boolean isValidFileName(String filename) {
return !isFileNameEmpty(filename) && isCorrectFileExtension(filename);
}
private static boolean isFileNameEmpty(String filename) {
return filename.isEmpty();
}
/**
* Returns true if file extension is of .csv format.
*/
private static boolean isCorrectFileExtension(String filename) {
Pattern pattern = Pattern.compile(FILE_EXT_REGEX);
Matcher matcher = pattern.matcher(filename);
if (matcher.find()) {
return filename.split(FILE_EXT_REGEX)[1].equals("csv");
} else {
return false;
}
}
public String getFileNameWithoutExt() {
return this.filename.split(FILE_EXT_REGEX)[0];
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof CsvFile && ((CsvFile) obj).filename.equals(this.filename);
}
@Override
public int hashCode() {
return filename.hashCode();
}
}
| 28.737705 | 105 | 0.652025 |
ba717201d6c5cfb8cfd58f5a119cbe187512fc0c | 3,162 | package cn.wildfire.chat.kit.group.manage;
import android.widget.Toast;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.kyleduo.switchbutton.SwitchButton;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfire.chat.kit.R;
import cn.wildfire.chat.kit.R2;
import cn.wildfirechat.model.GroupInfo;
public class GroupMuteActivity extends WfcBaseActivity {
private GroupInfo groupInfo;
private GroupViewModel groupViewModel;
@BindView(R2.id.muteSwitchButton)
SwitchButton switchButton;
@Override
protected int contentLayout() {
return R.layout.group_manage_mute_activity;
}
@Override
protected void afterViews() {
super.afterViews();
groupInfo = getIntent().getParcelableExtra("groupInfo");
init();
}
private void init() {
groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
groupViewModel.groupInfoUpdateLiveData().observe(this, new Observer<List<GroupInfo>>() {
@Override
public void onChanged(List<GroupInfo> groupInfos) {
if (groupInfos != null) {
for (GroupInfo info : groupInfos) {
if (info.target.equals(groupInfo.target)) {
boolean oMuted = groupInfo.mute == 1;
boolean nMuted = info.mute == 1;
groupInfo = info;
if (oMuted != nMuted) {
initGroupMemberMuteListFragment(!nMuted);
}
break;
}
}
}
}
});
switchButton.setCheckedNoEvent(groupInfo.mute == 1);
switchButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
groupViewModel.muteAll(groupInfo.target, isChecked, null, Collections.singletonList(0)).observe(this, booleanOperateResult -> {
if (!booleanOperateResult.isSuccess()) {
switchButton.setCheckedNoEvent(!isChecked);
Toast.makeText(this, "禁言失败 " + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
}
});
});
if (groupInfo.mute == 0) {
initGroupMemberMuteListFragment(true);
}
}
private GroupMemberMuteListFragment fragment;
private void initGroupMemberMuteListFragment(boolean show) {
if (show) {
if (fragment == null) {
fragment = GroupMemberMuteListFragment.newInstance(groupInfo);
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerFrameLayout, fragment)
.commit();
} else {
if (fragment != null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
fragment = null;
}
}
}
}
| 33.638298 | 139 | 0.590133 |
77ee5cca7fa789bc2dfc867c52c8560768276d2f | 860 | package seedu.address.testutil.notes;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TITLE;
import seedu.address.logic.commands.notes.EditNoteCommand.EditNoteDescriptor;
/**
* A utility class for Note.
*/
public class NoteUtil {
/**
* Returns the part of command string for the given {@code EditNoteDescriptor}'s details.
*/
public static String getEditNoteDescriptorDetails(EditNoteDescriptor descriptor) {
StringBuilder sb = new StringBuilder();
descriptor.getTitle().ifPresent(title -> sb.append(PREFIX_TITLE).append(title.title).append(" "));
descriptor.getDescription().ifPresent(description ->
sb.append(PREFIX_DESCRIPTION).append(description.description).append(" "));
return sb.toString();
}
}
| 35.833333 | 106 | 0.72907 |
2263afa9582ada34c3efa2bd6557a93143fc6b96 | 482 | package com.kh.yeokku.model.dao;
import java.util.List;
import java.util.Map;
import com.kh.yeokku.model.dto.LikeTourCourseDto;
import com.kh.yeokku.model.dto.RoomDto;
public interface RoomDao {
String NAMESPACE="room.";
public int createRoom(Map<String, Object> map, String pw);
public List<RoomDto> selectAll();
public int roomUpdate(RoomDto dto);
public RoomDto viewRoom(int room);
public RoomDto remakeRoom(String pw);
public int roomLike(LikeTourCourseDto dto);
}
| 24.1 | 59 | 0.771784 |
11f631204a0906fad39323818b2bfedf3e72ff83 | 3,558 | package com.net.comy;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
private Context mContext;
private String mUserId;
private ArrayList<ChatMessageModel> mChatMessageModelArrayList;
public ChatAdapter(Context pContext, String pUserId) {
mContext = pContext;
mUserId = pUserId;
mChatMessageModelArrayList = new ArrayList<>();
}
public void addChatMessage(ChatMessageModel pMessageModel) {
mChatMessageModelArrayList.add(pMessageModel);
notifyDataSetChanged();
}
@NonNull
@Override
public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(mContext).inflate(R.layout.chat_message, parent, false);
return new ChatViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
holder.createMessageBox(position);
}
@Override
public int getItemCount() {
return mChatMessageModelArrayList.size();
}
class ChatViewHolder extends RecyclerView.ViewHolder {
private TextView mChatMessage, mChatTime;
private CardView mChatContainer;
private LinearLayout mLinearLayout;
public ChatViewHolder(@NonNull View itemView) {
super(itemView);
mChatMessage = itemView.findViewById(R.id.chat_message_txt);
mChatTime = itemView.findViewById(R.id.chat_message_time_txt);
mChatContainer = itemView.findViewById(R.id.chat_container);
mLinearLayout = itemView.findViewById(R.id.linearlayout_cont);
}
public void createMessageBox(int pPosition) {
ChatMessageModel messageModel = mChatMessageModelArrayList.get(pPosition);
mChatMessage.setText(messageModel.getChatMessage());
String time = Utils.getMessageTime(messageModel.getTimestamp());
mChatTime.setText(time);
if (mUserId.equals(messageModel.getUserId())) {
mChatContainer.setBackgroundResource(R.drawable.chat_message_background);
mChatMessage.setTextColor(mContext.getResources().getColor(R.color.white));
mChatTime.setTextColor(mContext.getResources().getColor(R.color.white));
mLinearLayout.setGravity(Gravity.END);
mLinearLayout.setPadding(dpToPx(50), 0, 0, 0);
} else {
mChatContainer.setBackgroundResource(R.drawable.chat_message_background_normal);
mChatMessage.setTextColor(mContext.getResources().getColor(R.color.black));
mChatTime.setTextColor(mContext.getResources().getColor(R.color.black));
mLinearLayout.setGravity(Gravity.START);
mLinearLayout.setPadding(0, 0, dpToPx(50), 0);
}
}
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
}
| 38.673913 | 98 | 0.701799 |
387f12cb1df31d82b0c470fcfef309958868ae9f | 2,176 | package com.explore.weeboos.gaodemap;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Created by weeboos
* on 2018/11/30
* 通过ViewDrag实现滑动上移效果的viewGroup
*/
public class SlidingLayout extends FrameLayout {
private ViewDragHelper mDragger;
private ViewDragHelper.Callback callback;
private String slidingViewTag;
public SlidingLayout(@NonNull Context context) {
this(context,null);
}
public SlidingLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
callback = new DragCallBack();
mDragger = ViewDragHelper.create(this,1.0f,callback);
}
public void addView(View view, String tag) {
slidingViewTag = tag;
view.setTag(tag);
addView(view);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
/*@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mDragger.shouldInterceptTouchEvent(ev);
}*/
@Override
public boolean onTouchEvent(MotionEvent event) {
mDragger.processTouchEvent(event);
return true;
}
class DragCallBack extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(@NonNull View view, int i) {
if(view.getTag()!=null && view.getTag().equals(slidingViewTag)) {
return true;
}
return false;
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return left;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return top;
}
}
}
| 27.544304 | 100 | 0.671415 |
6efc7d5d91abe579d8ff450dbb1d8a019cca56d8 | 866 | package com.blocklang.marketplace.service;
import java.util.Optional;
import com.blocklang.marketplace.model.ApiRepoVersion;
/**
* Api 仓库版本管理数据服务接口。
*
* <p> 一个 Api 仓库中有多个稳定版本和一个 master 版本。
* 使用 git tag 标注稳定版本,在 master 分支中存最新版本。
*
* @author Zhengwei Jin
*
*/
public interface ApiRepoVersionService {
/**
* 根据 Api 仓库的版本标识获取 Api 仓库的版本信息
*
* @param apiRepoVersionId 根据 Api 仓库的版本标识
* @return Api 仓库的版本信息
*/
Optional<ApiRepoVersion> findById(Integer apiRepoVersionId);
/**
* 获取 Api 仓库中最新稳定版版本信息
*
* @param apiRepoId Api 仓库标识
* @return 最新稳定版本信息
*/
Optional<ApiRepoVersion> findLatestStableVersion(Integer apiRepoId);
/**
* 获取 Api 仓库的 master/main 分支信息。
*
* @param apiRepoId Api 仓库标识
* @return master/main 分支信息
*/
Optional<ApiRepoVersion> findMasterVersion(Integer apiRepoId);
}
| 20.619048 | 70 | 0.678984 |
876bd4ff70fe6341f96ef2e549454ffa778245e6 | 566 | package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.*;
import me.vilsol.nmswrapper.reflections.*;
import me.vilsol.nmswrapper.wraps.*;
@ReflectiveClass(name = "AchievementList")
public class NMSAchievementList extends NMSWrap {
public NMSAchievementList(Object nmsObject){
super(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.AchievementList#a()
*/
@ReflectiveMethod(name = "a", types = {})
public void a(){
NMSWrapper.getInstance().exec(nmsObject);
}
} | 24.608696 | 60 | 0.689046 |
22f0940a22dffb74de2cb76b3983484ff267ace7 | 188 | package com;
import org.junit.Test;
/**
* Created by bruce.ge on 2016/11/21.
*/
public class FirstTest {
@Test
public void test(){
System.out.println("nimei");
}
}
| 13.428571 | 37 | 0.601064 |
36b3d5e026b56094563d4e1ab8797aa2a647d27f | 333 | package cn.keking.dao;
import cn.keking.entity.DataList;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* @Author mingyuan
* @Date 2020.06.14 16:10
*/
public interface DataListDao extends MongoRepository<DataList, String> {
DataList findByOid(String oid);
DataList findFirstByUid(String uid);
}
| 23.785714 | 72 | 0.765766 |
5ff8a476c8fb15bc291d12b8507b791bf3a3d7bd | 2,684 | package org.dataalgorithms.chap11.projection.memorysort;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import edu.umd.cloud9.io.pair.PairOfLongInt;
import org.apache.log4j.Logger;
import org.dataalgorithms.util.HadoopUtil;
/**
* MapReduce job for projecting customer transaction data
* by using in memory sort (without secondary sort design pattern).
*
* @author Mahmoud Parsian
*
*/
public class SortInMemoryProjectionDriver {
private static final Logger theLogger =
Logger.getLogger(SortInMemoryProjectionDriver.class);
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
theLogger.warn("Usage: SortInMemoryProjectionDriver <input> <output>");
System.exit(1);
}
Job job = new Job(conf, "SortInMemoryProjectionDriver");
// add jars to distributed cache
HadoopUtil.addJarsToDistributedCache(job, "/lib/");
// set mapper/reducer
job.setMapperClass(SortInMemoryProjectionMapper.class);
job.setReducerClass(SortInMemoryProjectionReducer.class);
// define mapper's output key-value
job.setMapOutputKeyClass(Text.class);
// PairOfLongInt = pair(long, int) = pair(date, amount)
job.setMapOutputValueClass(PairOfLongInt.class);
// define reducer's output key-value
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
// define I/O
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
boolean jobStatus = job.waitForCompletion(true);
long elapsedTime = System.currentTimeMillis() - startTime;
theLogger.info("jobStatus: "+ jobStatus);
theLogger.info("elapsedTime (in milliseconds): "+ elapsedTime);
System.exit(jobStatus? 0 : 1);
}
}
| 37.277778 | 84 | 0.711252 |
80471b6b3c1d2897b3599727cf05c93b946351c2 | 7,430 | package playn.core;
import org.jbox2d.callbacks.DebugDraw;
import org.jbox2d.common.Color3f;
import org.jbox2d.common.OBBViewportTransform;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
import static playn.core.PlayN.log;
public class DebugDrawBox2D extends DebugDraw {
private static String CANVASERROR =
"Must set canvas (DebugDrawBox2D.setCanvas()) in DebugDrawBox2D before drawing.";
private Canvas canvas;
private float strokeWidth;
private int strokeAlpha;
private int fillAlpha;
private float cameraX, cameraY, cameraScale = 1;
private static float cacheFillR, cacheFillG, cacheFillB; // cached fill color
private static float cacheStrokeR, cacheStrokeG, cacheStrokeB; // cached
// stroke color
private final Vec2 tempVec1 = new Vec2();
private final Vec2 tempVec2 = new Vec2();
private final Vec2 tempVec3 = new Vec2();
public DebugDrawBox2D() {
super(new OBBViewportTransform());
viewportTransform.setYFlip(true);
strokeWidth = 1.0f;
strokeAlpha = 255;
fillAlpha = 150;
}
@Override
public void drawCircle(Vec2 center, float radius, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
setFillColor(color);
setStrokeColor(color);
// calculate the effective radius
tempVec1.set(center.x + radius, center.y + radius);
getWorldToScreenToOut(tempVec1, tempVec1);
getWorldToScreenToOut(center, tempVec2);
canvas.fillCircle(tempVec2.x, tempVec2.y, tempVec1.x - tempVec2.x);
canvas.strokeCircle(tempVec2.x, tempVec2.y, tempVec1.x - tempVec2.x);
}
@Override
public void drawPoint(Vec2 argPoint, float argRadiusOnScreen, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
setFillColor(color);
setStrokeColor(color);
getWorldToScreenToOut(argPoint, tempVec1);
canvas.fillCircle(tempVec1.x, tempVec1.y, argRadiusOnScreen);
}
@Override
public void drawSegment(Vec2 p1, Vec2 p2, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
setStrokeColor(color);
setFillColor(color);
getWorldToScreenToOut(p1, tempVec1);
getWorldToScreenToOut(p2, tempVec2);
canvas.drawLine(tempVec1.x, tempVec1.y, tempVec2.x, tempVec2.y);
}
@Override
public void drawSolidCircle(Vec2 center, float radius, Vec2 axis, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
setFillColor(color);
setStrokeColor(color);
// calculate the effective radius
tempVec1.set(center.x + radius, center.y + radius);
getWorldToScreenToOut(tempVec1, tempVec1);
getWorldToScreenToOut(center, tempVec2);
getWorldToScreenToOut(axis, tempVec3);
canvas.fillCircle(tempVec2.x, tempVec2.y, tempVec1.x - tempVec2.x);
canvas.strokeCircle(tempVec2.x, tempVec2.y, tempVec1.x - tempVec2.x);
}
@Override
public void drawSolidPolygon(Vec2[] vertices, int vertexCount, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
setFillColor(color);
setStrokeColor(color);
Path path = canvas.createPath();
for (int i = 0; i < vertexCount; i++) {
getWorldToScreenToOut(vertices[i], tempVec1);
if (i == 0) {
path.moveTo(tempVec1.x, tempVec1.y);
} else {
path.lineTo(tempVec1.x, tempVec1.y);
}
}
path.close();
canvas.fillPath(path);
canvas.strokePath(path);
}
@Override
public void drawString(float x, float y, String s, Color3f color) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
log().info("drawString not yet implemented in DebugDrawBox2D: " + s);
}
@Override
public void drawTransform(Transform xf) {
if (canvas == null) {
log().error(CANVASERROR);
return;
}
getWorldToScreenToOut(xf.position, tempVec1);
tempVec2.setZero();
float k_axisScale = 0.4f;
canvas.setStrokeColor(Color.rgb(1, 0, 0)); // note: violates
// strokeAlpha
tempVec2.x = xf.position.x + k_axisScale * xf.R.m11;
tempVec2.y = xf.position.y + k_axisScale * xf.R.m12;
getWorldToScreenToOut(tempVec2, tempVec2);
canvas.drawLine(tempVec1.x, tempVec1.y, tempVec2.x, tempVec2.y);
canvas.setStrokeColor(Color.rgb(0, 1, 0)); // note: violates
// strokeAlpha
tempVec2.x = xf.position.x + k_axisScale * xf.R.m21;
tempVec2.y = xf.position.y + k_axisScale * xf.R.m22;
getWorldToScreenToOut(tempVec2, tempVec2);
canvas.drawLine(tempVec1.x, tempVec1.y, tempVec2.x, tempVec2.y);
canvas.setStrokeColor(Color.argb(strokeAlpha, 1, 0, 0)); // restores
// strokeAlpha
}
public Canvas getCanvas() {
return canvas;
}
public int getFillAlpha() {
return fillAlpha;
}
public int getStrokeAlpha() {
return strokeAlpha;
}
public float getStrokeWidth() {
return strokeWidth;
}
@Override
public void setCamera(float x, float y, float scale) {
cameraX = x;
cameraY = y;
cameraScale = scale;
updateCamera();
}
public void setCameraScale(float scale) {
cameraScale = scale;
updateCamera();
}
public void setCameraX(float x) {
cameraX = x;
updateCamera();
}
public void setCameraY(float y) {
cameraY = y;
updateCamera();
}
public void setCanvas(CanvasImage image) {
this.canvas = image.canvas();
canvas.setStrokeWidth(strokeWidth);
}
public void setFillAlpha(int fillAlpha) {
this.fillAlpha = fillAlpha;
}
public void setFlipY(boolean flip) {
viewportTransform.setYFlip(flip);
}
public void setStrokeAlpha(int strokeAlpha) {
this.strokeAlpha = strokeAlpha;
}
public void setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
if (canvas != null) {
canvas.setStrokeWidth(strokeWidth);
}
}
/**
* Sets the fill color from a Color3f
*
* @param color color where (r,g,b) = (x,y,z)
*/
private void setFillColor(Color3f color) {
if (cacheFillR == color.x && cacheFillG == color.y && cacheFillB == color.z) {
// no need to re-set the fill color, just use the cached values
} else {
cacheFillR = color.x;
cacheFillG = color.y;
cacheFillB = color.z;
canvas
.setFillColor(
Color.argb(fillAlpha, (int) (255 * color.x), (int) (255 * color.y),
(int) (255 * color.z)));
}
}
/**
* Sets the stroke color from a Color3f
*
* @param color color where (r,g,b) = (x,y,z)
*/
private void setStrokeColor(Color3f color) {
if (cacheStrokeR == color.x && cacheStrokeG == color.y && cacheStrokeB == color.z) {
// no need to re-set the stroke color, just use the cached values
} else {
cacheStrokeR = color.x;
cacheStrokeG = color.y;
cacheStrokeB = color.z;
canvas.setStrokeColor(
Color.argb(strokeAlpha, (int) (255 * color.x), (int) (255 * color.y),
(int) (255 * color.z)));
}
}
private void updateCamera() {
super.setCamera(cameraX, cameraY, cameraScale);
}
@Override
public void clear() {
canvas.clear();
}
}
| 26.726619 | 88 | 0.634186 |
8d93bd1715aa84117365112debede6d49ec37aa7 | 10,614 | /*
* Copyright 2019 Dmitriy Ponomarenko
*
* 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.dimowner.charttemplate;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.dimowner.charttemplate.model.ChartData;
import com.dimowner.charttemplate.model.Data;
import com.dimowner.charttemplate.util.AndroidUtils;
import com.dimowner.charttemplate.util.TimeUtils;
import com.dimowner.charttemplate.widget.ChartScrollOverlayView;
import com.dimowner.charttemplate.widget.ChartView;
import com.dimowner.charttemplate.widget.ItemView;
import com.google.gson.Gson;
import java.io.IOException;
import timber.log.Timber;
public class MainActivity extends Activity implements View.OnClickListener,
ChartView.OnMoveEventsListener, ChartScrollOverlayView.OnScrollListener {
private ItemView itemView;
private Gson gson = new Gson();
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private ItemsAdapter adapter;
private Parcelable listSaveState;
@Override
protected void onCreate(Bundle savedInstanceState) {
AndroidUtils.update(getApplicationContext());
if (CTApplication.isNightMode()) {
setTheme(R.style.AppTheme_Night);
} else {
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
itemView = findViewById(R.id.itemView);
ImageButton btnNightMode = findViewById(R.id.btnNightMode);
btnNightMode.setOnClickListener(this);
TextView txtTitle = findViewById(R.id.txtTitle);
if (CTApplication.isNightMode()) {
int color = getResources().getColor(R.color.white);
txtTitle.setTextColor(color);
btnNightMode.setImageResource(R.drawable.moon_light7);
} else {
int color = getResources().getColor(R.color.black);
txtTitle.setTextColor(color);
btnNightMode.setImageResource(R.drawable.moon7);
AndroidUtils.statusBarLightMode(this);
}
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new ItemsAdapter();
recyclerView.setAdapter(adapter);
adapter.setOnDetailsListener(new ChartView.OnDetailsListener() {
@Override
public void showDetails(final int num, long time) {
if (num == 5) {
ChartData c = CTApplication.getChartData()[4];
c.setDetailsMode(true);
adapter.setItem(num - 1, c);
} else {
loadChartAsync(num, time, new OnLoadCharListener() {
@Override
public void onLoadChart(ChartData chart) {
if (chart != null) {
adapter.setItem(num - 1, chart);
}
}
});
}
}
@Override
public void hideDetails(int num) {
if (num == 5) {
ChartData c = CTApplication.getChartData()[4];
c.setDetailsMode(false);
adapter.setItem(num - 1, c);
}
adapter.setItem(num-1, CTApplication.getChartData()[num-1]);
}
});
if (savedInstanceState == null || CTApplication.getChartData() == null) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final ChartData d = readDemoData(0);
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.setData(CTApplication.getChartData());
}
});
}
});
thread.start();
}
}
public void setData(ChartData d) {
itemView.setData(d);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
AndroidUtils.update(getApplicationContext());
super.onConfigurationChanged(newConfig);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("item_view1", itemView.onSaveInstanceState());
if (outState != null) {
listSaveState = layoutManager.onSaveInstanceState();
outState.putParcelable("recycler_state", listSaveState);
outState.putBundle("adapter", adapter.onSaveState());
}
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
itemView.onRestoreInstanceState(state.getParcelable("item_view1"));
if (state != null) {
listSaveState = state.getParcelable("recycler_state");
adapter.setData(CTApplication.getChartData());
layoutManager.onRestoreInstanceState(listSaveState);
adapter.onRestoreState(state.getBundle("adapter"));
}
}
/**
* Load chart data
* if time <= 0 load overview chart with selected num
*/
public ChartData loadChart(int chartNum, long time) {
try {
boolean detailsMode;
String location;
if (time > 0) {
location = "contest/" + chartNum + "/" + TimeUtils.getMonthYear(time) + "/"
+ TimeUtils.getDayOfMonth(time) + ".json";
detailsMode = true;
} else {
location = "contest/" + chartNum + "/overview.json";
detailsMode = false;
}
String json1 = AndroidUtils.readAsset(getApplicationContext(), location);
return toChartData(detailsMode, chartNum, gson.fromJson(json1, Data.class));
} catch (IOException | ClassCastException ex) {
Timber.e(ex);
}
return null;
}
public void loadChartAsync(final int num, final long time, final OnLoadCharListener listener) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final ChartData data = loadChart(num, time);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (listener != null) {
listener.onLoadChart(data);
}
}
});
}
});
thread.start();
}
public ChartData readDemoData(int pos) {
try {
// String DATA_ARRAY = "dataArray";
// String COLUMNS = "columns";
// String TYPES = "types";
// String COLORS = "colors";
// String NAMES = "names";
// String json = AndroidUtils.readAsset(getApplicationContext(), "telegram_chart_data.json");
String json1 = AndroidUtils.readAsset(getApplicationContext(), "contest/1/overview.json");
String json2 = AndroidUtils.readAsset(getApplicationContext(), "contest/2/overview.json");
String json3 = AndroidUtils.readAsset(getApplicationContext(), "contest/3/overview.json");
String json4 = AndroidUtils.readAsset(getApplicationContext(), "contest/4/overview.json");
String json5 = AndroidUtils.readAsset(getApplicationContext(), "contest/5/overview.json");
// Timber.v("json = %s", json);
// JSONObject jo = new JSONObject(json);
// JSONArray joArray = jo.getJSONArray(DATA_ARRAY);
// Data[] dataValues = new Data[joArray.length()];
// for (int i = 0; i < joArray.length(); i++) {
// Object[][] columns;
// Map<String, String> types;
// Map<String, String> names;
// Map<String, String> colors;
// JSONObject joItem = (JSONObject) joArray.get(i);
//
// names = AndroidUtils.jsonToMap(joItem.getJSONObject(NAMES));
// types = AndroidUtils.jsonToMap(joItem.getJSONObject(TYPES));
// colors = AndroidUtils.jsonToMap(joItem.getJSONObject(COLORS));
//
// JSONArray colArray = joItem.getJSONArray(COLUMNS);
// List<Object> list = AndroidUtils.toList(colArray);
// columns = new Object[list.size()][];
//
// for (int j = 0; j < list.size(); j++) {
// List<Object> l2 = (List<Object>) list.get(j);
// Object[] a = new Object[l2.size()];
// for (int k = 0; k < l2.size(); k++) {
// a[k] = l2.get(k);
// }
// columns[j] = a;
// }
// dataValues[i] = new Data(columns, types, names, colors);
// }
Gson gson = new Gson();
// DataArray data = gson.fromJson(json, DataArray.class);
Data data1 = gson.fromJson(json1, Data.class);
Data data2 = gson.fromJson(json2, Data.class);
Data data3 = gson.fromJson(json3, Data.class);
Data data4 = gson.fromJson(json4, Data.class);
Data data5 = gson.fromJson(json5, Data.class);
// dataArray = array.getDataArray();
ChartData[] chartData = new ChartData[] {toChartData(false, 1, data1), toChartData(false, 2, data2),
toChartData(false, 3, data3), toChartData(false, 4, data4), toChartData(false, 5, data5)};
CTApplication.setChartData(chartData);
// CTApplication.setData(new Data[]{data1, data2, data3, data4, data5});
// CTApplication.setData(dataValues);
// } catch (IOException | ClassCastException | JSONException ex) {
} catch (IOException | ClassCastException ex) {
Timber.e(ex);
return null;
}
// return toChartData(CTApplication.getData()[pos]);
return CTApplication.getChartData()[pos];
}
private ChartData toChartData(boolean detailsMode, int chartNum, Data d) {
if (d != null) {
String[] keys = d.getColumnsKeys();
int[][] vals = new int[keys.length][d.getDataLength()];
String[] names = new String[keys.length];
String[] types = new String[keys.length];
String[] colors = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
vals[i] = d.getValues(keys[i]);
names[i] = d.getName(keys[i]);
types[i] = d.getType(keys[i]);
colors[i] = d.getColor(keys[i]);
}
return new ChartData(detailsMode, chartNum, d.getTimeArray(), vals, names, types, colors,
d.isYscaled(), d.isPercentage(), d.isStacked());
}
return null;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnNightMode) {
CTApplication.setNightMode(!CTApplication.isNightMode());
recreate();
}
}
@Override
public void disallowTouchEvent() {
// scrollView.requestDisallowInterceptTouchEvent(true);
// recyclerView.requestDisallowInterceptTouchEvent(true);
}
@Override
public void allowTouchEvent() {
// scrollView.requestDisallowInterceptTouchEvent(false);
// recyclerView.requestDisallowInterceptTouchEvent(false);
}
@Override
public void onScroll(float x, float size) {
// chartView.scrollPos(x, size);
// scrollView.requestDisallowInterceptTouchEvent(true);
// recyclerView.requestDisallowInterceptTouchEvent(true);
}
public interface OnLoadCharListener {
void onLoadChart(ChartData chart);
}
}
| 32.458716 | 103 | 0.704353 |
12c052851c8d78e5484699337775c5b2e3364b9b | 1,572 | package com.callfire.api11.client.api.common.model;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Generic list response
*/
public class ResourceList<T> {
// name of entity's type
@JsonIgnore
private String name;
@JsonProperty("@totalResults")
private Integer totalResults;
@JsonIgnore
private List<T> items = new ArrayList<>();
public ResourceList() {
}
public ResourceList(List<T> items, Class<T> itemsType) {
this.items = items;
this.name = itemsType.getSimpleName();
this.totalResults = items.size();
}
public List<T> get() {
return items;
}
@JsonAnySetter
private void setItems(String name, List<T> items) {
this.name = name;
this.items = items;
}
@JsonAnyGetter
private Map<String, List<T>> getItems() {
Map<String, List<T>> mapping = new HashMap<>();
mapping.put(name, items);
return mapping;
}
public Integer getTotalResults() {
return totalResults;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("totalResults", totalResults)
.append("items", items)
.toString();
}
}
| 24.5625 | 60 | 0.65458 |
84db7e8315a554b5dbf8e2651daafd6deeed77bc | 1,574 | package fi.iki.maf;
import java.util.ArrayList;
public class Option {
static public ArrayList<Option> getOptionList()
{
ArrayList<Option> options = GameData.getOptions();
return options;
}
public Option(int firstRound, int lastRound, String beforeText, String afterText, String missedText, String completedText, int missedScoreChange, int completedScoreChange, Option prerequisite)
{
this.firstRound = firstRound;
this.lastRound = lastRound;
this.beforeText = beforeText;
this.afterText = afterText;
this.missedText = missedText;
this.completedText = completedText;
this.missedScoreChange = missedScoreChange;
this.completedScoreChange = completedScoreChange;
this.used = false;
this.prerequisite = prerequisite;
}
public final int firstRound;
public final int lastRound;
public final String beforeText;
public final String afterText;
public final String missedText;
public final String completedText;
public final int missedScoreChange;
public final int completedScoreChange;
public final Option prerequisite;
private boolean used;
boolean isActive(int round)
{
if (prerequisite != null && !prerequisite.isUsed()) return false;
if (isUsed()) return false;
return round >= firstRound && round <= lastRound;
}
String getBeforeText() { return beforeText; }
String getAfterText() { return afterText; }
void use() { used = true; }
boolean isUsed() { return used; }
int getScoreChange() { return used ? completedScoreChange : missedScoreChange; }
String getResultText() { return used ? completedText : missedText; }
}
| 30.862745 | 193 | 0.759848 |
2778482b6e42655aa758d1cf011635ed2b72f1e4 | 92 | package cn.aezo.springboot.datasource.enums;
public enum HobbyEnum {
GAME, CODE, READ
} | 18.4 | 44 | 0.75 |
c5523c73d83bfd25754293e15002df265f594d28 | 1,832 | /*
* 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.nlpcraft.model;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* Annotation to define an intent on the method serving as its callback. This annotation takes a string value
* that defines an intent via intent DSL.
* <p>
* Read full documentation in <a target=_ href="https://nlpcraft.apache.org/intent-matching.html">Intent Matching</a> section and review
* <a target=_ href="https://github.com/apache/incubator-nlpcraft/tree/master/nlpcraft/src/main/scala/org/apache/nlpcraft/examples/">examples</a>.
*
* @see NCIntentRef
* @see NCIntentTerm
* @see NCIntentExample
* @see NCIntentSkip
* @see NCIntentMatch
* @see NCModel#onMatchedIntent(NCIntentMatch)
*/
@Documented
@Retention(value=RUNTIME)
@Target(value=METHOD)
public @interface NCIntent {
/**
* Intent specification using intent DSL.
*
* @return Intent specification using intent DSL.
*/
String value() default "";
}
| 36.64 | 146 | 0.74345 |
f203e23c48788e637c16b26c9270d7c8e38ecc3b | 249 | package com.lyq.util.hibernate;
import com.lyq.model.PaymentWay;
/**
* 支付方式Hibernate映射类型
* @author Li Yongqiang
*/
public class PaymentWayType extends EnumType<PaymentWay> {
public PaymentWayType() {
super(PaymentWay.class);
}
}
| 19.153846 | 59 | 0.710843 |
554243d0e08a3ea470b8094ca5498f66135d2130 | 9,466 | /*
* 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 tcp.client.view;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.ObjectWrapper;
import model.Customer;
import tcp.client.control.ClientCtr;
/**
*
* @author Asus
*/
public class ClientFrm extends javax.swing.JFrame {
/**
* Creates new form RegisterFrm
*/
private ClientCtr mySocket;
public ClientFrm(ClientCtr socket) {
mySocket = socket;
initComponents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mySocket.getActiveFunction().add(new ObjectWrapper(ObjectWrapper.REPLY_REGISTER_CLIENT, this));
}
/**
* 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() {
jLabel10 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jTextFieldName = new javax.swing.JTextField();
jTextFieldAddress = new javax.swing.JTextField();
jTextFieldTel = new javax.swing.JTextField();
jButtonConfirm = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
jTextFieldEmail = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jTextFieldNote = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel10.setText("REGISTER FORM");
jLabel5.setText("Name:");
jLabel7.setText("Address:");
jLabel8.setText("Tel:");
jButtonConfirm.setText("Confirm");
jButtonConfirm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonConfirmActionPerformed(evt);
}
});
jLabel9.setText("Email:");
jLabel11.setText("Note:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 111, Short.MAX_VALUE)
.addComponent(jLabel10)
.addGap(117, 117, 117))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldNote, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(jTextFieldName))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldAddress)
.addComponent(jTextFieldTel))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(jButtonConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jTextFieldTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(jTextFieldNote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButtonConfirm)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConfirmActionPerformed
// TODO add your handling code here:
Customer customer = new Customer();
customer.setName(jTextFieldName.getText());
customer.setAddress(jTextFieldAddress.getText());
customer.setTel(jTextFieldTel.getText());
customer.setEmail(jTextFieldEmail.getText());
customer.setNote(jTextFieldNote.getText());
mySocket.sendData(new ObjectWrapper(ObjectWrapper.REGISTER_CLIENT, customer));
}//GEN-LAST:event_jButtonConfirmActionPerformed
/**
* @param args the command line arguments
*/
public void receivedDataProcessing(ObjectWrapper data) {
if(data.getData().equals("true")){
JOptionPane.showMessageDialog(this, "AddClient succesfully!");
this.dispose();
}
else {
JOptionPane.showMessageDialog(this, "Error when AddClient!");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonConfirm;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JTextField jTextFieldAddress;
private javax.swing.JTextField jTextFieldEmail;
private javax.swing.JTextField jTextFieldName;
private javax.swing.JTextField jTextFieldNote;
private javax.swing.JTextField jTextFieldTel;
// End of variables declaration//GEN-END:variables
}
| 50.892473 | 170 | 0.65149 |
70c95bfedd1450c1de4315fcd2456a7dee6819c9 | 2,279 | package com.jocelyne.mesh.instructor.hype;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.jocelyne.mesh.R;
import com.jocelyne.mesh.session_management.Student;
import java.util.Locale;
import java.util.Map;
public class PresentStudentAdapter extends BaseAdapter {
private Map<String, Student> mPresentStudents;
private Context context;
private LayoutInflater inflater = null;
public PresentStudentAdapter(Context context, Map<String, Student> mPresentStudents) {
this.context = context;
this.mPresentStudents = mPresentStudents;
}
protected LayoutInflater getInflater() {
if (inflater == null) {
inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
return inflater;
}
protected Context getContext() {
return context;
}
protected Map<String, Student> getPresentStudents() {
return mPresentStudents;
}
@Override
public int getCount() {
return mPresentStudents.size();
}
@Override
public Object getItem(int position) {
return getPresentStudents().values().toArray()[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if (vi == null)
vi = getInflater().inflate(R.layout.present_student_cell_view, null);
TextView presentStudentID = (TextView)vi.findViewById(R.id.present_student_id);
Student presentStudent = (Student) getItem(position);
presentStudentID.setText(String.format(Locale.US,"%d", presentStudent.getInstance().getUserIdentifier()));
ImageView statusImageView = vi.findViewById(R.id.student_status);
if (presentStudent.lost) {
statusImageView.setImageResource(R.drawable.ic_red_circle_24dp);
} else {
statusImageView.setImageResource(R.drawable.ic_green_circle_24dp);
}
return vi;
}
}
| 27.457831 | 114 | 0.694164 |
c973064f8d3955346ea5b50be877d8fc15ca87ee | 1,073 | package interceptor;
/**
* @Author Froid_Li
* @Email 269504518@qq.com
* @Date 2017/9/5 14:37
*/
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsonAccessInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Methods","*");
response.addHeader("Access-Control-Max-Age","3600"); // 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
response.addHeader("Access-Control-Allow-Headers", "Authorization,x-requested-with,content-type");
response.addHeader("Access-Control-Allow-Credentials","true");
if(request.getMethod().equalsIgnoreCase("OPTIONS")){
return false;
}
return super.preHandle(request, response, handler);
}
}
| 35.766667 | 106 | 0.707363 |
5795d5312a12d9a4e6093dd45d89aea28b9559d8 | 1,828 | package nl.mvdr.adventofcode.adventofcode2020.day18;
import org.junit.jupiter.api.Test;
import nl.mvdr.adventofcode.SolverTest;
/**
* Unit test cases for {@link OperationOrderPart1}.
*
* @author Martijn van de Rijdt
*/
public class OperationOrderPart1Test extends SolverTest<OperationOrderPart1> {
/** Constructor. */
public OperationOrderPart1Test() {
super(OperationOrderPart1.class);
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample0() {
assertSolution("71", "example-day18-2020-0.txt");
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample1() {
assertSolution("51", "example-day18-2020-1.txt");
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample2() {
assertSolution("26", "example-day18-2020-2.txt");
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample3() {
assertSolution("437", "example-day18-2020-3.txt");
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample4() {
assertSolution("12240", "example-day18-2020-4.txt");
}
/** Test case based on an example from the puzzle text. */
@Test
public void testExample5() {
assertSolution("13632", "example-day18-2020-5.txt");
}
/** Test case based on the examples from the puzzle text. */
@Test
public void testExample6() {
assertSolution("26457", "example-day18-2020-6.txt");
}
/** Test case based on the accepted solution. */
@Test
public void testSolution() {
assertSolution("8929569623593", "input-day18-2020.txt");
}
}
| 27.283582 | 78 | 0.626915 |
3d9297ddedd8558b3ae16e827090bd287a47c3a9 | 1,162 | /*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.restlets;
import junit.framework.TestCase;
import org.restlet.data.MediaType;
import org.restlet.data.Metadata;
/**
* @author Saurabh Agrawal
* @crated Jan 16, 2009
*/
public class PscMetadataServiceTest extends TestCase {
private PscMetadataService metadataService;
@Override
protected void setUp() throws Exception {
super.setUp();
metadataService = new PscMetadataService();
}
public void testConstructor() {
Metadata metadata = metadataService.getMetadata("ics");
assertNotNull("must support ics extention", metadata);
assertEquals("must be of type calendar", MediaType.TEXT_CALENDAR, metadata);
}
public void testCsvConstructor() {
Metadata metadata = metadataService.getMetadata("csv");
assertNotNull("must support csv extention", metadata);
assertEquals("must be of type calendar", PscMetadataService.TEXT_CSV, metadata);
}
}
| 27.666667 | 88 | 0.716007 |
08514e414df2e57fa5bddcfeb9c083265aeee7fe | 144 | package com.agatsenko.mongo.mapper.util;
@FunctionalInterface
public interface Procedure3<A1, A2, A3> {
void apply(A1 a1, A2 a2, A3 a3);
}
| 20.571429 | 41 | 0.729167 |
73199a0b4d59af0c17b139bcc89f0f13c0a58b78 | 2,647 | package noobanidus.mods.glimmering.client.render.entity.layer;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.entity.IEntityRenderer;
import net.minecraft.client.renderer.entity.layers.LayerRenderer;
import net.minecraft.client.renderer.entity.model.EntityModel;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import noobanidus.mods.glimmering.Glimmering;
import noobanidus.mods.glimmering.entity.GlimmerEntity;
@OnlyIn(Dist.CLIENT)
public class LayerElectric<E extends GlimmerEntity, M extends EntityModel<E>> extends LayerRenderer<E, M> {
private static final ResourceLocation LIGHTNING_TEXTURE = new ResourceLocation(Glimmering.MODID, "textures/entity/gold_electric.png");
private M glimmerModel; // = new GlimmerModel();
public LayerElectric(IEntityRenderer<E, M> renderer, M model) {
super(renderer);
this.glimmerModel = model;
}
public void render(E glimmer, float p_212842_2_, float p_212842_3_, float p_212842_4_, float p_212842_5_, float p_212842_6_, float p_212842_7_, float p_212842_8_) {
if (glimmer.recentlyPowered()) {
GlStateManager.depthMask(true);
this.bindTexture(LIGHTNING_TEXTURE);
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
float lvt_10_1_ = (float) glimmer.ticksExisted + p_212842_4_;
GlStateManager.translatef(lvt_10_1_ * 0.01F, lvt_10_1_ * 0.01F, 0.0F);
GlStateManager.matrixMode(5888);
GlStateManager.enableBlend();
GlStateManager.color4f(0.5F, 0.5F, 0.5F, 1.0F);
GlStateManager.disableLighting();
GlStateManager.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE);
this.getEntityModel().setModelAttributes(this.glimmerModel);
GameRenderer renderer = Minecraft.getInstance().gameRenderer;
renderer.setupFogColor(true);
GlStateManager.pushMatrix();
GlStateManager.scalef(1.1f, 1.1f, 1.1f);
GlStateManager.translatef(0, -0.08f, 0);
this.glimmerModel.render(glimmer, p_212842_2_, p_212842_3_, p_212842_5_, p_212842_6_, p_212842_7_, p_212842_8_);
GlStateManager.popMatrix();
renderer.setupFogColor(false);
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
GlStateManager.matrixMode(5888);
GlStateManager.enableLighting();
GlStateManager.disableBlend();
GlStateManager.depthMask(true);
}
}
public boolean shouldCombineTextures() {
return false;
}
}
| 44.116667 | 166 | 0.762372 |
c9870c25ff1c096d2e565a83c25c692f4fbb804b | 3,357 | /*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License"). See License in the project root for license information.
*
*/
package com.linkedin.kafka.cruisecontrol.analyzer;
import com.linkedin.kafka.cruisecontrol.analyzer.goals.Goal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
/**
* The state for the analyzer.
*/
public class AnalyzerState {
private static final String IS_PROPOSAL_READY = "isProposalReady";
private static final String READY_GOALS = "readyGoals";
private static final String STATUS = "status";
private static final String READY = "ready";
private static final String NOT_READY = "notReady";
private static final String NAME = "name";
private static final String MODEL_COMPLETE_REQUIREMENT = "modelCompleteRequirement";
private static final String GOAL_READINESS = "goalReadiness";
private final boolean _isProposalReady;
private final Map<Goal, Boolean> _readyGoals;
/**
* @param isProposalReady True if the goal optimizer has valid cached proposals for optimization with the default goals.
* @param readyGoals Goals that are ready for self-healing.
*/
public AnalyzerState(boolean isProposalReady, Map<Goal, Boolean> readyGoals) {
_isProposalReady = isProposalReady;
_readyGoals = readyGoals;
}
/**
* @return True if the proposal is ready, false otherwise.
*/
public boolean proposalReady() {
return _isProposalReady;
}
/**
* @return A map of ready goals.
*/
public Map<Goal, Boolean> readyGoals() {
return _readyGoals;
}
/**
* @param verbose True if verbose, false otherwise.
* @return An object that can be further used to encode into JSON.
*/
public Map<String, Object> getJsonStructure(boolean verbose) {
Map<String, Object> analyzerState = new HashMap<>(verbose ? 3 : 2);
Set<String> readyGoalNames = new HashSet<>();
for (Map.Entry<Goal, Boolean> entry : _readyGoals.entrySet()) {
if (entry.getValue()) {
readyGoalNames.add(entry.getKey().name());
}
}
analyzerState.put(IS_PROPOSAL_READY, _isProposalReady);
analyzerState.put(READY_GOALS, readyGoalNames);
if (verbose) {
List<Object> goalReadinessList = new ArrayList<>(_readyGoals.size());
for (Map.Entry<Goal, Boolean> entry : _readyGoals.entrySet()) {
Goal goal = entry.getKey();
Map<String, Object> goalReadinessRecord = new HashMap<>(3);
goalReadinessRecord.put(NAME, goal.getClass().getSimpleName());
goalReadinessRecord.put(MODEL_COMPLETE_REQUIREMENT, goal.clusterModelCompletenessRequirements().getJsonStructure());
goalReadinessRecord.put(STATUS, entry.getValue() ? READY : NOT_READY);
goalReadinessList.add(goalReadinessRecord);
}
analyzerState.put(GOAL_READINESS, goalReadinessList);
}
return analyzerState;
}
@Override
public String toString() {
Set<String> readyGoalNames = new HashSet<>();
for (Map.Entry<Goal, Boolean> entry : _readyGoals.entrySet()) {
if (entry.getValue()) {
readyGoalNames.add(entry.getKey().getClass().getSimpleName());
}
}
return String.format("{%s: %s, %s: %s}", IS_PROPOSAL_READY, _isProposalReady, READY_GOALS, readyGoalNames);
}
}
| 35.336842 | 146 | 0.708966 |
2029dc5d5b1fff4fc844f588efe733dbf46e6621 | 775 | package com.gpnk.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Map;
@Getter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class WeatherReport {
private double temp;
private String skyCondition;
@JsonProperty("currently")
public void fromDarkSkyJson(final Map<String, String> currently) {
this.temp = Double.parseDouble(currently.get("temperature"));
this.skyCondition = currently.get("summary");
}
@Override
public String toString() {
return temp + " degrees and " + skyCondition;
}
}
| 25 | 70 | 0.745806 |
cfe160abe59145ab58bca4926ad3e412bc4786ea | 3,697 | package com.bullhornsdk.data.model.entity.association.paybill;
import com.bullhornsdk.data.model.entity.association.AssociationField;
import com.bullhornsdk.data.model.entity.association.EntityAssociations;
import com.bullhornsdk.data.model.entity.association.standard.StandardAssociationField;
import com.bullhornsdk.data.model.entity.core.paybill.charge.BillableCharge;
import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatement;
import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatementDistributionBatch;
import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatementDistributionBatch;
import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatementLineDistribution;
import com.bullhornsdk.data.model.entity.core.paybill.transaction.BillMasterTransaction;
import com.bullhornsdk.data.model.entity.core.type.BullhornEntity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fayranne.lipton 4/10/2020
*/
public class InvoiceStatementDistributionBatchAssociations implements EntityAssociations<InvoiceStatementDistributionBatch> {
private final AssociationField<InvoiceStatementDistributionBatch, InvoiceStatementLineDistribution> invoiceStatementLineDistributions = instantiateAssociationField("invoiceStatementLineDistributions", InvoiceStatementLineDistribution.class);
private final AssociationField<InvoiceStatementDistributionBatch, InvoiceStatement> invoiceStatements = instantiateAssociationField("invoiceStatements", InvoiceStatement.class);
private List<AssociationField<InvoiceStatementDistributionBatch, ? extends BullhornEntity>> allAssociations;
private static final InvoiceStatementDistributionBatchAssociations INSTANCE = new InvoiceStatementDistributionBatchAssociations();
private InvoiceStatementDistributionBatchAssociations() {
super();
}
public static InvoiceStatementDistributionBatchAssociations getInstance() {
return INSTANCE;
}
public AssociationField<InvoiceStatementDistributionBatch, InvoiceStatementLineDistribution> invoiceStatementLineDistributions() {
return invoiceStatementLineDistributions;
}
public AssociationField<InvoiceStatementDistributionBatch, InvoiceStatement> invoiceStatements() {
return invoiceStatements;
}
private <E extends BullhornEntity> AssociationField<InvoiceStatementDistributionBatch, E> instantiateAssociationField(String associationName, Class<E> associationType) {
return new StandardAssociationField<InvoiceStatementDistributionBatch, E>(associationName, associationType);
}
@Override
public List<AssociationField<InvoiceStatementDistributionBatch, ? extends BullhornEntity>> allAssociations() {
if (allAssociations == null) {
allAssociations = new ArrayList<AssociationField<InvoiceStatementDistributionBatch, ? extends BullhornEntity>>();
allAssociations.add(invoiceStatementLineDistributions());
allAssociations.add(invoiceStatements());
}
return allAssociations;
}
@Override
public AssociationField<InvoiceStatementDistributionBatch, ? extends BullhornEntity> getAssociation(String associationName) {
for (AssociationField<InvoiceStatementDistributionBatch, ? extends BullhornEntity> associationField : allAssociations()) {
if (associationName.equalsIgnoreCase(associationField.getAssociationFieldName())) {
return associationField;
}
}
throw new IllegalArgumentException("There is no association on entity InvoiceStatementDistributionBatch called: " + associationName);
}
}
| 52.070423 | 245 | 0.80687 |
c15630f0c400e8d0aba0800d0c09be6c4ed663bc | 30,781 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.animation;
import static androidx.core.animation.AnimatorSetTest.AnimEvent.EventType.END;
import static androidx.core.animation.AnimatorSetTest.AnimEvent.EventType.START;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import android.util.Property;
import androidx.annotation.NonNull;
import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class AnimatorSetTest {
private AnimatorSet mAnimatorSet;
private float mPreviousDurationScale = 1.0f;
private ValueAnimator mAnim1;
private ValueAnimator mAnim2;
private static final float EPSILON = 0.001f;
enum PlayOrder {
SEQUENTIAL,
TOGETHER
}
@Before
public void setup() {
mPreviousDurationScale = ValueAnimator.getDurationScale();
ValueAnimator.setDurationScale(1.0f);
mAnim1 = ValueAnimator.ofFloat(0f, 100f);
mAnim2 = ValueAnimator.ofInt(100, 200);
}
@After
public void tearDown() {
ValueAnimator.setDurationScale(mPreviousDurationScale);
}
@ClassRule
public static AnimatorTestRule sAnimatorTestRule = new AnimatorTestRule();
@UiThreadTest
@Test
public void testPlaySequentially() {
List<Animator> animators = new ArrayList<Animator>();
animators.add(mAnim1);
animators.add(mAnim2);
mAnimatorSet = new AnimatorSet();
mAnimatorSet.playSequentially(animators);
verifyPlayOrder(mAnimatorSet, new Animator[] {mAnim1, mAnim2}, PlayOrder.SEQUENTIAL);
AnimatorSet set = new AnimatorSet();
set.playSequentially(mAnim1, mAnim2);
verifyPlayOrder(set, new Animator[] {mAnim1, mAnim2}, PlayOrder.SEQUENTIAL);
}
@UiThreadTest
@Test
public void testPlayTogether() {
List<Animator> animators = new ArrayList<Animator>();
animators.add(mAnim1);
animators.add(mAnim2);
mAnimatorSet = new AnimatorSet();
mAnimatorSet.playTogether(animators);
verifyPlayOrder(mAnimatorSet, new Animator[] {mAnim1, mAnim2}, PlayOrder.TOGETHER);
AnimatorSet set = new AnimatorSet();
set.playTogether(mAnim1, mAnim2);
verifyPlayOrder(set, new Animator[] {mAnim1, mAnim2}, PlayOrder.TOGETHER);
}
/**
* Start the animator, and verify the animators are played sequentially in the order that is
* defined in the array.
*
* @param set AnimatorSet to be started and verified
* @param animators animators that we put in the AnimatorSet, in the order that they'll play
*/
private void verifyPlayOrder(final AnimatorSet set, Animator[] animators, PlayOrder playOrder) {
ArrayList<AnimEvent> animEvents = registerAnimatorsForEvents(animators);
set.start();
sAnimatorTestRule.advanceTimeBy(set.getStartDelay());
for (int i = 0; i < animators.length; i++) {
sAnimatorTestRule.advanceTimeBy(animators[i].getTotalDuration());
}
// All animations should finish by now
int animatorNum = animators.length;
assertEquals(animatorNum * 2, animEvents.size());
if (playOrder == PlayOrder.SEQUENTIAL) {
for (int i = 0; i < animatorNum; i++) {
assertEquals(START, animEvents.get(i * 2).mType);
assertEquals(animators[i], animEvents.get(i * 2).mAnim);
assertEquals(END, animEvents.get(i * 2 + 1).mType);
assertEquals(animators[i], animEvents.get(i * 2 + 1).mAnim);
}
} else {
for (int i = 0; i < animatorNum; i++) {
assertEquals(START, animEvents.get(i).mType);
assertEquals(animators[i], animEvents.get(i).mAnim);
}
}
}
private ArrayList<AnimEvent> registerAnimatorsForEvents(Animator[] animators) {
final ArrayList<AnimEvent> animEvents = new ArrayList<>();
Animator.AnimatorListener listener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(@NonNull Animator animation) {
animEvents.add(new AnimEvent(START, animation));
}
@Override
public void onAnimationEnd(@NonNull Animator animation) {
animEvents.add(new AnimEvent(END, animation));
}
@Override
public void onAnimationCancel(@NonNull Animator animation) {
}
@Override
public void onAnimationRepeat(@NonNull Animator animation) {
}
};
for (int i = 0; i < animators.length; i++) {
animators[i].removeListener(listener);
animators[i].addListener(listener);
}
return animEvents;
}
@UiThreadTest
@Test
public void testPlayBeforeAfter() {
final ValueAnimator anim3 = ValueAnimator.ofFloat(200f, 300f);
AnimatorSet set = new AnimatorSet();
set.play(mAnim1).before(mAnim2).after(anim3);
verifyPlayOrder(set, new Animator[] {anim3, mAnim1, mAnim2}, PlayOrder.SEQUENTIAL);
}
@UiThreadTest
@Test
public void testListenerCallbackOnEmptySet() {
// Create an AnimatorSet that only contains one empty AnimatorSet, and checks the callback
// sequence by checking the time stamps of the callbacks.
final AnimatorSet emptySet = new AnimatorSet();
final AnimatorSet set = new AnimatorSet();
set.play(emptySet);
ArrayList<AnimEvent> animEvents = registerAnimatorsForEvents(
new Animator[] {emptySet, set});
set.start();
sAnimatorTestRule.advanceTimeBy(10);
// Check callback sequence via Animator Events
assertEquals(animEvents.get(0).mAnim, set);
assertEquals(animEvents.get(0).mType, START);
assertEquals(animEvents.get(1).mAnim, emptySet);
assertEquals(animEvents.get(1).mType, START);
assertEquals(animEvents.get(2).mAnim, emptySet);
assertEquals(animEvents.get(2).mType, END);
assertEquals(animEvents.get(3).mAnim, set);
assertEquals(animEvents.get(3).mType, END);
}
@UiThreadTest
@Test
public void testPause() {
final ValueAnimator anim = ValueAnimator.ofFloat(0f, 1000f);
anim.setDuration(1000L);
anim.setInterpolator(new LinearInterpolator());
final AnimatorSet set = new AnimatorSet();
set.playTogether(anim);
set.start();
sAnimatorTestRule.advanceTimeBy(300);
assertEquals(300L, set.getCurrentPlayTime());
assertEquals(300f, (float) anim.getAnimatedValue(), EPSILON);
set.pause();
sAnimatorTestRule.advanceTimeBy(300);
assertEquals(300L, set.getCurrentPlayTime());
assertEquals(300f, (float) anim.getAnimatedValue(), EPSILON);
set.resume();
sAnimatorTestRule.advanceTimeBy(300);
assertEquals(600L, set.getCurrentPlayTime());
assertEquals(600f, (float) anim.getAnimatedValue(), EPSILON);
}
@UiThreadTest
@Test
public void testPauseAndResume() {
final AnimatorSet set = new AnimatorSet();
set.playTogether(mAnim1, mAnim2);
set.start();
sAnimatorTestRule.advanceTimeBy(0);
set.pause();
assertTrue(set.isPaused());
sAnimatorTestRule.advanceTimeBy(5);
// After 10s, set is still not yet finished.
sAnimatorTestRule.advanceTimeBy(10000);
assertTrue(set.isStarted());
assertTrue(set.isPaused());
set.resume();
sAnimatorTestRule.advanceTimeBy(5);
assertTrue(set.isStarted());
assertFalse(set.isPaused());
sAnimatorTestRule.advanceTimeBy(10000);
assertFalse(set.isStarted());
assertFalse(set.isPaused());
}
@UiThreadTest
@Test
public void testPauseBeforeStart() {
final AnimatorSet set = new AnimatorSet();
set.playSequentially(mAnim1, mAnim2);
set.pause();
// Verify that pause should have no effect on a not-yet-started animator.
assertFalse(set.isPaused());
set.start();
sAnimatorTestRule.advanceTimeBy(0);
assertTrue(set.isStarted());
sAnimatorTestRule.advanceTimeBy(set.getTotalDuration());
assertFalse(set.isStarted());
}
@UiThreadTest
@Test
public void testPauseRewindResume() {
final AnimatorSet set = new AnimatorSet();
final ValueAnimator a1 = ValueAnimator.ofFloat(0f, 1000f);
a1.setDuration(1000);
final ValueAnimator a2 = ValueAnimator.ofInt(0, 1000);
a2.setDuration(1000);
set.playSequentially(a1, a2);
set.setInterpolator(new LinearInterpolator());
assertEquals(2000L, set.getTotalDuration());
set.start();
sAnimatorTestRule.advanceTimeBy(1500L);
assertEquals(1000f, (float) a1.getAnimatedValue(), EPSILON);
assertEquals(500, (int) a2.getAnimatedValue());
set.pause();
set.setCurrentPlayTime(500L);
assertEquals(500f, (float) a1.getAnimatedValue(), EPSILON);
assertEquals(0, (int) a2.getAnimatedValue());
set.resume();
sAnimatorTestRule.advanceTimeBy(250L);
assertEquals(750f, (float) a1.getAnimatedValue(), EPSILON);
assertEquals(0, (int) a2.getAnimatedValue());
sAnimatorTestRule.advanceTimeBy(750L);
assertEquals(1000f, (float) a1.getAnimatedValue(), EPSILON);
assertEquals(500, (int) a2.getAnimatedValue());
}
@UiThreadTest
@Test
public void testSeekAfterPause() {
final AnimatorSet set = new AnimatorSet();
ValueAnimator a1 = ValueAnimator.ofFloat(0f, 50f);
a1.setDuration(50);
ValueAnimator a2 = ValueAnimator.ofFloat(50, 100f);
a2.setDuration(50);
set.playSequentially(a1, a2);
set.setInterpolator(new LinearInterpolator());
set.start();
set.pause();
set.setCurrentPlayTime(60);
assertEquals((long) set.getCurrentPlayTime(), 60);
assertEquals((float) a1.getAnimatedValue(), 50f, EPSILON);
assertEquals((float) a2.getAnimatedValue(), 60f, EPSILON);
set.setCurrentPlayTime(40);
assertEquals((long) set.getCurrentPlayTime(), 40);
assertEquals((float) a1.getAnimatedValue(), 40f, EPSILON);
assertEquals((float) a2.getAnimatedValue(), 50f, EPSILON);
set.cancel();
}
@UiThreadTest
@Test
public void testSeekListener() {
final AnimatorSet animatorSet = new AnimatorSet();
ValueAnimator anim = ValueAnimator.ofFloat(0f, 1000f);
anim.setDuration(1000);
animatorSet.playTogether(anim);
final AtomicLong notifiedPlayTime = new AtomicLong(0L);
animatorSet.addUpdateListener((animation) -> {
final AnimatorSet set = (AnimatorSet) animation;
notifiedPlayTime.set(set.getCurrentPlayTime());
});
animatorSet.setCurrentPlayTime(0L);
assertEquals(0L, notifiedPlayTime.get());
animatorSet.setCurrentPlayTime(100L);
assertEquals(100L, notifiedPlayTime.get());
}
@UiThreadTest
@Test
public void testDuration() {
mAnim1.setRepeatCount(ValueAnimator.INFINITE);
Animator[] animatorArray = {mAnim1, mAnim2};
mAnimatorSet = new AnimatorSet();
mAnimatorSet.playTogether(animatorArray);
mAnimatorSet.setDuration(1000);
assertEquals(mAnimatorSet.getDuration(), 1000);
}
@UiThreadTest
@Test
public void testStartDelay() {
mAnim1.setRepeatCount(ValueAnimator.INFINITE);
Animator[] animatorArray = {mAnim1, mAnim2};
mAnimatorSet = new AnimatorSet();
mAnimatorSet.playTogether(animatorArray);
mAnimatorSet.setStartDelay(10);
assertEquals(mAnimatorSet.getStartDelay(), 10);
}
/**
* This test sets up an AnimatorSet with start delay. One of the child animators also has
* start delay. We then verify that start delay was handled correctly on both AnimatorSet
* and individual animator level.
*/
@UiThreadTest
@Test
public void testReverseWithStartDelay() {
ValueAnimator a1 = ValueAnimator.ofFloat(0f, 1f);
a1.setDuration(200);
ValueAnimator a2 = ValueAnimator.ofFloat(1f, 2f);
a2.setDuration(200);
// Set start delay on a2 so that the delay is passed 100ms after a1 is finished.
a2.setStartDelay(300);
AnimatorSet set = new AnimatorSet();
set.playTogether(a1, a2);
set.setStartDelay(1000);
set.reverse();
sAnimatorTestRule.advanceTimeBy(0);
assertTrue(a2.isStarted());
assertTrue(a2.isRunning());
assertFalse(a1.isStarted());
// a2 should finish 200ms after reverse started
sAnimatorTestRule.advanceTimeBy(200);
assertFalse(a2.isStarted());
// By the time a2 finishes reversing, a1 should not have started.
assertFalse(a1.isStarted());
sAnimatorTestRule.advanceTimeBy(100);
assertTrue(a1.isStarted());
// a1 finishes within 200ms after starting
sAnimatorTestRule.advanceTimeBy(200);
assertFalse(a1.isStarted());
assertFalse(set.isStarted());
set.cancel();
}
/**
* Test that duration scale is handled correctly in the AnimatorSet.
*/
@UiThreadTest
@Test
public void testZeroDurationScale() {
ValueAnimator.setDurationScale(0);
AnimatorSet set = new AnimatorSet();
set.playSequentially(mAnim1, mAnim2);
set.setStartDelay(1000);
set.start();
assertFalse(set.isStarted());
}
/**
* Test that non-zero duration scale is handled correctly in the AnimatorSet.
*/
@UiThreadTest
@Test
public void testDurationScale() {
// Change the duration scale to 3
ValueAnimator.setDurationScale(3f);
ValueAnimator a1 = ValueAnimator.ofFloat(0f, 1f);
a1.setDuration(100);
ValueAnimator a2 = ValueAnimator.ofFloat(1f, 2f);
a2.setDuration(100);
// Set start delay on a2 so that the delay is passed 100ms after a1 is finished.
a2.setStartDelay(200);
AnimatorSet set = new AnimatorSet();
set.playSequentially(a1, a2);
set.setStartDelay(200);
// Sleep for part of the start delay and check that no child animator has started, to verify
// that the duration scale has been properly scaled.
set.start();
sAnimatorTestRule.advanceTimeBy(0);
assertFalse(set.isRunning());
// start delay of the set should be scaled to 600ms
sAnimatorTestRule.advanceTimeBy(550);
assertFalse(set.isRunning());
sAnimatorTestRule.advanceTimeBy(50);
assertTrue(set.isRunning());
assertTrue(a1.isStarted());
assertFalse(a2.isStarted());
// Verify that a1 finish in 300ms (3x its defined duration)
sAnimatorTestRule.advanceTimeBy(300);
assertFalse(a1.isStarted());
assertTrue(a2.isStarted());
assertFalse(a2.isRunning());
// a2 should finish the delay stage now
sAnimatorTestRule.advanceTimeBy(600);
assertTrue(a2.isStarted());
assertTrue(a2.isRunning());
sAnimatorTestRule.advanceTimeBy(300);
assertFalse(a2.isStarted());
assertFalse(a2.isRunning());
assertFalse(set.isStarted());
}
@UiThreadTest
@Test
public void testClone() {
final AnimatorSet set1 = new AnimatorSet();
final AnimatorListenerAdapter setListener = new AnimatorListenerAdapter() {};
set1.addListener(setListener);
ObjectAnimator animator1 = new ObjectAnimator();
animator1.setDuration(100);
animator1.setPropertyName("x");
animator1.setIntValues(5);
animator1.setInterpolator(new LinearInterpolator());
AnimatorListenerAdapter listener1 = new AnimatorListenerAdapter(){};
AnimatorListenerAdapter listener2 = new AnimatorListenerAdapter(){};
animator1.addListener(listener1);
ObjectAnimator animator2 = new ObjectAnimator();
animator2.setDuration(100);
animator2.setInterpolator(new LinearInterpolator());
animator2.addListener(listener2);
animator2.setPropertyName("y");
animator2.setIntValues(10);
set1.playTogether(animator1, animator2);
class AnimateObject {
public int x = 1;
public int y = 2;
public void setX(int val) {
x = val;
}
public void setY(int val) {
y = val;
}
}
set1.setTarget(new AnimateObject());
set1.start();
assertTrue(set1.isStarted());
animator1.getListeners();
AnimatorSet set2 = set1.clone();
assertFalse(set2.isStarted());
assertEquals(2, set2.getChildAnimations().size());
Animator clone1 = set2.getChildAnimations().get(0);
Animator clone2 = set2.getChildAnimations().get(1);
assertTrue(clone1.getListeners().contains(listener1));
assertTrue(clone2.getListeners().contains(listener2));
assertTrue(set2.getListeners().contains(setListener));
for (Animator.AnimatorListener listener : set1.getListeners()) {
assertTrue(set2.getListeners().contains(listener));
}
assertEquals(animator1.getDuration(), clone1.getDuration());
assertEquals(animator2.getDuration(), clone2.getDuration());
assertSame(animator1.getInterpolator(), clone1.getInterpolator());
assertSame(animator2.getInterpolator(), clone2.getInterpolator());
set1.cancel();
}
/**
* Testing seeking in an AnimatorSet containing sequential animators.
*/
@UiThreadTest
@Test
public void testSeeking() {
final AnimatorSet set = new AnimatorSet();
final ValueAnimator a1 = ValueAnimator.ofFloat(0f, 150f);
a1.setDuration(150);
final ValueAnimator a2 = ValueAnimator.ofFloat(150f, 250f);
a2.setDuration(100);
final ValueAnimator a3 = ValueAnimator.ofFloat(250f, 300f);
a3.setDuration(50);
a1.setInterpolator(null);
a2.setInterpolator(null);
a3.setInterpolator(null);
set.playSequentially(a1, a2, a3);
set.setCurrentPlayTime(100);
assertEquals(100f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(150f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(250f, (Float) a3.getAnimatedValue(), EPSILON);
set.setCurrentPlayTime(280);
assertEquals(150f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(250f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(280f, (Float) a3.getAnimatedValue(), EPSILON);
set.start();
sAnimatorTestRule.advanceTimeBy(0);
assertEquals(280, set.getCurrentPlayTime());
assertTrue(set.isRunning());
sAnimatorTestRule.advanceTimeBy(20);
assertFalse(set.isStarted());
// Seek after a run to the middle-ish, and verify the first animator is at the end
// value and the 3rd at beginning value, and the 2nd animator is at the seeked value.
set.setCurrentPlayTime(200);
assertEquals(150f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(200f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(250f, (Float) a3.getAnimatedValue(), EPSILON);
}
/**
* Testing seeking in an AnimatorSet containing infinite animators.
*/
@Test
public void testSeekingInfinite() {
final AnimatorSet set = new AnimatorSet();
final ValueAnimator a1 = ValueAnimator.ofFloat(0f, 100f);
a1.setDuration(100);
final ValueAnimator a2 = ValueAnimator.ofFloat(100f, 200f);
a2.setDuration(100);
a2.setRepeatCount(ValueAnimator.INFINITE);
a2.setRepeatMode(ValueAnimator.RESTART);
final ValueAnimator a3 = ValueAnimator.ofFloat(100f, 200f);
a3.setDuration(100);
a3.setRepeatCount(ValueAnimator.INFINITE);
a3.setRepeatMode(ValueAnimator.REVERSE);
a1.setInterpolator(null);
a2.setInterpolator(null);
a3.setInterpolator(null);
set.play(a1).before(a2);
set.play(a1).before(a3);
set.setCurrentPlayTime(50);
assertEquals(50L, set.getCurrentPlayTime());
assertEquals(50f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(100f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(100f, (Float) a3.getAnimatedValue(), EPSILON);
set.setCurrentPlayTime(100);
assertEquals(100L, set.getCurrentPlayTime());
assertEquals(100f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(100f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(100f, (Float) a3.getAnimatedValue(), EPSILON);
// Seek to the 1st iteration of the infinite repeat animators, and they should have the
// same value.
set.setCurrentPlayTime(180);
assertEquals(180L, set.getCurrentPlayTime());
assertEquals(100f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(180f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(180f, (Float) a3.getAnimatedValue(), EPSILON);
// Seek to the 2nd iteration of the infinite repeat animators, and they should have
// different values as they have different repeat mode.
set.setCurrentPlayTime(280);
assertEquals(280L, set.getCurrentPlayTime());
assertEquals(100f, (Float) a1.getAnimatedValue(), EPSILON);
assertEquals(180f, (Float) a2.getAnimatedValue(), EPSILON);
assertEquals(120f, (Float) a3.getAnimatedValue(), EPSILON);
}
@UiThreadTest
@Test
public void testSeekNested() {
final AnimatorSet parent = new AnimatorSet();
final ValueAnimator a1 = ValueAnimator.ofFloat(0f, 100f);
a1.setDuration(100);
final AnimatorSet child = new AnimatorSet();
child.playTogether(a1);
final ValueAnimator a2 = ValueAnimator.ofFloat(100f, 200f);
a2.setDuration(100);
parent.playTogether(child, a2);
parent.setCurrentPlayTime(50);
assertEquals(50f, (float) a1.getAnimatedValue(), EPSILON);
assertEquals(150f, (float) a2.getAnimatedValue(), EPSILON);
}
@UiThreadTest
@Test
public void testNotifiesAfterEnd() {
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
class TestListener extends AnimatorListenerAdapter {
public boolean startIsCalled = false;
public boolean endIsCalled = false;
@Override
public void onAnimationStart(@NonNull Animator animation) {
assertTrue(animation.isStarted());
assertTrue(animation.isRunning());
startIsCalled = true;
}
@Override
public void onAnimationEnd(@NonNull Animator animation) {
assertFalse(animation.isRunning());
assertFalse(animation.isStarted());
super.onAnimationEnd(animation);
endIsCalled = true;
}
}
TestListener listener = new TestListener();
animator.addListener(listener);
TestListener setListener = new TestListener();
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.addListener(setListener);
animatorSet.start();
animator.end();
assertFalse(animator.isStarted());
assertTrue(listener.startIsCalled);
assertTrue(listener.endIsCalled);
assertTrue(setListener.startIsCalled);
}
/**
*
* This test verifies that custom ValueAnimators will be start()'ed in a set.
*/
@UiThreadTest
@Test
public void testChildAnimatorStartCalled() {
class StartListener extends AnimatorListenerAdapter {
public boolean mStartCalled = false;
@Override
public void onAnimationStart(@NonNull Animator anim) {
mStartCalled = true;
}
}
StartListener l1 = new StartListener();
StartListener l2 = new StartListener();
mAnim1.addListener(l1);
mAnim2.addListener(l2);
AnimatorSet set = new AnimatorSet();
set.playTogether(mAnim1, mAnim2);
set.start();
assertTrue(l1.mStartCalled);
assertTrue(l2.mStartCalled);
}
/**
* This test sets up an AnimatorSet that contains two sequential animations. The first animation
* is infinite, the second animation therefore has an infinite start time. This test verifies
* that the infinite start time is handled correctly.
*/
@UiThreadTest
@Test
public void testInfiniteStartTime() {
ValueAnimator a1 = ValueAnimator.ofFloat(0f, 1f);
a1.setRepeatCount(ValueAnimator.INFINITE);
ValueAnimator a2 = ValueAnimator.ofFloat(0f, 1f);
AnimatorSet set = new AnimatorSet();
set.playSequentially(a1, a2);
set.start();
assertEquals(Animator.DURATION_INFINITE, set.getTotalDuration());
set.end();
}
/**
* This test sets up 10 animators playing together. We expect the start time for all animators
* to be the same.
*/
@UiThreadTest
@Test
public void testMultipleAnimatorsPlayTogether() {
Animator[] animators = new Animator[10];
for (int i = 0; i < 10; i++) {
animators[i] = ValueAnimator.ofFloat(0f, 1f);
animators[i].setDuration(100 + i * 100);
}
AnimatorSet set = new AnimatorSet();
set.playTogether(animators);
set.setStartDelay(80);
set.start();
sAnimatorTestRule.advanceTimeBy(0);
assertTrue(set.isStarted());
assertFalse(set.isRunning());
sAnimatorTestRule.advanceTimeBy(80);
for (int i = 0; i < 10; i++) {
assertTrue(animators[i].isRunning());
sAnimatorTestRule.advanceTimeBy(100);
assertFalse(animators[i].isStarted());
}
// The set should finish by now.
assertFalse(set.isStarted());
}
@UiThreadTest
@Test
public void testGetChildAnimations() {
Animator[] animatorArray = {mAnim1, mAnim2};
mAnimatorSet = new AnimatorSet();
mAnimatorSet.getChildAnimations();
assertEquals(0, mAnimatorSet.getChildAnimations().size());
mAnimatorSet.playSequentially(animatorArray);
assertEquals(2, mAnimatorSet.getChildAnimations().size());
}
/**
*
*/
@UiThreadTest
@Test
public void testSetInterpolator() {
mAnim1.setRepeatCount(ValueAnimator.INFINITE);
Animator[] animatorArray = {mAnim1, mAnim2};
Interpolator interpolator = new AccelerateDecelerateInterpolator();
mAnimatorSet = new AnimatorSet();
mAnimatorSet.playTogether(animatorArray);
mAnimatorSet.setInterpolator(interpolator);
assertFalse(mAnimatorSet.isRunning());
mAnimatorSet.start();
ArrayList<Animator> animatorList = mAnimatorSet.getChildAnimations();
assertEquals(interpolator, animatorList.get(0).getInterpolator());
assertEquals(interpolator, animatorList.get(1).getInterpolator());
mAnimatorSet.cancel();
}
@UiThreadTest
@Test
public void testMultipleAnimatorsSingleProperty() {
final SampleTarget target = new SampleTarget();
final ObjectAnimator a1 = ObjectAnimator.ofFloat(target, SampleTarget.VALUE, 0f, 1000f);
a1.setDuration(1000);
a1.setInterpolator(new LinearInterpolator());
final ObjectAnimator a2 = ObjectAnimator.ofFloat(target, SampleTarget.VALUE, 1000f, 2000f);
a2.setDuration(1000);
a2.setStartDelay(1000);
a2.setInterpolator(new LinearInterpolator());
final AnimatorSet set = new AnimatorSet();
set.playTogether(a1, a2);
set.start();
final float delta = 0.001f;
assertEquals(0f, target.mValue, delta);
sAnimatorTestRule.advanceTimeBy(500);
assertEquals(500f, (float) a1.getAnimatedValue(), delta);
assertEquals(500f, target.mValue, delta);
sAnimatorTestRule.advanceTimeBy(1000);
assertEquals(1500f, target.mValue, delta);
sAnimatorTestRule.advanceTimeBy(5000);
assertEquals(2000f, target.mValue, delta);
assertFalse(set.isRunning());
// Rewind
set.setCurrentPlayTime(1500);
assertEquals(1500f, target.mValue, delta);
set.setCurrentPlayTime(500);
assertEquals(500f, target.mValue, delta);
}
static class SampleTarget {
static final Property<SampleTarget, Float> VALUE = new FloatProperty<SampleTarget>() {
@Override
public void setValue(@NonNull SampleTarget object, float value) {
object.mValue = value;
}
@Override
public Float get(SampleTarget sampleTarget) {
return sampleTarget.mValue;
}
};
float mValue;
}
static class AnimEvent {
enum EventType {
START,
END
}
final EventType mType;
final Animator mAnim;
AnimEvent(EventType type, Animator anim) {
mType = type;
mAnim = anim;
}
}
}
| 34.315496 | 100 | 0.643254 |
a06dc197a039c3a91f55c7ca36f9694de5f9f302 | 3,305 | package cz.znj.kvr.sw.exp.java.dynamodb.basic;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.*;
import com.google.common.base.Throwables;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author
* Zbyněk Vyškovský
*/
public abstract class TableExperimentBase extends ExperimentBase {
protected Collection<String> getExampleTableNames() {
return getExperimentTablesDefinitions()
.stream()
.map((CreateTableRequest request) -> request.getTableName())
.collect(Collectors.toList());
}
protected Collection<CreateTableRequest> getExperimentTablesDefinitions() {
return Collections.<CreateTableRequest>emptyList();
}
protected void consumeExperimentTablesCreations(List<Table> tables) {
}
protected void initData() {
}
protected void doTableExperiment() {
}
public int process() {
try {
deleteExperimentTables();
} catch (ResourceNotFoundException ex) {
// ignore if the productTable didnot exist
}
createExperimentTables();
try {
initData();
doTableExperiment();
} finally {
deleteExperimentTables();
}
return 0;
}
protected void printExperimentTablesInformation() {
for (String tableName : getExampleTableNames()) {
logger.info("Describing " + tableName);
TableDescription tableDescription = new Table(dynamoDb, tableName).describe();
logger.info(String.format("Name: %s:\n" + "Status: %s \n"
+ "Provisioned Throughput (read capacity units/sec): %d \n"
+ "Provisioned Throughput (write capacity units/sec): %d \n",
tableDescription.getTableName(),
tableDescription.getTableStatus(),
tableDescription.getProvisionedThroughput().getReadCapacityUnits(),
tableDescription.getProvisionedThroughput().getWriteCapacityUnits()));
}
}
protected void createExperimentTables() {
consumeExperimentTablesCreations(getExperimentTablesDefinitions().stream()
.map((CreateTableRequest request) -> {
logger.info("Issuing CreateTable request for " + request.getTableName());
return dynamoDb.createTable(request);
})
.map((CreateTableResult createResult) -> {
Table table = new Table(dynamoDb, createResult.getTableDescription().getTableName());
logger.info("Waiting for " + table.getTableName() + " to be created...this may take a while...");
try {
table.waitForActive();
} catch (InterruptedException e) {
throw Throwables.propagate(e);
}
return table;
})
.collect(Collectors.toList())
);
logger.info("Tables created");
}
protected void deleteExperimentTables() {
getExampleTableNames().stream()
.map((String tableName) -> {
Table table = new Table(dynamoDb, tableName);
logger.info("Issuing DeleteTable request for " + tableName);
table.delete();
return table;
})
.forEach((Table table) -> {
logger.info("Waiting for " + table.getTableName() + " to be deleted...this may take a while...");
try {
table.waitForDelete();
} catch (ResourceNotFoundException e) {
// ignore non-existing productTable
} catch (InterruptedException e) {
throw Throwables.propagate(e);
}
});
logger.info("Tables deleted");
}
}
| 29.774775 | 102 | 0.70348 |
75298978a6ba221bed4cb10c7d9b0481c7cbc873 | 1,766 | /*
* Copyright 2017 Daniel Sawano
*
* 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 se.sawano.java.security.otp;
import java.nio.charset.Charset;
import static org.apache.commons.lang3.Validate.notNull;
import static se.sawano.java.security.otp.CodecUtils.*;
public class TestObjectFactory {
private static final Charset UTF_8 = Charset.forName("UTF8");
public static SharedSecret sharedSecretFromBase32(final String base32Secret, final ShaAlgorithm algorithm) {
final byte[] bytes = decodeBase32(base32Secret.getBytes());
return SharedSecret.from(bytes, algorithm);
}
public static SharedSecret from(final String value, final ShaAlgorithm algorithm) {
return from(value, UTF_8, algorithm);
}
public static SharedSecret from(final String value, final Charset charset, final ShaAlgorithm algorithm) {
notNull(value);
notNull(charset);
return fromHex(encodeToHexString(value, charset), algorithm);
}
public static SharedSecret fromHex(final String hexString, final ShaAlgorithm algorithm) {
notNull(hexString);
notNull(algorithm);
final byte[] bytes = decodeHex(hexString);
return SharedSecret.from(bytes, algorithm);
}
}
| 33.961538 | 112 | 0.728199 |
c82009d434e70a9101909a7ef35d978cd80b2a93 | 1,939 | package be.phury.relax;
import com.google.gson.JsonObject;
import javax.inject.Inject;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import java.util.List;
import java.util.NoSuchElementException;
public class JsonResourceImpl implements JsonResource {
@Inject
private Serializer serializer;
@Inject
private JsonDao jsonDao;
@Override
@PUT
public Object add(String collection, String json) {
List<JsonObject> list = jsonDao.getList(collection, JsonDao.Options.CREATE);
JsonObject toAdd = serializer.fromString(json, JsonObject.class);
toAdd.addProperty("id", list.size()+1);
list.add(toAdd);
jsonDao.saveList(collection, list);
return toAdd;
}
@Override
@POST
public Object update(String collection, String json) {
List<JsonObject> list = jsonDao.getList(collection);
JsonObject toUpdate = serializer.fromString(json, JsonObject.class);
int index = toUpdate.get("id").getAsInt() - 1;
if (index < 0 || index >= list.size()) {
throw new NoSuchElementException("no element with id " + index);
}
list.set(index, toUpdate);
jsonDao.saveList(collection, list);
return toUpdate;
}
@Override
@GET
public Object get(String collection, Integer id) {
return jsonDao.findById(jsonDao.getList(collection), id);
}
@Override
@GET
public Object list(String collection, Integer offset, Integer limit) {
return PageableList.createPaging(jsonDao.getList(collection), offset, limit);
}
@Override
@DELETE
public Object delete(String collection, Integer id) {
List<JsonObject> list = jsonDao.getList(collection);
JsonObject deleted = list.get(id);
list.remove(id);
jsonDao.saveList(collection, list);
return deleted;
}
}
| 28.514706 | 85 | 0.663228 |
e1f8c777752f722e6277cd2e1d44a7eda326fde0 | 1,414 | package com.loenan.bricks.sphere.generator.color.image;
import com.loenan.bricks.ldraw.color.Color;
import com.loenan.bricks.ldraw.color.ColorSet;
import com.loenan.bricks.sphere.generator.color.CoordinatesColorScheme;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.Math.min;
public abstract class ImagePickerColorScheme extends CoordinatesColorScheme {
private final BufferedImage image;
private final int imageWidth;
private final int imageHeight;
protected ImagePickerColorScheme(String schemeName, String imageResource) throws IOException {
super(schemeName);
try (InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(imageResource)) {
if (inputStream == null) {
throw new IllegalArgumentException("Image resource not found: " + imageResource);
}
image = ImageIO.read(inputStream);
imageWidth = image.getWidth();
imageHeight = image.getHeight();
}
}
@Override
public Color selectColor(double longitude, double latitude, ColorSet availableColors) {
int x = (int) ((180 + longitude) * imageWidth / 360) % imageWidth;
int y = min((int) ((90 - latitude) * imageHeight / 180), imageHeight - 1);
int rgb = image.getRGB(x, y);
return availableColors.getClosestColor(
(rgb & 0xff0000) >> 16,
(rgb & 0xff00) >> 8,
rgb & 0xff);
}
}
| 30.73913 | 95 | 0.74611 |
5c7587f5db4b33ca94c1bd513278c05226ccd007 | 8,456 | /*******************************************************************************
* Copyright (C) 2020 FVA GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package info.rexs.model;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import info.rexs.db.constants.RexsComponentType;
import info.rexs.model.jaxb.Accumulation;
import info.rexs.model.jaxb.Component;
import info.rexs.model.jaxb.LoadCase;
public class RexsSubModelTest {
@Test
public void integerConstructor_getterMatchesValuePassedToConstructor() throws Exception {
RexsSubModel rexsSubModel = new RexsSubModel(41);
assertThat(rexsSubModel.getId()).isEqualTo(41);
assertThat(rexsSubModel.isAccumulation()).isFalse();
}
@Test
public void loadCaseConstructor_getterMatchesValuePassedToConstructor() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
assertThat(rexsSubModel.getId()).isEqualTo(41);
assertThat(rexsSubModel.hasComponent(1)).isTrue();
assertThat(rexsSubModel.isAccumulation()).isFalse();
}
@Test
public void accumulationConstructor_getterMatchesValuePassedToConstructor() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
Accumulation rawAccumulation = new Accumulation();
rawAccumulation.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(rawAccumulation);
assertThat(rexsSubModel.getId()).isNull();
assertThat(rexsSubModel.hasComponent(1)).isTrue();
assertThat(rexsSubModel.isAccumulation()).isTrue();
}
@Test
public void accumulationConstructor_nullParameterDoesNotCrash() throws Exception {
RexsSubModel rexsSubModel = new RexsSubModel((Accumulation)null);
assertThat(rexsSubModel.getId()).isNull();
assertThat(rexsSubModel.hasComponent(1)).isFalse();
assertThat(rexsSubModel.isAccumulation()).isTrue();
}
@Test
public void hasComponent_componentNotInSubModelReturnsFalse() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
assertThat(rexsSubModel.hasComponent(2)).isFalse();
}
@Test
public void hasComponent_componentInSubModelReturnsTrue() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
assertThat(rexsSubModel.hasComponent(1)).isTrue();
}
@Test
public void getComponent_componentNotInSubModelReturnsNull() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
assertThat(rexsSubModel.getComponent(2)).isNull();
}
@Test
public void getComponent_componentInSubModelReturnsComponent() throws Exception {
Component rawComponent = new Component();
rawComponent.setId(1);
rawComponent.setType(RexsComponentType.cylindrical_gear.getId());
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
RexsComponent rexsComponent = rexsSubModel.getComponent(1);
assertThat(rexsComponent).isNotNull();
assertThat(rexsComponent.getId()).isEqualTo(1);
assertThat(rexsComponent.getType()).isEqualTo(RexsComponentType.cylindrical_gear);
assertThat(rexsComponent.getRawComponent()).isEqualTo(rawComponent);
}
@Test
public void changeComponentId_nonExistingComponentIdIgnoresMethodCall() throws Exception {
Component rawComponent1 = new Component();
rawComponent1.setId(1);
rawComponent1.setType(RexsComponentType.cylindrical_gear.getId());
Component rawComponent2 = new Component();
rawComponent2.setId(2);
rawComponent2.setType(RexsComponentType.bevel_gear.getId());
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent1);
loadCase.getComponent().add(rawComponent2);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
rexsSubModel.changeComponentId(3, 4);
assertThat(rexsSubModel.hasComponent(1)).isTrue();
assertThat(rexsSubModel.hasComponent(2)).isTrue();
assertThat(rexsSubModel.hasComponent(3)).isFalse();
assertThat(rexsSubModel.hasComponent(4)).isFalse();
}
@Test
public void changeComponentId_changesIdOfComponent() throws Exception {
Component rawComponent1 = new Component();
rawComponent1.setId(1);
rawComponent1.setType(RexsComponentType.cylindrical_gear.getId());
Component rawComponent2 = new Component();
rawComponent2.setId(2);
rawComponent2.setType(RexsComponentType.bevel_gear.getId());
LoadCase loadCase = new LoadCase();
loadCase.setId(41);
loadCase.getComponent().add(rawComponent1);
loadCase.getComponent().add(rawComponent2);
RexsSubModel rexsSubModel = new RexsSubModel(loadCase);
rexsSubModel.changeComponentId(2, 3);
assertThat(rexsSubModel.hasComponent(1)).isTrue();
assertThat(rexsSubModel.hasComponent(2)).isFalse();
assertThat(rexsSubModel.hasComponent(3)).isTrue();
}
@Test
public void compareTo_accumulationIsAlwaysGreaterThanAnyOtherLoadCase() throws Exception {
RexsSubModel rexsSubModelAccumulation = new RexsSubModel((Accumulation)null);
RexsSubModel rexsSubModelLoadCase1 = new RexsSubModel(1);
RexsSubModel rexsSubModelLoadCase24 = new RexsSubModel(24);
assertThat(rexsSubModelAccumulation.compareTo(rexsSubModelAccumulation)).isEqualTo(0);
assertThat(rexsSubModelAccumulation.compareTo(rexsSubModelLoadCase1)).isEqualTo(1);
assertThat(rexsSubModelAccumulation.compareTo(rexsSubModelLoadCase24)).isEqualTo(1);
assertThat(rexsSubModelLoadCase1.compareTo(rexsSubModelAccumulation)).isEqualTo(-1);
assertThat(rexsSubModelLoadCase24.compareTo(rexsSubModelAccumulation)).isEqualTo(-1);
}
@Test
public void compareTo_comparesById() throws Exception {
RexsSubModel rexsSubModel23 = new RexsSubModel(23);
RexsSubModel rexsSubModel24 = new RexsSubModel(24);
assertThat(rexsSubModel23.compareTo(rexsSubModel24)).isLessThan(0);
assertThat(rexsSubModel24.compareTo(rexsSubModel23)).isGreaterThan(0);
assertThat(rexsSubModel23.compareTo(rexsSubModel23)).isEqualTo(0);
assertThat(rexsSubModel24.compareTo(rexsSubModel24)).isEqualTo(0);
}
@Test
public void equals_equalObjects() {
RexsSubModel rexsSubModelAccumulation1 = new RexsSubModel((Accumulation)null);
RexsSubModel rexsSubModelAccumulation2 = new RexsSubModel((Accumulation)null);
RexsSubModel rexsSubModelLoadCase1 = new RexsSubModel(1);
RexsSubModel rexsSubModelLoadCase2 = new RexsSubModel(1);
assertThat(rexsSubModelAccumulation1.equals(rexsSubModelAccumulation1)).isTrue();
assertThat(rexsSubModelAccumulation1).isEqualTo(rexsSubModelAccumulation2);
assertThat(rexsSubModelLoadCase1.equals(rexsSubModelLoadCase1)).isTrue();
assertThat(rexsSubModelLoadCase1).isEqualTo(rexsSubModelLoadCase2);
}
@Test
public void equals_notEqualObjects() {
RexsSubModel rexsSubModelAccumulation = new RexsSubModel((Accumulation)null);
RexsSubModel rexsSubModelLoadCase1 = new RexsSubModel(1);
RexsSubModel rexsSubModelLoadCase24 = new RexsSubModel(24);
assertThat(rexsSubModelAccumulation).isNotEqualTo(rexsSubModelLoadCase1);
assertThat(rexsSubModelAccumulation).isNotEqualTo("1");
assertThat(rexsSubModelLoadCase1).isNotEqualTo(rexsSubModelLoadCase24);
assertThat(rexsSubModelLoadCase1).isNotEqualTo("1");
}
}
| 35.982979 | 95 | 0.777554 |
686001cc9af70d4c5cb90122f531dd270c83fed6 | 2,583 | package ru.intertrust.cm.core.config;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import ru.intertrust.cm.core.config.base.TopLevelConfig;
/**
*
* @author atsvetkov
*
*/
@Root(name = "notification")
public class NotificationConfig implements TopLevelConfig {
@Attribute(name = "name", required = true)
private String name;
@Attribute(name = "replace", required = false)
private String replacementPolicy;
@Element(name = "notification-type", required = true)
private NotificationTypeConfig notificationTypeConfig = new NotificationTypeConfig();
public String getName() {
return name;
}
@Override
public ExtensionPolicy getReplacementPolicy() {
return ExtensionPolicy.fromString(replacementPolicy);
}
@Override
public ExtensionPolicy getCreationPolicy() {
return ExtensionPolicy.Runtime;
}
public void setName(String name) {
this.name = name;
}
public NotificationTypeConfig getNotificationTypeConfig() {
return notificationTypeConfig;
}
public void setNotificationTypeConfig(NotificationTypeConfig notificationTypeConfig) {
this.notificationTypeConfig = notificationTypeConfig;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((notificationTypeConfig == null) ? 0 : notificationTypeConfig.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NotificationConfig other = (NotificationConfig) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (replacementPolicy != null ? !replacementPolicy.equals(other.replacementPolicy) : other.replacementPolicy != null) {
return false;
}
if (notificationTypeConfig == null) {
if (other.notificationTypeConfig != null) {
return false;
}
} else if (!notificationTypeConfig.equals(other.notificationTypeConfig)) {
return false;
}
return true;
}
}
| 27.774194 | 127 | 0.617499 |
c9c828315ee204e85aeb576b049ad8c1d7b4301f | 20,067 | /*
Copyright 2006 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.gp.breed;
import ec.*;
import ec.util.*;
import ec.gp.*;
import java.util.ArrayList;
import java.util.HashMap;
/*
* MutateDemotePipeline.java
*
* Created: Wed Dec 15 21:41:30 1999
* By: Sean Luke
*/
/**
* MutateDemotePipeline works very similarly to the DemoteNode algorithm
* described in Kumar Chellapilla,
* "A Preliminary Investigation into Evolving Modular Programs without Subtree
* Crossover", GP98, and is also similar to the "insertion" operator found in
* Una-May O'Reilly's thesis,
* <a href="http://www.ai.mit.edu/people/unamay/thesis.html">
* "An Analysis of Genetic Programming"</a>.
*
* <p>MutateDemotePipeline tries picks a random tree, then picks
* randomly from all the demotable nodes in the tree, and demotes one.
* If its chosen tree has no demotable nodes, or demoting
* its chosen demotable node would make the tree too deep, it repeats
* the choose-tree-then-choose-node process. If after <i>tries</i> times
* it has failed to find a valid tree and demotable node, it gives up and simply
* copies the individual.
*
* <p>"Demotion" means to take a node <i>n</i> and insert a new node <i>m</i>
* between <i>n</i> and <i>n</i>'s parent. <i>n</i> becomes a child of
* <i>m</i>; the place where it becomes a child is determined at random
* from all the type-compatible slots of <i>m</i>. The other child slots
* of <i>m</i> are filled with randomly-generated terminals.
* Chellapilla's version of the algorithm always
* places <i>n</i> in child slot 0 of <i>m</i>. Because this would be
* unneccessarily restrictive on strong typing, MutateDemotePipeline instead
* picks the slot at random from all available valid choices.
*
* <p>A "Demotable" node means a node which is capable of demotion
* given the existing function set. In general to demote a node <i>foo</i>,
* there must exist in the function set a nonterminal whose return type
* is type-compatible with the child slot <i>foo</i> holds in its parent;
* this nonterminal must also have a child slot which is type-compatible
* with <i>foo</i>'s return type.
*
* <p>This method is very expensive in searching nodes for
* "demotability". However, if the number of types is 1 (the
* GP run is typeless) then the type-constraint-checking
* code is bypassed and the method runs a little faster.
*
<p><b>Typical Number of Individuals Produced Per <tt>produce(...)</tt> call</b><br>
...as many as the source produces
<p><b>Number of Sources</b><br>
1
<p><b>Parameters</b><br>
<table>
<tr><td valign=top><i>base</i>.<tt>tries</tt><br>
<font size=-1>int >= 1</font></td>
<td valign=top>(number of times to try finding valid pairs of nodes)</td></tr>
<tr><td valign=top><i>base</i>.<tt>maxdepth</tt><br>
<font size=-1>int >= 1</font></td>
<td valign=top>(maximum valid depth of a mutated tree)</td></tr>
<tr><td valign=top><i>base</i>.<tt>tree.0</tt><br>
<font size=-1>0 < int < (num trees in individuals), if exists</font></td>
<td valign=top>(tree chosen for mutation; if parameter doesn't exist, tree is picked at random)</td></tr>
</table>
<p><b>Default Base</b><br>
gp.breed.mutate-demote
* @author Sean Luke
* @version 1.0
*/
public class MutateDemotePipeline extends GPBreedingPipeline
{
public static final String P_MUTATEDEMOTE = "mutate-demote";
public static final String P_NUM_TRIES = "tries";
public static final String P_MAXDEPTH = "maxdepth";
public static final int NUM_SOURCES = 1;
/** The number of times the pipeline tries to build a valid mutated
tree before it gives up and just passes on the original */
int numTries;
/** The maximum depth of a mutated tree */
int maxDepth;
/** Is our tree fixed? If not, this is -1 */
int tree;
public Parameter defaultBase() { return GPBreedDefaults.base().push(P_MUTATEDEMOTE); }
public int numSources() { return NUM_SOURCES; }
public void setup(final EvolutionState state, final Parameter base)
{
super.setup(state,base);
Parameter def = defaultBase();
numTries = state.parameters.getInt(base.push(P_NUM_TRIES),
def.push(P_NUM_TRIES),1);
if (numTries == 0)
state.output.fatal("MutateDemotePipeline has an invalid number of tries (it must be >= 1).",base.push(P_NUM_TRIES),def.push(P_NUM_TRIES));
maxDepth = state.parameters.getInt(base.push(P_MAXDEPTH),
def.push(P_MAXDEPTH),1);
if (maxDepth==0)
state.output.fatal("The MutateDemotePipeline " + base + "has an invalid maximum depth (it must be >= 1).",base.push(P_MAXDEPTH),def.push(P_MAXDEPTH));
tree = TREE_UNFIXED;
if (state.parameters.exists(base.push(P_TREE).push(""+0),
def.push(P_TREE).push(""+0)))
{
tree = state.parameters.getInt(base.push(P_TREE).push(""+0),
def.push(P_TREE).push(""+0),0);
if (tree==-1)
state.output.fatal("Tree fixed value, if defined, must be >= 0");
}
}
private boolean demotable(final GPInitializer initializer,
final GPNode node, final GPFunctionSet set)
{
GPType t;
if (node.parent instanceof GPNode) // ugh, expensive
t = ((GPNode)(node.parent)).constraints(initializer).childtypes[node.argposition];
else
t = ((GPTree)(node.parent)).constraints(initializer).treetype;
// Now, out of the nonterminals compatible with that return type,
// do any also have a child compatible with that return type? This
// will be VERY expensive
for(int x=0;x<set.nonterminals[t.type].length;x++)
for(int y=0;y<set.nonterminals[t.type][x].constraints(initializer).
childtypes.length;y++)
if (set.nonterminals[t.type][x].constraints(initializer).childtypes[y].
compatibleWith(initializer,node.constraints(initializer).returntype))
return true;
return false;
}
private void demoteSomething(final GPNode node, final EvolutionState state, final int thread, final GPFunctionSet set)
{
// if I have just one type, do it the easy way
if (((GPInitializer)state.initializer).numAtomicTypes +
((GPInitializer)state.initializer).numSetTypes == 1)
_demoteSomethingTypeless(node,state,thread,set);
// otherwise, I gotta do the dirty work
else _demoteSomething(node,state,thread,set);
}
private void _demoteSomething(final GPNode node, final EvolutionState state, final int thread, final GPFunctionSet set)
{
int numDemotable = 0;
GPType t;
GPInitializer initializer = ((GPInitializer)state.initializer);
if (node.parent instanceof GPNode) // ugh, expensive
t = ((GPNode)(node.parent)).constraints(initializer).childtypes[node.argposition];
else
t = ((GPTree)(node.parent)).constraints(initializer).treetype;
// Now, determine how many nodes we can demote this under --
// note this doesn't select based on the total population
// of "available child positions", but on the total population
// of *nodes* regardless of if they have more than one possible
// valid "child position".
for(int x=0;x<set.nonterminals[t.type].length;x++)
for(int y=0;y<set.nonterminals[t.type][x].constraints(initializer).
childtypes.length;y++)
if (set.nonterminals[t.type][x].constraints(initializer).childtypes[y].
compatibleWith(initializer,node.constraints(initializer).returntype))
{
numDemotable++; break; // breaks out to enclosing for
}
// pick a random item to demote -- numDemotable is assumed to be > 0
int demoteItem = state.random[thread].nextInt(numDemotable);
numDemotable=0;
// find it
for(int x=0;x<set.nonterminals[t.type].length;x++)
for(int y=0;y<set.nonterminals[t.type][x].constraints(initializer).
childtypes.length;y++)
if (set.nonterminals[t.type][x].constraints(initializer).childtypes[y].
compatibleWith(initializer,node.constraints(initializer).returntype))
{
if (numDemotable==demoteItem)
{
// clone the node
GPNode cnode = (GPNode)(set.nonterminals[t.type][x].lightClone());
// choose a spot to hang the old parent under
int numSpots=0;
GPType retyp = node.constraints(initializer).returntype;
GPType[] chityp = cnode.constraints(initializer).childtypes;
for(int z=0;z<cnode.children.length;z++)
if (chityp[z].compatibleWith(initializer,retyp))
numSpots++;
int choice = state.random[thread].nextInt(numSpots);
numSpots=0;
for(int z=0;z<cnode.children.length;z++)
if (chityp[z].compatibleWith(initializer,retyp))
{
if (numSpots==choice)
{
// demote the parent, inserting cnode
cnode.parent = node.parent;
cnode.argposition = node.argposition;
cnode.children[z] = node;
node.parent = cnode;
node.argposition = (byte)z;
if (cnode.parent instanceof GPNode)
((GPNode)(cnode.parent)).
children[cnode.argposition] = cnode;
else ((GPTree)(cnode.parent)).child = cnode;
// this is important to ensure that the
// demotion only happens once! Otherwise
// you'll get really nasty bugs
numSpots++; // notice no break
}
else
{
// hang a randomly-generated terminal off of cnode
GPNode term = (GPNode)(set.terminals[chityp[z].type][
state.random[thread].nextInt(
set.terminals[chityp[z].type].length)].lightClone());
cnode.children[z] = term;
term.parent = cnode; // just in case
term.argposition = (byte)z; // just in case
term.resetNode(state,thread); // let it randomize itself if necessary
// increase numSpots
numSpots++; // notice no break
}
}
else
{
// hang a randomly-generated terminal off of cnode
GPNode term = (GPNode)(set.terminals[chityp[z].type][
state.random[thread].nextInt(
set.terminals[chityp[z].type].length)].lightClone());
cnode.children[z] = term;
term.parent = cnode; // just in case
term.argposition = (byte)z; // just in case
term.resetNode(state,thread); // let it randomize itself if necessary
}
return;
}
else
{
numDemotable++; break; // breaks out to enclosing for
}
}
// should never reach here
throw new InternalError("Bug in demoteSomething -- should never be able to reach the end of the function");
}
private void _demoteSomethingTypeless(final GPNode node, final EvolutionState state, final int thread, final GPFunctionSet set)
{
int numDemotable = 0;
// since we're typeless, we can demote under any nonterminal
numDemotable = set.nonterminals[0].length;
// pick a random item to demote -- numDemotable is assumed to be > 0
int demoteItem = state.random[thread].nextInt(numDemotable);
numDemotable=0;
// find it
// clone the node
GPNode cnode = (GPNode)(set.nonterminals[0][demoteItem].lightClone());
GPType[] chityp = cnode.constraints(((GPInitializer)state.initializer)).childtypes;
// choose a spot to hang the old parent under
int choice = state.random[thread].nextInt(cnode.children.length);
for(int z=0;z<cnode.children.length;z++)
if (z==choice)
{
// demote the parent, inserting cnode
cnode.parent = node.parent;
cnode.argposition = node.argposition;
cnode.children[z] = node;
node.parent = cnode;
node.argposition = (byte)z;
if (cnode.parent instanceof GPNode)
((GPNode)(cnode.parent)).
children[cnode.argposition] = cnode;
else ((GPTree)(cnode.parent)).child = cnode;
}
else
{
// hang a randomly-generated terminal off of cnode
GPNode term = (GPNode)(
set.terminals[chityp[z].type][
state.random[thread].nextInt(
set.terminals[chityp[z].type].length)].lightClone());
cnode.children[z] = term;
term.parent = cnode; // just in case
term.argposition = (byte)z; // just in case
term.resetNode(state,thread); // let it randomize itself if necessary
}
}
private int numDemotableNodes(final GPInitializer initializer,
final GPNode root, int soFar, final GPFunctionSet set)
{
// if I have just one type, skip this and just return
// the number of nonterminals in the tree
if (initializer.numAtomicTypes +
initializer.numSetTypes == 1)
return root.numNodes(GPNode.NODESEARCH_ALL);
// otherwise, I gotta do the dirty work
else return _numDemotableNodes(initializer,root,soFar,set);
}
private int _numDemotableNodes(final GPInitializer initializer,
final GPNode root, int soFar, final GPFunctionSet set)
{
if (demotable(initializer,root, set)) soFar++;
for(int x=0;x<root.children.length;x++)
soFar = _numDemotableNodes(initializer,root.children[x],soFar, set);
return soFar;
}
private GPNode demotableNode;
private int pickDemotableNode(final GPInitializer initializer,
final GPNode root, int num, final GPFunctionSet set)
{
// if I have just one type, skip this and just
// the num-th nonterminal
if (initializer.numAtomicTypes +
initializer.numSetTypes == 1)
{
demotableNode = root.nodeInPosition(num,GPNode.NODESEARCH_ALL);
return -1; // what _pickDemotableNode() returns...
}
// otherwise, I gotta do the dirty work
else return _pickDemotableNode(initializer,root,num,set);
}
// sticks the node in
private int _pickDemotableNode(final GPInitializer initializer,
final GPNode root, int num, final GPFunctionSet set)
{
if (demotable(initializer,root, set))
{
num--;
if (num==-1) // found it
{
demotableNode = root;
return num;
}
}
for(int x=0;x<root.children.length;x++)
{
num = _pickDemotableNode(initializer, root.children[x],num,set);
if (num==-1) break; // someone found it
}
return num;
}
/** Returns true if inner1's depth + atdepth +1 is within the depth bounds */
private boolean verifyPoint(GPNode inner1)
{
// We know they're swap-compatible since we generated inner1
// to be exactly that. So don't bother.
// next check to see if inner1 can be demoted
if (inner1.depth()+inner1.atDepth()+1 > maxDepth) return false;
// checks done!
return true;
}
public int produce(final int min,
final int max,
final int subpopulation,
final ArrayList<Individual> inds,
final EvolutionState state,
final int thread, HashMap<String, Object> misc)
{
int start = inds.size();
// grab n individuals from our source and stick 'em right into inds.
// we'll modify them from there
int n = sources[0].produce(min,max,subpopulation,inds, state,thread, misc);
// should we bother?
if (!state.random[thread].nextBoolean(likelihood))
{
return n;
}
GPInitializer initializer = ((GPInitializer)state.initializer);
// now let's mutate 'em
for(int q=start; q < n+start; q++)
{
GPIndividual i = (GPIndividual)inds.get(q);
if (tree!=TREE_UNFIXED && (tree<0 || tree >= i.trees.length))
// uh oh
state.output.fatal("MutateDemotePipeline attempted to fix tree.0 to a value which was out of bounds of the array of the individual's trees. Check the pipeline's fixed tree values -- they may be negative or greater than the number of trees in an individual");
for (int x=0;x<numTries;x++)
{
int t;
// pick random tree
if (tree==TREE_UNFIXED)
if (i.trees.length>1) t = state.random[thread].nextInt(i.trees.length);
else t = 0;
else t = tree;
// is the tree demotable?
int numdemote = numDemotableNodes(initializer, i.trees[t].child,0,i.trees[t].constraints(initializer).functionset);
if (numdemote==0) continue; // uh oh, try again
// demote the node, or if we're unsuccessful, just leave it alone
pickDemotableNode(initializer, i.trees[t].child,state.random[thread].nextInt(numdemote),i.trees[t].constraints(initializer).functionset);
// does this node exceed the maximum depth limits?
if (!verifyPoint(demotableNode)) continue; // uh oh, try again
// demote it
demoteSomething(demotableNode,state,thread,i.trees[t].constraints(initializer).functionset);
i.evaluated = false;
break;
}
// add the new individual, replacing its previous source
inds.set(q,i);
}
return n;
}
}
| 41.290123 | 276 | 0.554891 |
e6b1ed238ee7f6e144866d90303320f172b5637c | 2,126 | /*
* 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.river.qa.harness;
import java.rmi.MarshalledObject;
import java.io.Serializable;
/**
* A <code>SlaveRequest</code> to start a service.
*/
class StartClassServerRequest implements SlaveRequest {
/** the service name */
private String serviceName;
/**
* Construct the request.
*
* @param serviceName the service name
*/
StartClassServerRequest(String serviceName) {
this.serviceName = serviceName;
}
/**
* Called by the <code>SlaveTest</code> after unmarshalling this object.
* The <code>AdminManager</code> is retrieved from the slave test,
* an admin is retrieved from the manager, and the admins <code>start</code>
* method is called. The <code>serviceName</code> should be the name
* of a class server, although no check is performed to verify this.
* <code>null</code> is returned since the class server 'proxy' is
* a local reference which is not serializable.
*
* @param slaveTest a reference to the <code>SlaveTest</code>
* @return null
* @throws Exception if an error occurs starting the service
*/
public Object doSlaveRequest(SlaveTest slaveTest) throws Exception {
Admin admin = slaveTest.getAdminManager().getAdmin(serviceName, 0);
admin.start();
return null;
}
}
| 34.852459 | 80 | 0.713547 |
72d002550e3492f18d261378c2bc5e711ee8b4cf | 3,760 | package display;
import cellsociety.CellSociety;
import javafx.animation.Animation;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import property.Property;
import xml.XMLParser;
public class SimulationGroup
{
public static int BUTTON_ROOM = 175;
private CellSociety cellSociety;
private ComboBox<String> selectionBox;
private VBox dynamicUpdaters;
private int societyNumber;
private double width;
private double height;
private int numCols;
private int numRows;
public SimulationGroup(CellSociety cellSociety, Animation animation, int societyNumber, int totalSocietyNumber)
{
this.cellSociety = cellSociety;
this.societyNumber = societyNumber;
numCols = (int) Math.ceil(Math.sqrt(totalSocietyNumber));
numRows = (int) Math.ceil(Math.sqrt(totalSocietyNumber));
width = getXScaleFactor() * SimulationTab.SIMULATIONS_WIDTH;
height = getYScaleFactor() * SimulationTab.SIMULATIONS_HEIGHT;
selectionBox = makeSelectionBox(animation, cellSociety);
dynamicUpdaters = getDynamicUpdaters(animation);
}
public BorderPane getSimulationImage()
{
return makeGridImage();
}
private BorderPane makeGridImage()
{
BorderPane borderPane = new BorderPane();
Group societyGroup = new Group();
for (int i = 0; i < cellSociety.getCellGrid().getHeight(); i++) {
for (int j = 0; j < cellSociety.getCellGrid().getWidth(); j++) {
Node addedCell = cellSociety.getCellGrid().getCell(i, j).getImage(height, width);
societyGroup.getChildren().add(addedCell);
}
}
borderPane.setCenter(societyGroup);
borderPane.setBottom(dynamicUpdaters);
return borderPane;
}
private double getXScaleFactor()
{
return (1.0) / numCols - ((double) BUTTON_ROOM / (double) SimulationTab.SIMULATIONS_WIDTH);
}
private double getYScaleFactor()
{
return (1.0) / numRows - ((double) BUTTON_ROOM / (double) SimulationTab.SIMULATIONS_HEIGHT);
}
public int getRowNumber()
{
return (int) Math.floor(societyNumber / numRows);
}
public int getColNumber()
{
return (societyNumber % numCols);
}
public VBox getDynamicUpdaters(Animation animation)
{
VBox vbox = new VBox();
for (Property<?> property : cellSociety.getRule().getProperties()) {
Node dynamicUpdater = property.makeDynamicUpdater();
if (dynamicUpdater != null) {
dynamicUpdater.setOnMousePressed((event) -> {
animation.stop();
});
dynamicUpdater.setOnMouseReleased((event) -> {
animation.play();
});
vbox.getChildren().add(dynamicUpdater);
}
}
vbox.getChildren().add(selectionBox);
vbox.setAlignment(Pos.CENTER);
return vbox;
}
private ComboBox<String> makeSelectionBox(Animation animation, CellSociety cellSociety)
{
ObservableList<String> xmlFiles = FXCollections.observableArrayList(XMLParser.RULE_MAP.keySet());
ComboBox<String> selectionBox = new ComboBox<String>(xmlFiles);
selectionBox.setLayoutX(width / 2);
selectionBox.setLayoutY(height);
selectionBox.setValue(xmlFiles.get(0));
selectionBox.setOnMousePressed((event) -> {
animation.stop();
});
selectionBox.valueProperty().addListener(new ChangeListener<String>()
{
@Override
public void changed(ObservableValue<? extends String> observable, String oldXML, String newXML)
{
XMLParser parser = new XMLParser();
cellSociety.setRule(parser.getRule(XMLParser.FILE_MAP.get(newXML)));
dynamicUpdaters = getDynamicUpdaters(animation);
animation.play();
}
});
return selectionBox;
}
}
| 28.484848 | 112 | 0.746543 |
e117ba536f4d28948ca1f19f4a0f91f9d9592536 | 17,960 | /*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.primitives.resources.impl;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import io.atomix.protocols.raft.RaftClient;
import io.atomix.protocols.raft.RaftError;
import io.atomix.protocols.raft.RaftServer;
import io.atomix.protocols.raft.ReadConsistency;
import io.atomix.protocols.raft.cluster.MemberId;
import io.atomix.protocols.raft.cluster.RaftMember;
import io.atomix.protocols.raft.cluster.impl.DefaultRaftMember;
import io.atomix.protocols.raft.event.RaftEvent;
import io.atomix.protocols.raft.event.impl.DefaultEventType;
import io.atomix.protocols.raft.operation.OperationType;
import io.atomix.protocols.raft.operation.RaftOperation;
import io.atomix.protocols.raft.operation.impl.DefaultOperationId;
import io.atomix.protocols.raft.protocol.AppendRequest;
import io.atomix.protocols.raft.protocol.AppendResponse;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.CloseSessionResponse;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.ConfigureRequest;
import io.atomix.protocols.raft.protocol.ConfigureResponse;
import io.atomix.protocols.raft.protocol.InstallRequest;
import io.atomix.protocols.raft.protocol.InstallResponse;
import io.atomix.protocols.raft.protocol.JoinRequest;
import io.atomix.protocols.raft.protocol.JoinResponse;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.KeepAliveResponse;
import io.atomix.protocols.raft.protocol.LeaveRequest;
import io.atomix.protocols.raft.protocol.LeaveResponse;
import io.atomix.protocols.raft.protocol.MetadataRequest;
import io.atomix.protocols.raft.protocol.MetadataResponse;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.OpenSessionResponse;
import io.atomix.protocols.raft.protocol.PollRequest;
import io.atomix.protocols.raft.protocol.PollResponse;
import io.atomix.protocols.raft.protocol.PublishRequest;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.protocols.raft.protocol.ReconfigureRequest;
import io.atomix.protocols.raft.protocol.ReconfigureResponse;
import io.atomix.protocols.raft.protocol.ResetRequest;
import io.atomix.protocols.raft.protocol.VoteRequest;
import io.atomix.protocols.raft.protocol.VoteResponse;
import io.atomix.protocols.raft.proxy.CommunicationStrategy;
import io.atomix.protocols.raft.proxy.RaftProxy;
import io.atomix.protocols.raft.service.RaftService;
import io.atomix.protocols.raft.session.SessionId;
import io.atomix.protocols.raft.storage.RaftStorage;
import io.atomix.protocols.raft.storage.log.entry.CloseSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.CommandEntry;
import io.atomix.protocols.raft.storage.log.entry.ConfigurationEntry;
import io.atomix.protocols.raft.storage.log.entry.InitializeEntry;
import io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry;
import io.atomix.protocols.raft.storage.log.entry.MetadataEntry;
import io.atomix.protocols.raft.storage.log.entry.OpenSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.QueryEntry;
import io.atomix.protocols.raft.storage.system.Configuration;
import io.atomix.storage.StorageLevel;
import org.junit.After;
import org.junit.Before;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.PartitionId;
import org.onosproject.store.primitives.impl.RaftClientCommunicator;
import org.onosproject.store.primitives.impl.RaftServerCommunicator;
import org.onosproject.store.service.Serializer;
/**
* Base class for various Atomix tests.
*
* @param <T> the Raft primitive type being tested
*/
public abstract class AtomixTestBase<T extends AbstractRaftPrimitive> {
private static final Serializer PROTOCOL_SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
.register(OpenSessionRequest.class)
.register(OpenSessionResponse.class)
.register(CloseSessionRequest.class)
.register(CloseSessionResponse.class)
.register(KeepAliveRequest.class)
.register(KeepAliveResponse.class)
.register(QueryRequest.class)
.register(QueryResponse.class)
.register(CommandRequest.class)
.register(CommandResponse.class)
.register(MetadataRequest.class)
.register(MetadataResponse.class)
.register(JoinRequest.class)
.register(JoinResponse.class)
.register(LeaveRequest.class)
.register(LeaveResponse.class)
.register(ConfigureRequest.class)
.register(ConfigureResponse.class)
.register(ReconfigureRequest.class)
.register(ReconfigureResponse.class)
.register(InstallRequest.class)
.register(InstallResponse.class)
.register(PollRequest.class)
.register(PollResponse.class)
.register(VoteRequest.class)
.register(VoteResponse.class)
.register(AppendRequest.class)
.register(AppendResponse.class)
.register(PublishRequest.class)
.register(ResetRequest.class)
.register(RaftResponse.Status.class)
.register(RaftError.class)
.register(RaftError.Type.class)
.register(ReadConsistency.class)
.register(byte[].class)
.register(long[].class)
.register(CloseSessionEntry.class)
.register(CommandEntry.class)
.register(ConfigurationEntry.class)
.register(InitializeEntry.class)
.register(KeepAliveEntry.class)
.register(MetadataEntry.class)
.register(OpenSessionEntry.class)
.register(QueryEntry.class)
.register(RaftOperation.class)
.register(RaftEvent.class)
.register(DefaultEventType.class)
.register(DefaultOperationId.class)
.register(OperationType.class)
.register(ReadConsistency.class)
.register(ArrayList.class)
.register(LinkedList.class)
.register(Collections.emptyList().getClass())
.register(HashSet.class)
.register(DefaultRaftMember.class)
.register(MemberId.class)
.register(SessionId.class)
.register(RaftMember.Type.class)
.register(Instant.class)
.register(Configuration.class)
.register(AtomixAtomicCounterMapOperations.class)
.register(AtomixConsistentMapEvents.class)
.register(AtomixConsistentMapOperations.class)
.register(AtomixConsistentSetMultimapOperations.class)
.register(AtomixConsistentSetMultimapEvents.class)
.register(AtomixConsistentTreeMapEvents.class)
.register(AtomixConsistentTreeMapOperations.class)
.register(AtomixCounterOperations.class)
.register(AtomixDocumentTreeEvents.class)
.register(AtomixDocumentTreeOperations.class)
.register(AtomixLeaderElectorEvents.class)
.register(AtomixLeaderElectorOperations.class)
.register(AtomixWorkQueueEvents.class)
.register(AtomixWorkQueueOperations.class)
.build());
private static final Serializer STORAGE_SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
.register(CloseSessionEntry.class)
.register(CommandEntry.class)
.register(ConfigurationEntry.class)
.register(InitializeEntry.class)
.register(KeepAliveEntry.class)
.register(MetadataEntry.class)
.register(OpenSessionEntry.class)
.register(QueryEntry.class)
.register(RaftOperation.class)
.register(ReadConsistency.class)
.register(AtomixAtomicCounterMapOperations.class)
.register(AtomixConsistentMapOperations.class)
.register(AtomixConsistentSetMultimapOperations.class)
.register(AtomixConsistentTreeMapOperations.class)
.register(AtomixCounterOperations.class)
.register(AtomixDocumentTreeOperations.class)
.register(AtomixLeaderElectorOperations.class)
.register(AtomixWorkQueueOperations.class)
.register(ArrayList.class)
.register(HashSet.class)
.register(DefaultRaftMember.class)
.register(MemberId.class)
.register(RaftMember.Type.class)
.register(Instant.class)
.register(Configuration.class)
.register(byte[].class)
.register(long[].class)
.build());
protected TestClusterCommunicationServiceFactory communicationServiceFactory;
protected List<RaftMember> members = Lists.newCopyOnWriteArrayList();
protected List<RaftClient> clients = Lists.newCopyOnWriteArrayList();
protected List<RaftServer> servers = Lists.newCopyOnWriteArrayList();
protected int nextId;
/**
* Creates the primitive service.
*
* @return the primitive service
*/
protected abstract RaftService createService();
/**
* Creates a new primitive.
*
* @param name the primitive name
* @return the primitive instance
*/
protected T newPrimitive(String name) {
RaftClient client = createClient();
RaftProxy proxy = client.newProxyBuilder()
.withName(name)
.withServiceType("test")
.withReadConsistency(readConsistency())
.withCommunicationStrategy(communicationStrategy())
.build()
.open()
.join();
return createPrimitive(proxy);
}
/**
* Creates a new primitive instance.
*
* @param proxy the primitive proxy
* @return the primitive instance
*/
protected abstract T createPrimitive(RaftProxy proxy);
/**
* Returns the proxy read consistency.
*
* @return the primitive read consistency
*/
protected ReadConsistency readConsistency() {
return ReadConsistency.LINEARIZABLE;
}
/**
* Returns the proxy communication strategy.
*
* @return the primitive communication strategy
*/
protected CommunicationStrategy communicationStrategy() {
return CommunicationStrategy.LEADER;
}
@Before
public void prepare() {
members.clear();
clients.clear();
servers.clear();
communicationServiceFactory = new TestClusterCommunicationServiceFactory();
createServers(3);
}
@After
public void cleanup() {
shutdown();
}
/**
* Shuts down clients and servers.
*/
private void shutdown() {
clients.forEach(c -> {
try {
c.close().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
}
});
servers.forEach(s -> {
try {
if (s.isRunning()) {
s.shutdown().get(10, TimeUnit.SECONDS);
}
} catch (Exception e) {
}
});
Path directory = Paths.get("target/primitives/");
if (Files.exists(directory)) {
try {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
}
}
}
/**
* Returns the next unique member identifier.
*
* @return The next unique member identifier.
*/
private MemberId nextMemberId() {
return MemberId.from(String.valueOf(++nextId));
}
/**
* Returns the next server address.
*
* @param type The startup member type.
* @return The next server address.
*/
private RaftMember nextMember(RaftMember.Type type) {
return new TestMember(nextMemberId(), type);
}
/**
* Creates a set of Raft servers.
*/
protected List<RaftServer> createServers(int nodes) {
List<RaftServer> servers = new ArrayList<>();
for (int i = 0; i < nodes; i++) {
members.add(nextMember(RaftMember.Type.ACTIVE));
}
CountDownLatch latch = new CountDownLatch(nodes);
for (int i = 0; i < nodes; i++) {
RaftServer server = createServer(members.get(i));
server.bootstrap(members.stream().map(RaftMember::memberId).collect(Collectors.toList()))
.thenRun(latch::countDown);
servers.add(server);
}
try {
latch.await(30000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return servers;
}
/**
* Creates a Raft server.
*/
private RaftServer createServer(RaftMember member) {
RaftServer.Builder builder = RaftServer.newBuilder(member.memberId())
.withType(member.getType())
.withProtocol(new RaftServerCommunicator(
PartitionId.from(1),
PROTOCOL_SERIALIZER,
communicationServiceFactory.newCommunicationService(NodeId.nodeId(member.memberId().id()))))
.withStorage(RaftStorage.newBuilder()
.withStorageLevel(StorageLevel.MEMORY)
.withDirectory(new File(String.format("target/primitives/%s", member.memberId())))
.withSerializer(new AtomixSerializerAdapter(STORAGE_SERIALIZER))
.withMaxSegmentSize(1024 * 1024)
.build())
.addService("test", this::createService);
RaftServer server = builder.build();
servers.add(server);
return server;
}
/**
* Creates a Raft client.
*/
private RaftClient createClient() {
MemberId memberId = nextMemberId();
RaftClient client = RaftClient.newBuilder()
.withMemberId(memberId)
.withProtocol(new RaftClientCommunicator(
PartitionId.from(1),
PROTOCOL_SERIALIZER,
communicationServiceFactory.newCommunicationService(NodeId.nodeId(memberId.id()))))
.build();
client.connect(members.stream().map(RaftMember::memberId).collect(Collectors.toList())).join();
clients.add(client);
return client;
}
/**
* Test member.
*/
public static class TestMember implements RaftMember {
private final MemberId memberId;
private final Type type;
public TestMember(MemberId memberId, Type type) {
this.memberId = memberId;
this.type = type;
}
@Override
public MemberId memberId() {
return memberId;
}
@Override
public int hash() {
return memberId.hashCode();
}
@Override
public Type getType() {
return type;
}
@Override
public void addTypeChangeListener(Consumer<Type> listener) {
}
@Override
public void removeTypeChangeListener(Consumer<Type> listener) {
}
@Override
public Instant getLastUpdated() {
return Instant.now();
}
@Override
public CompletableFuture<Void> promote() {
return null;
}
@Override
public CompletableFuture<Void> promote(Type type) {
return null;
}
@Override
public CompletableFuture<Void> demote() {
return null;
}
@Override
public CompletableFuture<Void> demote(Type type) {
return null;
}
@Override
public CompletableFuture<Void> remove() {
return null;
}
}
}
| 36.87885 | 116 | 0.658018 |
2dbaf7074b8fdcdc2e217df3fde00ec2045685c1 | 13,556 | package dev.squaremile.asynctcp.internal.transport.nonblockingimpl;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import org.agrona.CloseHelper;
import org.agrona.LangUtil;
import org.agrona.concurrent.EpochClock;
import org.agrona.nio.TransportPoller;
import dev.squaremile.asynctcp.api.transport.app.ConnectionCommand;
import dev.squaremile.asynctcp.api.transport.app.ConnectionUserCommand;
import dev.squaremile.asynctcp.api.transport.app.EventListener;
import dev.squaremile.asynctcp.api.transport.app.Transport;
import dev.squaremile.asynctcp.api.transport.app.TransportCommand;
import dev.squaremile.asynctcp.api.transport.app.TransportCommandHandler;
import dev.squaremile.asynctcp.api.transport.app.TransportUserCommand;
import dev.squaremile.asynctcp.api.transport.commands.Connect;
import dev.squaremile.asynctcp.api.transport.commands.Listen;
import dev.squaremile.asynctcp.api.transport.commands.SendData;
import dev.squaremile.asynctcp.api.transport.commands.StopListening;
import dev.squaremile.asynctcp.api.transport.events.StartedListening;
import dev.squaremile.asynctcp.api.transport.events.StoppedListening;
import dev.squaremile.asynctcp.api.transport.events.TransportCommandFailed;
import dev.squaremile.asynctcp.api.transport.values.ConnectionIdValue;
import dev.squaremile.asynctcp.internal.transport.domain.CommandFactory;
import dev.squaremile.asynctcp.internal.transport.domain.NoOpCommand;
import dev.squaremile.asynctcp.internal.transport.domain.ReadData;
import dev.squaremile.asynctcp.internal.transport.domain.connection.Connection;
import dev.squaremile.asynctcp.internal.transport.domain.connection.ConnectionConfiguration;
import dev.squaremile.asynctcp.internal.transport.domain.connection.ConnectionState;
public class NonBlockingTransport extends TransportPoller implements AutoCloseable, Transport
{
private final ConnectionIdSource connectionIdSource;
private final Selector selector;
private final CommandFactory commandFactory = new CommandFactory();
private final EventListener eventListener;
private final Connections connections;
private final Servers servers;
private final PendingConnections pendingConnections;
private final EpochClock clock;
private final TransportCommandHandler commandHandler;
private final String role;
private final RelativeClock relativeClock;
private final WorkProtection workProtection;
public NonBlockingTransport(final EventListener eventListener, final TransportCommandHandler commandHandler, final EpochClock clock, final String role)
{
this.role = role;
this.clock = clock;
this.relativeClock = new RelativeClock.SystemRelativeClock();
this.servers = new Servers(relativeClock);
this.connections = new Connections(eventListener::onEvent);
this.eventListener = eventListener;
this.commandHandler = commandHandler;
this.pendingConnections = new PendingConnections(clock, eventListener);
this.connectionIdSource = new ConnectionIdSource();
this.workProtection = new WorkProtection(role);
try
{
this.selector = Selector.open();
SELECTED_KEYS_FIELD.set(selector, selectedKeySet);
PUBLIC_SELECTED_KEYS_FIELD.set(selector, selectedKeySet);
}
catch (IOException | IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
private void handle(final ConnectionUserCommand command)
{
workProtection.onHandle();
Connection connection = connections.get(command.connectionId());
if (connection == null)
{
eventListener.onEvent(new TransportCommandFailed(command, "Connection id not found"));
return;
}
connection.handle(command);
connections.updateBasedOnState(connection);
if (connection.state() == ConnectionState.CLOSED)
{
connections.remove(command.connectionId());
}
}
@Override
public void work()
{
workProtection.onWork();
if (!workProtection.nextWorkAllowedNs(relativeClock.relativeNanoTime()))
{
return;
}
pendingConnections.work();
try
{
if (selector.selectNow() > 0)
{
final SelectionKey[] keys = selectedKeySet.keys();
for (int i = 0, length = selectedKeySet.size(); i < length; i++)
{
final SelectionKey key = keys[i];
if (!key.isValid())
{
continue;
}
if (key.isAcceptable())
{
ListeningSocketContext listeningSocketContext = (ListeningSocketContext)key.attachment();
int port = listeningSocketContext.port();
final Server server = servers.serverListeningOn(port);
final SocketChannel acceptedSocketChannel = server.acceptChannel();
long connectionId = registerConnection(acceptedSocketChannel, server.createConnection(acceptedSocketChannel, listeningSocketContext.delineation()));
connections.get(connectionId).accepted(server.commandIdThatTriggeredListening());
}
else if (key.isConnectable())
{
ConnectedNotification connectedNotification = pendingConnections.pendingConnection(key);
SocketChannel socketChannel = connectedNotification.socketChannel;
socketChannel.socket().setTcpNoDelay(true);
try
{
socketChannel.finishConnect();
}
catch (ConnectException e)
{
eventListener.onEvent(new TransportCommandFailed(
connectedNotification.port, connectedNotification.commandId, e.getMessage(), Connect.class
));
pendingConnections.removePendingConnection(key);
key.cancel();
}
if (socketChannel.isConnected())
{
Socket socket = socketChannel.socket();
socket.setTcpNoDelay(true);
ConnectionIdValue connectionId = new ConnectionIdValue(socket.getLocalPort(), connectionIdSource.newId());
final ConnectionConfiguration configuration = new ConnectionConfiguration(
connectionId,
connectedNotification.remoteHost,
socket.getPort(),
socket.getSendBufferSize(),
socket.getSendBufferSize() * 16,
socket.getReceiveBufferSize()
);
registerConnection(
socketChannel,
new ConnectionImpl(
role,
configuration,
relativeClock,
new SocketBackedChannel(socketChannel),
connectedNotification.command.delineation(),
eventListener::onEvent
)
);
connections.get(connectionId.connectionId()).connected(connectedNotification.commandId);
pendingConnections.removePendingConnection(key);
}
}
else
{
ConnectionCommand command = ((ConnectionConductor)key.attachment()).command(key);
Connection connection = connections.get(command.connectionId());
connection.handle(command);
if (connection.state() == ConnectionState.CLOSED)
{
connections.remove(command.connectionId());
}
}
}
selectedKeySet.reset();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
connections.work();
}
@Override
public <C extends TransportUserCommand> C command(final Class<C> commandType)
{
return commandFactory.create(commandType);
}
@Override
public <C extends ConnectionUserCommand> C command(final long connectionId, final Class<C> commandType)
{
Connection connection = connections.get(connectionId);
if (connection == null)
{
throw new IllegalArgumentException("There is no connection " + connectionId);
}
return connection.command(commandType);
}
@Override
public void onStart()
{
connections.onStart();
}
@Override
public void onStop()
{
connections.onStop();
}
@Override
public void handle(final TransportCommand command)
{
commandHandler.handle(command);
tryHandle(command);
}
private void tryHandle(final TransportCommand command)
{
if (command instanceof ConnectionUserCommand)
{
handle((ConnectionUserCommand)command);
}
else if (command instanceof Listen)
{
handle((Listen)command);
}
else if (command instanceof StopListening)
{
handle((StopListening)command);
}
else if (command instanceof Connect)
{
handle((Connect)command);
}
else
{
throw new UnsupportedOperationException(command.getClass().getCanonicalName());
}
}
@Override
public void close()
{
CloseHelper.close(connections);
CloseHelper.closeAll(servers);
CloseHelper.close(selector);
}
private long registerConnection(final SocketChannel socketChannel, final Connection connection) throws ClosedChannelException
{
connections.add(connection, socketChannel.register(
selector,
SelectionKey.OP_READ,
new ConnectionConductor(
new ReadData(connection),
new SendData(connection, 0),
new NoOpCommand(connection)
)
));
return connection.connectionId();
}
private void handle(final Listen command)
{
if (servers.isListeningOn(command.port()))
{
eventListener.onEvent(new TransportCommandFailed(command, "Address already in use"));
return;
}
try
{
servers.start(role, command.port(), command.commandId(), connectionIdSource, eventListener, commandFactory);
Server server = servers.serverListeningOn(command.port());
final ServerSocketChannel serverSocketChannel = server.serverSocketChannel();
final SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
selectionKey.attach(new ListeningSocketContext(server.port(), command.delineation()));
eventListener.onEvent(new StartedListening(command.port(), command.commandId(), command.delineation()));
}
catch (IOException e)
{
servers.stop(command.port());
eventListener.onEvent(new TransportCommandFailed(command, e.getMessage()));
}
}
private void handle(final StopListening command)
{
if (!servers.isListeningOn(command.port()))
{
eventListener.onEvent(new TransportCommandFailed(command, "No listening socket found on this port"));
return;
}
servers.stop(command.port());
eventListener.onEvent(new StoppedListening(command.port(), command.commandId()));
}
private void handle(final Connect command)
{
try
{
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress(command.remoteHost(), command.remotePort()));
final SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_CONNECT);
pendingConnections.add(new ConnectedNotification(socketChannel, command, clock.time() + command.timeoutMs(), selectionKey, command.delineation()));
}
catch (IOException e)
{
LangUtil.rethrowUnchecked(e);
}
}
@Override
public String toString()
{
return "NonBlockingTransport{" +
"role='" + role + '\'' +
'}';
}
}
| 40.465672 | 172 | 0.602464 |
9f084650f769bcb4b2de1fa9a776d348574ce80b | 10,646 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.dsl.model.android;
import com.android.tools.idea.gradle.dsl.api.android.ProductFlavorModel;
import com.android.tools.idea.gradle.dsl.api.android.productFlavors.ExternalNativeBuildOptionsModel;
import com.android.tools.idea.gradle.dsl.api.android.productFlavors.NdkOptionsModel;
import com.android.tools.idea.gradle.dsl.api.android.productFlavors.VectorDrawablesOptionsModel;
import com.android.tools.idea.gradle.dsl.api.ext.ResolvedPropertyModel;
import com.android.tools.idea.gradle.dsl.model.android.productFlavors.ExternalNativeBuildOptionsModelImpl;
import com.android.tools.idea.gradle.dsl.model.android.productFlavors.NdkOptionsModelImpl;
import com.android.tools.idea.gradle.dsl.model.android.productFlavors.VectorDrawablesOptionsModelImpl;
import com.android.tools.idea.gradle.dsl.model.ext.GradlePropertyModelBuilder;
import com.android.tools.idea.gradle.dsl.model.ext.PropertyUtil;
import com.android.tools.idea.gradle.dsl.parser.android.AbstractProductFlavorDslElement;
import com.android.tools.idea.gradle.dsl.parser.android.ProductFlavorDslElement;
import com.android.tools.idea.gradle.dsl.parser.android.productFlavors.ExternalNativeBuildOptionsDslElement;
import com.android.tools.idea.gradle.dsl.parser.android.productFlavors.NdkOptionsDslElement;
import com.android.tools.idea.gradle.dsl.parser.android.productFlavors.VectorDrawablesOptionsDslElement;
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslElement;
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionList;
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionMap;
import com.android.tools.idea.gradle.dsl.parser.elements.GradleNameElement;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.android.tools.idea.gradle.dsl.api.ext.PropertyType.REGULAR;
import static com.android.tools.idea.gradle.dsl.parser.android.productFlavors.ExternalNativeBuildOptionsDslElement.EXTERNAL_NATIVE_BUILD_OPTIONS;
import static com.android.tools.idea.gradle.dsl.parser.android.productFlavors.NdkOptionsDslElement.NDK_OPTIONS;
import static com.android.tools.idea.gradle.dsl.parser.android.productFlavors.VectorDrawablesOptionsDslElement.VECTOR_DRAWABLES_OPTIONS;
public final class ProductFlavorModelImpl extends FlavorTypeModelImpl implements ProductFlavorModel {
/**
* These are used here and in the construction of Dsl by {@link ProductFlavorDslElement}.
*/
@NonNls public static final String APPLICATION_ID = "mApplicationId";
@NonNls public static final String DIMENSION = "mDimension";
@NonNls public static final String MAX_SDK_VERSION = "mMaxSdkVersion";
@NonNls public static final String MIN_SDK_VERSION = "mMinSdkVersion";
@NonNls public static final String MISSING_DIMENSION_STRATEGY = "mMissingDimensionStrategy";
@NonNls public static final String RENDER_SCRIPT_TARGET_API = "mRenderscriptTargetApi";
@NonNls public static final String RENDER_SCRIPT_SUPPORT_MODE_ENABLED = "mRenderscriptSupportModeEnabled";
@NonNls public static final String RENDER_SCRIPT_SUPPORT_MODE_BLAS_ENABLED = "mRenderscriptSupportModeBlasEnabled";
@NonNls public static final String RENDER_SCRIPT_NDK_MODE_ENABLED = "mRenderscriptNdkModeEnabled";
@NonNls public static final String RES_CONFIGS = "mResConfigs";
@NonNls public static final String TARGET_SDK_VERSION = "mTargetSdkVersion";
@NonNls public static final String TEST_APPLICATION_ID = "mTestApplicationId";
@NonNls public static final String TEST_FUNCTIONAL_TEST = "mTestFunctionalTest";
@NonNls public static final String TEST_HANDLE_PROFILING = "mTestHandleProfiling";
@NonNls public static final String TEST_INSTRUMENTATION_RUNNER = "mTestInstrumentationRunner";
@NonNls public static final String TEST_INSTRUMENTATION_RUNNER_ARGUMENTS = "mTestInstrumentationRunnerArguments";
@NonNls public static final String VERSION_CODE = "mVersionCode";
@NonNls public static final String VERSION_NAME = "mVersionName";
@NonNls public static final String WEAR_APP_UNBUNDLED = "mWearAppUnbundled";
public ProductFlavorModelImpl(@NotNull AbstractProductFlavorDslElement dslElement) {
super(dslElement);
}
@Override
@NotNull
public ResolvedPropertyModel applicationId() {
return getModelForProperty(APPLICATION_ID);
}
@Override
@NotNull
public ResolvedPropertyModel dimension() {
return getModelForProperty(DIMENSION);
}
@Override
@NotNull
public ExternalNativeBuildOptionsModel externalNativeBuild() {
ExternalNativeBuildOptionsDslElement externalNativeBuildOptionsDslElement =
myDslElement.ensurePropertyElement(EXTERNAL_NATIVE_BUILD_OPTIONS);
return new ExternalNativeBuildOptionsModelImpl(externalNativeBuildOptionsDslElement);
}
@Override
public void removeExternalNativeBuild() {
myDslElement.removeProperty(EXTERNAL_NATIVE_BUILD_OPTIONS.name);
}
@Override
@NotNull
public ResolvedPropertyModel maxSdkVersion() {
return getModelForProperty(MAX_SDK_VERSION);
}
@Override
@NotNull
public ResolvedPropertyModel minSdkVersion() {
return getModelForProperty(MIN_SDK_VERSION);
}
@NotNull
@Override
public List<ResolvedPropertyModel> missingDimensionStrategies() {
List<ResolvedPropertyModel> models = new ArrayList<>();
for (GradleDslExpressionList list : myDslElement.getPropertyElements(MISSING_DIMENSION_STRATEGY, GradleDslExpressionList.class)) {
if (list.getExpressions().size() > 1) {
models.add(GradlePropertyModelBuilder.create(list).buildResolved());
}
}
return models;
}
@NotNull
@Override
public ResolvedPropertyModel addMissingDimensionStrategy(@NotNull String dimension, @NotNull Object... fallbacks) {
GradleDslExpressionList list = new GradleDslExpressionList(myDslElement, GradleNameElement.create(MISSING_DIMENSION_STRATEGY), false);
myDslElement.setNewElement(list);
list.setElementType(REGULAR);
ResolvedPropertyModel model = GradlePropertyModelBuilder.create(list).buildResolved();
model.addListValue().setValue(dimension);
for (Object fallback : fallbacks) {
model.addListValue().setValue(fallback);
}
return model;
}
@Override
public boolean areMissingDimensionStrategiesModified() {
List<GradleDslElement> originalElements =
myDslElement.getOriginalElements().stream().filter(e -> e.getName().equals(MISSING_DIMENSION_STRATEGY)).collect(Collectors.toList());
List<GradleDslElement> currentElements = myDslElement.getPropertyElementsByName(MISSING_DIMENSION_STRATEGY);
if (originalElements.size() != currentElements.size()) {
return true;
}
for (GradleDslElement oldElement : originalElements) {
boolean modified = true;
for (GradleDslElement newElement : currentElements) {
modified &= PropertyUtil.isElementModified(oldElement, newElement);
}
if (modified) {
return true;
}
}
return false;
}
@Override
@NotNull
public NdkOptionsModel ndk() {
NdkOptionsDslElement ndkOptionsDslElement = myDslElement.ensurePropertyElement(NDK_OPTIONS);
return new NdkOptionsModelImpl(ndkOptionsDslElement);
}
@Override
public void removeNdk() {
myDslElement.removeProperty(NDK_OPTIONS.name);
}
@Override
@NotNull
public ResolvedPropertyModel resConfigs() {
return getModelForProperty(RES_CONFIGS);
}
@NotNull
@Override
public ResolvedPropertyModel renderscriptTargetApi() {
return getModelForProperty(RENDER_SCRIPT_TARGET_API);
}
@NotNull
@Override
public ResolvedPropertyModel renderscriptSupportModeEnabled() {
return getModelForProperty(RENDER_SCRIPT_SUPPORT_MODE_ENABLED);
}
@NotNull
@Override
public ResolvedPropertyModel renderscriptSupportModelBlasEnabled() {
return getModelForProperty(RENDER_SCRIPT_SUPPORT_MODE_BLAS_ENABLED);
}
@NotNull
@Override
public ResolvedPropertyModel renderscriptNdkModeEnabled() {
return getModelForProperty(RENDER_SCRIPT_NDK_MODE_ENABLED);
}
@Override
@NotNull
public ResolvedPropertyModel targetSdkVersion() {
return getModelForProperty(TARGET_SDK_VERSION);
}
@Override
@NotNull
public ResolvedPropertyModel testApplicationId() {
return getModelForProperty(TEST_APPLICATION_ID);
}
@Override
@NotNull
public ResolvedPropertyModel testFunctionalTest() {
return getModelForProperty(TEST_FUNCTIONAL_TEST);
}
@Override
@NotNull
public ResolvedPropertyModel testHandleProfiling() {
return getModelForProperty(TEST_HANDLE_PROFILING);
}
@Override
@NotNull
public ResolvedPropertyModel testInstrumentationRunner() {
return getModelForProperty(TEST_INSTRUMENTATION_RUNNER);
}
@Override
@NotNull
public ResolvedPropertyModel testInstrumentationRunnerArguments() {
GradleDslExpressionMap testInstrumentationRunnerArguments = myDslElement.getPropertyElement(GradleDslExpressionMap.TEST_INSTRUMENTATION_RUNNER_ARGUMENTS);
if (testInstrumentationRunnerArguments == null) {
myDslElement.addDefaultProperty(new GradleDslExpressionMap(myDslElement, GradleNameElement.fake(TEST_INSTRUMENTATION_RUNNER_ARGUMENTS)));
}
return getModelForProperty(TEST_INSTRUMENTATION_RUNNER_ARGUMENTS);
}
@Override
@NotNull
public ResolvedPropertyModel versionCode() {
return getModelForProperty(VERSION_CODE);
}
@Override
@NotNull
public ResolvedPropertyModel versionName() {
return getModelForProperty(VERSION_NAME);
}
@NotNull
@Override
public VectorDrawablesOptionsModel vectorDrawables() {
VectorDrawablesOptionsDslElement vectorDrawableElement = myDslElement.ensurePropertyElement(VECTOR_DRAWABLES_OPTIONS);
return new VectorDrawablesOptionsModelImpl(vectorDrawableElement);
}
@NotNull
@Override
public ResolvedPropertyModel wearAppUnbundled() {
return getModelForProperty(WEAR_APP_UNBUNDLED);
}
}
| 39.723881 | 158 | 0.800113 |
1a3ec383ee942e1177976a06e701725648e1708b | 3,663 | package com.jackie.media_preview.ui;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;
import com.jackie.media_preview.R;
import com.jackie.media_preview.entity.MediaData;
import com.jackie.media_preview.utils.UniversalImageLoaderUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
/**
* <br>预览图片或视频的{@link Fragment },在{@link SelectPhotosFragment }中点击子项缩略图跳转至当前{@link Fragment }
* <br>Created by Jackie on 7/14/15.
*
* @author Jackie
* @version 1.0
*/
public class PreviewFragment extends BaseFragment<SelectPhotosActivity> {
private static final String TAG = PreviewFragment.class.getSimpleName();
/**
* 当点击的是图片的缩略图在此{@link ImageView}控件中显示此缩略图的全部内容
*/
private ImageView imageView;
/**
* 当点击的是视频的缩略图在此{@link VideoView}控件中显示此视频的内容并在{@link VideoView}中播放
*/
private VideoView videoView;
/**
* @see MediaController
*/
private MediaController mediaController;
/**
* 所点击的缩略图的{@link MediaData}封装对象
*/
private MediaData mediaData;
public static PreviewFragment newInstance(String... params) {
return createInstance(new PreviewFragment(), params);
}
@Override
public void setLayoutId() {
layoutId = R.layout.preview_album;
}
@Override
public void initView() {
Log.i(TAG, "initView");
imageView = getViewById(R.id.preview_image_view);
videoView = getViewById(R.id.preview_video_view);
displayView();
}
/**
* <br>根据点击的缩略图传入的{@link MediaData}数据类型的{@link MediaData#getType()}在当前UI中显示不同的视图
* <br>{@link MediaData#getType()}若得到的为{@link MediaData#TYPE_VIDEO}则通过{@link VideoView}显示可播放的视频
* <br>预览,若得到的为{@link MediaData#TYPE_IMAGE}显示图片的全部内容
*/
private void displayView() {
if (!TextUtils.isEmpty(mediaData.getPath()) && imageView != null) {
if (MediaData.TYPE_VIDEO.equals(mediaData.getType())) {
videoView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
// 视频预览
if (mediaController == null) {
mediaController = new MediaController(getActivity());
}
videoView.setMediaController(mediaController);
videoView.setVideoURI(mediaData.getContentUri());
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
videoView.start();
} else {
imageView.setVisibility(View.VISIBLE);
videoView.setVisibility(View.GONE);
String path = mediaData.getPath();
Log.i(TAG, "displayView& uri: " + mediaData.getContentUri());
// 显示图片预览
ImageLoader.getInstance().displayImage(path, imageView, UniversalImageLoaderUtil.options);
}
}
}
/**
* Called when the Fragment is no longer started. This is generally
* tied to {@link Activity#onStop() Activity.onStop} of the containing
* Activity's lifecycle.
*/
@Override
public void onStop() {
super.onStop();
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
}
/**
* 传入缩略图的封装数据{@link MediaData}在当前UI中显示数据中的内容
*
* @param mediaData 缩略图的数据内容
*/
public void displayImage(MediaData mediaData) {
this.mediaData = mediaData;
displayView();
}
}
| 29.540323 | 106 | 0.632542 |
a811a98c6eca2f34fbfe0af065be02a5a2cd41a8 | 4,538 | package io.github.gecko10000.GeckoSpawners;
import de.tr7zw.nbtapi.NBTCompound;
import de.tr7zw.nbtapi.NBTContainer;
import io.github.gecko10000.GeckoSpawners.guis.MainEditor;
import io.github.gecko10000.GeckoSpawners.guis.SpawnerEditor;
import io.github.gecko10000.GeckoSpawners.objects.SpawnCandidate;
import io.github.gecko10000.GeckoSpawners.objects.SpawnerObject;
import io.github.gecko10000.GeckoSpawners.util.Config;
import io.github.gecko10000.GeckoSpawners.util.Lang;
import io.github.gecko10000.GeckoSpawners.util.ShortWrapper;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import redempt.redlib.configmanager.ConfigManager;
import redempt.redlib.configmanager.annotations.ConfigValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GeckoSpawners extends JavaPlugin {
public ConfigManager spawnerConfig;
@ConfigValue("spawners")
public Map<String, SpawnerObject> spawnerObjects = ConfigManager.map(String.class, SpawnerObject.class);
public Map<Player, SpawnCandidate> editingCandidates = new HashMap<>();
public Map<Player, SpawnerEditor> previousEditors = new HashMap<>();
public MainEditor editor;
public static final NamespacedKey SPAWNER_NAME_KEY = NamespacedKey.fromString("geckospawners:name");
public void onEnable() {
reload();
new CommandHandler(this);
new Listeners(this);
editor = new MainEditor(this);
}
public void onDisable() {
spawnerConfig.save();
}
public void reload() {
new ConfigManager(this)
.addConverter(ShortWrapper.class, ShortWrapper::new, ShortWrapper::toString)
.register(Config.class).saveDefaults().load();
new ConfigManager(this, "lang.yml")
.register(Lang.class).saveDefaults().load();
spawnerConfig = new ConfigManager(this, "spawners.yml")
.addConverter(NBTCompound.class, NBTContainer::new, NBTCompound::toString)
.addConverter(Material.class, Material::getMaterial, Material::toString)
.addConverter(ShortWrapper.class, ShortWrapper::new, ShortWrapper::toString)
.register(this).saveDefaults().load();
editor = new MainEditor(this);
}
public ItemStack pageItem(boolean prev) {
ItemStack item = new ItemStack(prev ? Material.RED_STAINED_GLASS_PANE : Material.LIME_STAINED_GLASS_PANE);
ItemMeta meta = item.getItemMeta();
meta.displayName(Component.translatable("createWorld.customize.custom." + (prev ? "prev" : "next"))
.decoration(TextDecoration.ITALIC, false)
.color(prev ? NamedTextColor.RED : NamedTextColor.GREEN));
item.setItemMeta(meta);
return item;
}
public ItemStack backItem() {
ItemStack item = new ItemStack(Material.RED_STAINED_GLASS_PANE);
ItemMeta meta = item.getItemMeta();
meta.displayName(Component.translatable("gui.back")
.decoration(TextDecoration.ITALIC, false)
.color(NamedTextColor.RED));
item.setItemMeta(meta);
return item;
}
public ItemStack makeItem(Material material, String name) {
return makeItem(material, name, new ArrayList<>());
}
public ItemStack makeItem(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.displayName(makeReadable(name).decoration(TextDecoration.ITALIC, false));
meta.lore(lore.stream()
.map(GeckoSpawners::makeReadable)
.map(c -> c.decoration(TextDecoration.ITALIC, false))
.collect(Collectors.toList())
);
item.setItemMeta(meta);
return item;
}
public static List<Component> makeReadable(List<String> input) {
return input.stream().map(GeckoSpawners::makeReadable).collect(Collectors.toList());
}
public static Component makeReadable(String input) {
return MiniMessage.get().parse(input);
}
}
| 39.46087 | 114 | 0.705377 |
6459bddf062486dcefeb8c81a03c00705943e457 | 1,009 | package ru.betterend.registry;
import net.fabricmc.fabric.api.client.rendereregistry.v1.EntityRendererRegistry;
import net.minecraft.client.render.entity.MobEntityRenderer;
import net.minecraft.entity.EntityType;
import ru.betterend.entity.render.RendererEntityDragonfly;
import ru.betterend.entity.render.RendererEntityEndSlime;
public class EntityRenderRegistry {
public static void register() {
register(EntityRegistry.DRAGONFLY, RendererEntityDragonfly.class);
register(EntityRegistry.END_SLIME, RendererEntityEndSlime.class);
}
private static void register(EntityType<?> type, Class<? extends MobEntityRenderer<?, ?>> renderer) {
EntityRendererRegistry.INSTANCE.register(type, (entityRenderDispatcher, context) -> {
MobEntityRenderer<?, ?> render = null;
try {
render = renderer.getConstructor(entityRenderDispatcher.getClass()).newInstance(entityRenderDispatcher);
} catch (Exception e) {
e.printStackTrace();
}
return render;
});
}
}
| 36.035714 | 109 | 0.763132 |
93a0277fec46a331118a19bba1acd3729493afce | 1,153 | package sorting;
public class QuickSortRecursive {
public void quickSort(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException();
}
quickSort(arr, 0, arr.length -1);
}
private void quickSort(int[] arr, int left, int right) {
int index = partition(arr, left, right);
if (left < index -1) {
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(arr, index, right);
}
}
private int partition(int[] arr, int left, int right) {
int pivot = arr[left + right /2];
while (left <= right) {
while (arr[left] < pivot) {
left++;
}
while (arr[right] > pivot) {
right--;
}
if (left <= right) {
swap(arr, left, right);
left++;
right--;
}
}
return left;
}
private void swap(int[] arr, int left, int right) {
int temp = arr[right];
arr[right] = arr[left];
arr[left] = temp;
}
}
| 23.530612 | 60 | 0.452732 |
e01d2f8272b21eb0790c17c407f5a1812da8b3b6 | 666 | /*
* © 2021. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.io.extractor;
/**
* This interface should be implemented only by other interfaces that should be used by the {@link
* Extractor} It provides the entry point for the extraction method in the {@link Extractor}. If
* this interface is implemented by other interfaces one has to take care about, that the
* corresponding extractElements()-method in {@link Extractor} is extended accordingly.
*
* @version 0.1
* @since 31.03.20
*/
public interface NestedEntity {}
| 37 | 98 | 0.756757 |
dc0e8e47cbb278c4d5592c0f9082f5a05d58f70b | 645 | package io.github.xerprojects.xerj.commandstack.exceptions;
/**
* Base exception for command stack library.
*
* @author Joel Jeremy Marquez
*/
public class CommandStackException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructor.
* @param message The exception message.
*/
public CommandStackException(String message) {
super(message);
}
/**
* Constructor.
* @param message The exception message.
* @param cause The cause of the exception.
*/
public CommandStackException(String message, Throwable cause) {
super(message, cause);
}
}
| 22.241379 | 67 | 0.688372 |
66de3e312e3a4fb64787d18d639bbac32b0b0d51 | 3,241 | package engine.graph;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.system.MemoryStack;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL11.glTexParameteri;
import static org.lwjgl.opengl.GL14.GL_TEXTURE_LOD_BIAS;
import static org.lwjgl.opengl.GL30.glGenerateMipmap;
import static org.lwjgl.stb.STBImage.*;
public class Texture implements Serializable {
private final int ID;
private int width;
private int height;
public Texture(String fileName){
ByteBuffer buf = null;
width = 0;
height = 0;
// Load Texture file
try (MemoryStack stack = MemoryStack.stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer channels = stack.mallocInt(1);
buf = stbi_load(fileName, w, h, channels, 4);
if (buf == null) {
throw new Exception("Image file [" + fileName + "] not loaded: " + stbi_failure_reason());
}
width = w.get();
height = h.get();
} catch (Exception e) {
e.printStackTrace();
}
this.ID = createTexture(buf);
stbi_image_free(buf);
buf.clear();
}
public Texture(ByteBuffer imageBuffer) throws Exception {
ByteBuffer buf;
// Load Texture file
try (MemoryStack stack = MemoryStack.stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer channels = stack.mallocInt(1);
buf = stbi_load_from_memory(imageBuffer, w, h, channels, 4);
if (buf == null) {
throw new Exception("Image file not loaded: " + stbi_failure_reason());
}
width = w.get();
height = h.get();
}
this.ID = createTexture(buf);
stbi_image_free(buf);
buf.clear();
}
private int createTexture(ByteBuffer buf) {
// Create a new OpenGL texture
int textureId = glGenTextures();
// Bind the texture
glBindTexture(GL_TEXTURE_2D, textureId);
// Tell OpenGL how to unpack the RGBA bytes. Each component is 1 byte size
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Upload the texture data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, buf);
// Generate Mip Map
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, -1);
return textureId;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public void bind() {
glBindTexture(GL_TEXTURE_2D, ID);
}
public int getId() {
return ID;
}
public void cleanUp() {
glDeleteTextures(ID);
}
}
| 28.681416 | 108 | 0.583153 |
4bf81019b6bb623e22d1182cf016bdf01d308c99 | 1,864 | /*
* Copyright 2012 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.jabuticava.cnab.remessa;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public class ConstrutorDeCobrancaFalso {
private Carteira carteira;
private Agencia agencia;
private Conta conta;
private Comando comando;
private Titulo titulo;
private CobrancaOpcoes opcoes = CobrancaOpcoes.padrao();
public Cobranca novaInstancia() {
return Cobranca.builder()
.carteira(carteira)
.agencia(agencia)
.conta(conta)
.comando(comando)
.titulo(titulo)
.opcoes(opcoes)
.build();
}
public ConstrutorDeCobrancaFalso carteira(Carteira carteira) {
this.carteira = carteira;
return this;
}
public ConstrutorDeCobrancaFalso agencia(Agencia agencia) {
this.agencia = agencia;
return this;
}
public ConstrutorDeCobrancaFalso conta(Conta conta) {
this.conta = conta;
return this;
}
public ConstrutorDeCobrancaFalso comando(Comando comando) {
this.comando = comando;
return this;
}
public ConstrutorDeCobrancaFalso titulo(Titulo titulo) {
this.titulo = titulo;
return this;
}
public ConstrutorDeCobrancaFalso opcoes(CobrancaOpcoes opcoes) {
this.opcoes = opcoes;
return this;
}
} | 26.253521 | 80 | 0.711373 |
006f8d712c1e863b0ce6c337f2d8bdaae8cb451f | 759 | package org.mi.adminui.web.core.configuration;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/robots.txt")
.addResourceLocations("classpath:/static/robots.txt");
}
@Bean
public LayoutDialect layoutDialect() {
return new LayoutDialect();
}
}
| 33 | 81 | 0.779974 |
11d5ddc011c9dee941ff9866b678bd8acd296d13 | 500 | package org.oagi.score.repo.component.bccp;
import java.math.BigInteger;
public class UpdateBccpBdtRepositoryResponse {
private final BigInteger bccpManifestId;
private final String den;
public UpdateBccpBdtRepositoryResponse(BigInteger bccpManifestId, String den) {
this.bccpManifestId = bccpManifestId;
this.den = den;
}
public BigInteger getBccpManifestId() {
return bccpManifestId;
}
public String getDen() {
return den;
}
}
| 20.833333 | 83 | 0.702 |
58f03a525af0dd0511ee14efcc58ab92d954ef5a | 197 | package com.example.exceptions.username;
public class InvalidUsernameFormatException extends RuntimeException {
public InvalidUsernameFormatException(String message) {
super(message);
}
}
| 24.625 | 70 | 0.812183 |
619b9b0041ff607e0a30a9693b5d464d3a0b7b2f | 6,527 | package com.ieoca.algorithm.ga;
import com.ieoca.components.problem.Problem;
import com.ieoca.problem.TSP;
import java.util.Arrays;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class GeneticAlgorithm extends GA {
private final Logger logger = LogManager.getLogger(GeneticAlgorithm.class);
private TSP tsp;
private final double mutationRate = 0.015;
private final int tournamentSize = 5;
private final int populationSize = 50;
private final int iterations = 1000;
private final boolean elitism = true;
private Tour fittest;
private GeneticAlgorithm() {
super(new GeneticAlgorithmView());
this.logger.info(String.format("%s was loaded.", GeneticAlgorithm.class));
}
@Override
public void run() {
this.solve(this.tsp);
}
@Override
public void solve(Problem problem) {
this.tsp.setEventsEnabled(false);
this.distances = this.tsp.getDistances();
this.cities = this.distances.length;
this.logger.info(GeneticAlgorithm.printDistance(this.distances));
Population pop = new Population(this.populationSize, true, this.distances);
this.fittest = pop.getFittest();
this.tsp.setBestTrail(false, this.fittest.getBestTrail());
System.out.println("Initial distance: " + this.fittest.getDistance());
pop = this.evolvePopulation(pop);
for (int i = 0; i < this.iterations; i++) {
if (this.isInterrupt()) {
this.progressBar.setValue(0);
return;
}
this.progressBar.setValue(i + 1);
int percent = ((i + 1) * 100) / this.iterations;
this.progressBar.setString(Integer.toString(percent) + "%");
pop = this.evolvePopulation(pop);
if (pop.getFittest().getDistance() < this.fittest.getDistance()) {
this.fittest = pop.getFittest();
this.tsp.setBestTrail(false, this.fittest.getBestTrail());
this.logger.info(
String.format("New best length of %d found at %d", this.fittest.getDistance(), i));
}
}
this.logger.warn(this.progressBar.isMaximumSizeSet());
this.logger.info("Time complete");
this.logger.info(
String.format("Best trail found %s", Arrays.toString(this.fittest.getBestTrail())));
this.logger.info(String.format("Length of best trail found %d", this.fittest.getDistance()));
System.out.println("Finished");
System.out.println("Final distance: " + this.fittest.getDistance());
System.out.println("Solution");
System.out.println(this.fittest);
}
private Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.populationSize(), false, this.distances);
// Keep our best individual if elitism is enabled
int elitismOffset = 0;
if (elitism) {
newPopulation.saveTour(0, pop.getFittest());
elitismOffset = 1;
}
// Crossover population
// Loop over the new population's size and create individuals from
// Current population
for (int i = elitismOffset; i < newPopulation.populationSize(); i++) {
// Select parents
Tour parent1 = this.tournamentSelection(pop);
Tour parent2 = this.tournamentSelection(pop);
// Crossover parents
Tour child = this.crossover(parent1, parent2);
newPopulation.saveTour(i, child);
}
// Mutate the new population a bit to add some new genetic material
for (int i = elitismOffset; i < newPopulation.populationSize(); i++) {
this.mutate(newPopulation.getTour(i));
}
return newPopulation;
}
private Tour crossover(Tour parent1, Tour parent2) {
// Create new child tour
Tour child = new Tour(this.distances);
// Get start and end sub tour positions for parent1's tour
int startPos = (int) (Math.random() * parent1.tourSize());
int endPos = (int) (Math.random() * parent1.tourSize());
// Loop and add the sub tour from parent1 to our child
for (int i = 0; i < child.tourSize(); i++) {
// If our start position is less than the end position
if (startPos < endPos && i > startPos && i < endPos) {
child.setCity(i, parent1.getCity(i));
} // if our start position is larger
else if (startPos > endPos) {
if (!(i < startPos && i > endPos)) {
child.setCity(i, parent1.getCity(i));
}
}
}
// Loop through parent2's city tour
for (int i = 0; i < parent2.tourSize(); i++) {
// If child doesn't have the city add it
if (!child.containsCity(parent2.getCity(i))) {
// Loop to find a spare position in the child's tour
for (int k = 0; k < child.tourSize(); k++) {
// Spare position found, add city
if (child.getCity(k) == null) {
child.setCity(k, parent2.getCity(i));
break;
}
}
}
}
return child;
}
private void mutate(Tour tour) {
// Loop through tour cities
for (int tourPos1 = 0; tourPos1 < tour.tourSize(); tourPos1++) {
// Apply mutation rate
if (Math.random() < mutationRate) {
// Get a second random position in the tour
int tourPos2 = (int) (tour.tourSize() * Math.random());
// Get the cities at target position in tour
int city1 = tour.getCity(tourPos1);
int city2 = tour.getCity(tourPos2);
// Swap them around
tour.setCity(tourPos2, city1);
tour.setCity(tourPos1, city2);
}
}
}
private Tour tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(this.tournamentSize, false, this.distances);
// For each place in the tournament get a random candidate tour and
// add it
for (int i = 0; i < this.tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.populationSize());
tournament.saveTour(i, pop.getTour(randomId));
}
// Get the fittest tour
return tournament.getFittest();
}
@Override
public void setProperties(Problem problem) {
this.tsp = (TSP) problem;
this.progressBar = tsp.getProgressBar();
this.progressBar.setMinimum(0);
this.progressBar.setMaximum(super.getIteration());
this.progressBar.setValue(0);
}
private static String printDistance(int[][] distances) {
StringBuilder sb = new StringBuilder();
for (int[] distance : distances) {
sb.append("\n");
for (int j = 0; j < distances.length; j++) {
sb.append(String.format("%3s", distance[j]));
}
}
return sb.toString();
}
}
| 32.635 | 97 | 0.645932 |
8ccad4e480156cb41d72620421a7470a35bb3815 | 1,531 | package com.tbot.ruler.plugins.jwavez.switchmultilevel;
import com.rposcro.jwavez.core.commands.controlled.SwitchMultiLevelCommandBuilder;
import com.rposcro.jwavez.core.commands.controlled.ZWaveControlledCommand;
import com.rposcro.jwavez.core.exceptions.JWaveZException;
import com.rposcro.jwavez.core.model.NodeId;
import com.tbot.ruler.exceptions.MessageProcessingException;
import com.tbot.ruler.message.Message;
import com.tbot.ruler.message.payloads.BooleanUpdatePayload;
import com.tbot.ruler.things.Collector;
import com.tbot.ruler.things.CollectorId;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import java.util.function.BiConsumer;
@Getter
@Builder
public class SwitchMultilevelCollector implements Collector {
@NonNull private CollectorId id;
@NonNull private String name;
private String description;
@NonNull private byte switchDuration;
@NonNull private NodeId nodeId;
@NonNull private BiConsumer<NodeId, ZWaveControlledCommand> commandConsumer;
@Override
public void acceptMessage(Message message) {
try {
BooleanUpdatePayload payload = message.getPayload().ensureMessageType();
ZWaveControlledCommand command = new SwitchMultiLevelCommandBuilder()
.buildSetCommand((byte) (payload.isState() ? 255 : 0), switchDuration);
commandConsumer.accept(nodeId, command);
} catch(JWaveZException e) {
throw new MessageProcessingException("Command send failed!", e);
}
}
}
| 36.452381 | 87 | 0.7629 |
073c32f0a50fe330afb9b960a56cbf8f8da588eb | 8,157 | /*
* Copyright (C) 2008 Google 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 com.denvycom.gidigames;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Simple database access helper class. Defines the basic CRUD operations
* for the LEXIS Database
*
*/
public class DbAdapter {
//sCORETable
public static final String _ROWID = "OD";
public static final String KEY_GAME_TITLE= "title";
public static final String KEY_GAME_DIFFICULTY = "difficulty";
public static final String KEY_GAME_MOVES= "moves";
public static final String KEY_GAME_SUBTITLE= "subtitle";
public static final String KEY_GAME_TIME= "time";
public static final String COLUMN_NAME_MODIFICATION_DATE = "modified";
public static final String COLUMN_NAME_CREATE_DATE = "created";
private static final String DATABASE_NAME = "gidigames";
//Language Game Table
public static final String KEY_LANG_LANGUAGE= "lang_language";
public static final String KEY_LANG_ROOTWORD = "lang_rootword";
public static final String KEY_LANG_ENGLISHTRANS= "lang_englishtrans";
private static final String TABLE_SCORES = "scores";
private static final String TABLE_LEXIS = "lexis";
private static final int DATABASE_VERSION = 3 ;
private static final String TAG = "DbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
Long now = Long.valueOf(System.currentTimeMillis());
/**
* Database creation sql statement
*/
private static final String CREATE_SCORES_SQL ="CREATE TABLE " + TABLE_SCORES + " ("
+ _ROWID + " INTEGER PRIMARY KEY,"
+ KEY_GAME_TITLE + " TEXT,"
+ KEY_GAME_TIME + " INT,"
+ KEY_GAME_DIFFICULTY + " TEXT,"
+ KEY_GAME_MOVES + " INT,"
+ KEY_GAME_SUBTITLE + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ COLUMN_NAME_MODIFICATION_DATE + " INTEGER"
+ ");";
private static final String CREATE_LEXIS_SQL ="CREATE TABLE " + TABLE_LEXIS + " ("
+ _ROWID + " INTEGER PRIMARY KEY,"
+ KEY_LANG_ROOTWORD+ " TEXT,"
+ KEY_LANG_LANGUAGE + " TEXT,"
+ KEY_LANG_ENGLISHTRANS + " TEXT,"
+ KEY_GAME_DIFFICULTY + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ COLUMN_NAME_MODIFICATION_DATE + " INTEGER"
+ ");";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SCORES_SQL);
db.execSQL(CREATE_LEXIS_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LEXIS);
db.execSQL(CREATE_SCORES_SQL);
db.execSQL(CREATE_LEXIS_SQL);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx the Context within which to work
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* Open the data database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createScoreItem(String title, String subtitle, String difficulty, int moves, int time ) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GAME_TITLE, title);
initialValues.put(KEY_GAME_SUBTITLE, subtitle);
initialValues.put(KEY_GAME_DIFFICULTY, difficulty);
initialValues.put(KEY_GAME_MOVES, moves);
initialValues.put(KEY_GAME_TIME, time);
initialValues.put(COLUMN_NAME_CREATE_DATE, now);
initialValues.put(COLUMN_NAME_MODIFICATION_DATE, now);
return mDb.insert(TABLE_SCORES, null, initialValues);
}
/**
* Create a New Language Game Entry
*
* @param
* @return rowId or -1 if failed
*/
public long createLangGameWord(String rootword, String language, String englishtranslation, String difficulty ) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LANG_ROOTWORD, rootword);
initialValues.put(KEY_LANG_LANGUAGE, language);
initialValues.put(KEY_LANG_ENGLISHTRANS , englishtranslation);
initialValues.put(KEY_GAME_DIFFICULTY, difficulty);
return mDb.insert(TABLE_LEXIS, null, initialValues);
}
/**
* Fetch All Language Game Words
*
*/
public Cursor fetchLangGameWords() {
return mDb.query(TABLE_LEXIS, new String[] {_ROWID, KEY_LANG_ROOTWORD,
KEY_LANG_LANGUAGE, KEY_LANG_ENGLISHTRANS, KEY_GAME_DIFFICULTY}, null, null, null, null, null);
}
/**
* Fetch All Language Game Words
*
*/
public Cursor fetchWordSet(String thelang) {
return mDb.query(TABLE_LEXIS, new String[] {_ROWID, KEY_LANG_ROOTWORD,
KEY_LANG_LANGUAGE, KEY_LANG_ENGLISHTRANS, KEY_GAME_DIFFICULTY}, KEY_LANG_LANGUAGE + " = " + "'" + thelang + "'" , null, null, null, null);
}
public Cursor fetchAllWords() {
return mDb.query(TABLE_LEXIS, new String[] {_ROWID, KEY_LANG_ROOTWORD,
KEY_LANG_LANGUAGE, KEY_LANG_ENGLISHTRANS, KEY_GAME_DIFFICULTY}, null , null, null, null, null);
}
/**
* Fetch All Language Game Words
*
*/
public Cursor fetchLexisBest(String title, String language, String difficulty) {
return mDb.query(TABLE_SCORES, new String[] {_ROWID, KEY_GAME_TITLE,
KEY_GAME_DIFFICULTY, KEY_GAME_MOVES, KEY_GAME_TIME},
KEY_GAME_TITLE + "= '" + title + "'" + " " +
"AND " + KEY_GAME_DIFFICULTY + "= '" + difficulty + "'"
+ "AND " + KEY_GAME_SUBTITLE + "= '" + language + "'"
, null, null, null, KEY_GAME_MOVES + " ASC",null);
//mDb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
}
public Cursor fetchPuzzleBest(String title, String subtitle , String difficulty) {
return mDb.query(TABLE_SCORES, new String[] {_ROWID, KEY_GAME_TITLE,
KEY_GAME_DIFFICULTY, KEY_GAME_MOVES, KEY_GAME_TIME},
KEY_GAME_TITLE + "= '" + title + "'" + " AND " + KEY_GAME_DIFFICULTY + "= '" + difficulty + "'"
+ "AND " + KEY_GAME_SUBTITLE + "= '" + subtitle + "'"
, null, null, null, KEY_GAME_MOVES + " ASC",null);
//mDb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
}
/**
* Fetch All Language Game Words
*
*/
public Cursor fetchBestScorebyTime(String title, String difficulty) {
return mDb.query(TABLE_SCORES, new String[] {_ROWID, KEY_GAME_TITLE,
KEY_GAME_DIFFICULTY, KEY_GAME_MOVES, KEY_GAME_TIME},
KEY_GAME_TITLE + "= '" + title + "'" + " AND " + KEY_GAME_DIFFICULTY + "= '" + difficulty + "'"
, null, null, null, KEY_GAME_TIME,null);
//mDb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
}
}
| 31.133588 | 156 | 0.697438 |
689a97ddd2a81c18e1a853d2ad942b29d9f799c3 | 1,109 | package develop.odata.etl.repository.googleplaces;
import java.util.Date;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import develop.odata.etl.model.googleplaces.PlaceRecord;
import develop.odata.etl.model.googleplaces.PlaceCompositeKey;;
@RepositoryRestResource(collectionResourceRel = "place", path = "place")
public interface PlaceRecordRepository extends MongoRepository<PlaceRecord, PlaceCompositeKey> {
public PlaceRecord findById( PlaceCompositeKey id);
public List<PlaceRecord> updateTimeGreaterThanEqual(@Param("updateTime") Date d1 );
public List<PlaceRecord> updateTimeBetween(@Param("updateTime") Date d1 ,@Param("updateTime") Date d2 );
public List<PlaceRecord> findByIdAndUpdateTimeBetween( PlaceCompositeKey id , Date updateTime , Date d2 );
public List<PlaceRecord> findByIdAndUpdateTimeGreaterThanEqual( PlaceCompositeKey id , Date updateTime );
}
| 38.241379 | 113 | 0.788097 |
26e1ef3ac06c856663a7b8e5468c2f3a5427db8a | 663 | package com.lvsrobot.http.commands;
import com.lvsrobot.http.ExampleCommAdapter;
import org.opentcs.drivers.vehicle.AdapterCommand;
import org.opentcs.drivers.vehicle.VehicleCommAdapter;
public class SetPauseVehicle implements AdapterCommand {
private final boolean paused;
public SetPauseVehicle(boolean paused) {this.paused = paused;}
@Override
public void execute(VehicleCommAdapter adapter) {
if (!(adapter instanceof ExampleCommAdapter)) {
return;
}
ExampleCommAdapter exampleCommAdapter = (ExampleCommAdapter) adapter;
exampleCommAdapter.getProcessModel().setVehiclePaused(paused);
}
}
| 27.625 | 77 | 0.746606 |
f5d52cca2653282a8ad0fe8aeffe6a90c95e4fef | 6,502 | package com.orctom.jenkins.plugin.buildtimestamp;
import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Descriptor;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.util.ComboBoxModel;
import hudson.util.FormValidation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.orctom.jenkins.plugin.buildtimestamp.BuildTimestampPlugin.DEFAULT_PATTERN;
/**
* wrapper
* Created by hao on 12/16/15.
*/
public class BuildTimestampWrapper extends BuildWrapper {
@Extension
@Symbol("buildTimestamp")
public static final class DescriptorImpl extends BuildWrapperDescriptor {
private boolean enableBuildTimestamp = true;
private String timezone = TimeZone.getDefault().getID();
private String pattern = DEFAULT_PATTERN;
private Set<BuildTimestampExtraProperty> extraProperties = new HashSet<BuildTimestampExtraProperty>();
public DescriptorImpl() {
load();
}
@Override
public boolean isApplicable(AbstractProject<?, ?> abstractProject) {
return false;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
// reset optional authentication to default before data-binding
this.enableBuildTimestamp = false;
this.timezone = null;
this.pattern = null;
JSONObject data = formData.getJSONObject("enableBuildTimestamp");
if (isNullJSONObject(data)) {
enableBuildTimestamp = false;
} else {
enableBuildTimestamp = true;
timezone = data.getString("timezone");
pattern = data.getString("pattern");
Object extraPropertyValues = data.get("extraProperties");
if (null != extraPropertyValues) {
extraProperties = extractExtraProperties(extraPropertyValues);
} else {
extraProperties = new HashSet<BuildTimestampExtraProperty>();
}
}
save();
return super.configure(req, formData);
}
private boolean isNullJSONObject(JSONObject data) {
return null == data || data.isNullObject() || data.isEmpty();
}
private Set<BuildTimestampExtraProperty> extractExtraProperties(Object extraPropertyValues) {
Set<BuildTimestampExtraProperty> properties = new HashSet<BuildTimestampExtraProperty>();
if (extraPropertyValues instanceof JSONArray) {
JSONArray array = (JSONArray) extraPropertyValues;
for (Object item : array) {
addProperty(properties, item);
}
} else if (extraPropertyValues instanceof JSONObject) {
addProperty(properties, extraPropertyValues);
}
return properties;
}
private void addProperty(Set<BuildTimestampExtraProperty> properties, Object obj) {
JSONObject data = (JSONObject) obj;
String key = data.getString("key");
String value = data.getString("value");
String shiftExpression = data.getString("shiftExpression");
if (isVariableNameValid(key) && isPatternValid(value) && ShiftExpressionHelper.isShiftExpressionValid(shiftExpression)) {
properties.add(new BuildTimestampExtraProperty(key, value, shiftExpression));
}
}
private boolean isVariableNameValid(String name) {
return null != name && 0 != name.trim().length() && !name.matches(".*\\W.*");
}
private boolean isPatternValid(String pattern) {
if (null == pattern || 0 == pattern.trim().length()) {
return false;
}
try {
new SimpleDateFormat(pattern);
return true;
} catch (Exception e) {
return false;
}
}
private String getConfiguredTimezone(String timezoneParam) {
if (null == timezoneParam || 0 == timezoneParam.trim().length()) {
return TimeZone.getDefault().getID();
}
return TimeZone.getTimeZone(timezoneParam).getID();
}
public FormValidation doCheckPattern(@QueryParameter("pattern") String patternParam,
@QueryParameter("timezone") String timezoneParam) {
String configuredTimezone = getConfiguredTimezone(timezoneParam);
String patternStr = DEFAULT_PATTERN;
if (null != patternParam && 0 != patternParam.trim().length()) {
patternStr = patternParam.trim();
}
try {
SimpleDateFormat df = new SimpleDateFormat(patternStr);
df.setTimeZone(TimeZone.getTimeZone(configuredTimezone));
return FormValidation.ok("Using timezone: %s; Sample timestamp: %s", configuredTimezone, df.format(new Date()));
} catch (Exception e) {
return FormValidation.error("Invalid pattern");
}
}
public FormValidation doCheckKey(@QueryParameter("key") String key) {
if (isVariableNameValid(key)) {
return FormValidation.ok();
}
return FormValidation.error("Invalid variable name");
}
public FormValidation doCheckValue(@QueryParameter("value") String value) {
if (isPatternValid(value)) {
return FormValidation.ok();
}
return FormValidation.error("Invalid pattern");
}
public FormValidation doCheckShiftExpression(@QueryParameter("shiftExpression") String shiftExpression) {
if (ShiftExpressionHelper.isShiftExpressionValid(shiftExpression)) {
return FormValidation.ok();
}
return FormValidation.error("Invalid time shift expression");
}
public ComboBoxModel doFillTimezoneItems() {
ComboBoxModel items = new ComboBoxModel();
Collections.addAll(items, TimeZone.getAvailableIDs());
return items;
}
public boolean isEnableBuildTimestamp() {
return enableBuildTimestamp;
}
@DataBoundSetter
public void setEnableBuildTimestamp(boolean enableBuildTimestamp) {
this.enableBuildTimestamp = enableBuildTimestamp;
}
public String getPattern() {
return pattern;
}
@DataBoundSetter
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getTimezone() {
return timezone;
}
@DataBoundSetter
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public Set<BuildTimestampExtraProperty> getExtraProperties() {
return extraProperties;
}
@DataBoundSetter
public void setExtraProperties(Set<BuildTimestampExtraProperty> extraProperties) {
this.extraProperties = extraProperties;
}
}
}
| 30.24186 | 124 | 0.724392 |
4952aa3f2bdaa0b48cdeb4ef9a5af9f0f1588fbe | 13,657 | /*
* Copyright 2008-2016 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.opencl.wrapper;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingQueue;
import org.jocl.CL;
import org.jocl.Pointer;
import org.jocl.Sizeof;
import org.jocl.cl_command_queue;
import org.jocl.cl_context;
import org.jocl.cl_event;
import org.jocl.cl_mem;
public abstract class DeviceMemory {
private final cl_context context;
private final cl_command_queue queue;
private long memoryFree;
private final HashMap<String, MemoryRegister> inMemoryValues = new HashMap<>();
private final LinkedBlockingQueue<MemoryRequest> requestQueue = new LinkedBlockingQueue<>();
public DeviceMemory(long memoryFree, cl_context context, cl_command_queue queue) {
this.memoryFree = memoryFree;
this.context = context;
this.queue = queue;
}
public void setOnMemory(Device.OpenCLMemoryPrepare listener, String dataId, Object object, Class<?> objectClass, int size, boolean isRead, boolean canWrite) {
MemoryRegister register = inMemoryValues.get(dataId);
if (register == null) {
int byteSize = baseSize(objectClass) * size;
if (memoryFree < byteSize) {
if (!releaseMemory(byteSize)) {
MemoryRequest mr = new MemoryRequest(listener, dataId, object, objectClass, size, isRead, canWrite);
requestQueue.add(mr);
//Operation will be performed when there's space enough
return;
}
}
register = createRegister(dataId, byteSize, canWrite);
if (isRead) {
register.writeValue(objectClass, size, object);
}
inMemoryValues.put(dataId, register);
memoryFree -= register.getSize();
}
pendingAccess(register);
listener.completed(register);
}
public void replaceCreatorEvent(Object parValue, cl_event overridingEvent) {
MemoryRegister register = (MemoryRegister) parValue;
register.replaceLoadingEvent(overridingEvent);
}
public void retrieveValue(Object parValue, Object target, boolean wasWritten) {
MemoryRegister register = (MemoryRegister) parValue;
if (wasWritten) {
int size = 1;
Class<?> targetClass = target.getClass();
Object sizeObject = target;
while (targetClass.isArray()) {
size *= Array.getLength(sizeObject);
sizeObject = Array.get(sizeObject, 0);
targetClass = targetClass.getComponentType();
}
register.retrieveValue(target, targetClass, size);
}
performedAccess(register);
}
protected abstract MemoryRegister createRegister(String dataId, int size, boolean canWrite);
protected abstract void pendingAccess(MemoryRegister reg);
protected abstract void performedAccess(MemoryRegister reg);
private boolean releaseMemory(long space) {
MemoryRegister register;
while (space - memoryFree > 0) {
register = this.releaseRegister(space - memoryFree);
if (register == null) {
return false;
}
inMemoryValues.remove(register.getDataId());
memoryFree += register.getSize();
register.destroy();
}
return true;
}
protected abstract MemoryRegister releaseRegister(long missingSpace);
private static class MemoryRequest {
private final Device.OpenCLMemoryPrepare listener;
private final String valueRenaming;
private final Object object;
private final Class<?> objectClass;
private final int size;
private final boolean copyInput;
private final boolean canWrite;
public MemoryRequest(Device.OpenCLMemoryPrepare listener, String valueRenaming, Object object, Class<?> objectClass, int size, boolean copyInput, boolean canWrite) {
this.listener = listener;
this.valueRenaming = valueRenaming;
this.object = object;
this.objectClass = objectClass;
this.size = size;
this.copyInput = copyInput;
this.canWrite = canWrite;
}
public Device.OpenCLMemoryPrepare getListener() {
return listener;
}
public Object getObject() {
return object;
}
public Class<?> getObjectClass() {
return objectClass;
}
public int getSize() {
return size;
}
public String getValueRenaming() {
return valueRenaming;
}
public boolean isCanWrite() {
return canWrite;
}
public boolean isCopyInput() {
return copyInput;
}
}
public abstract class MemoryRegister {
private final cl_mem data;
private final long size;
private cl_event firstLoadingEvent;
private cl_event loadingEvent;
private final String dataId;
public MemoryRegister(String dataId, int size, boolean canWrite) {
this.size = size;
int[] errCode = new int[1];
this.data = CL.clCreateBuffer(context, canWrite ? CL.CL_MEM_READ_WRITE : CL.CL_MEM_READ_ONLY, size, null, errCode);
this.dataId = dataId;
}
public final String getDataId() {
return dataId;
}
public final long getSize() {
return size;
}
public final cl_mem getBuffer() {
return data;
}
public final void writeValue(Class<?> objectClass, int size, Object object) {
int[] errout = new int[1];
Object seq;
if (object.getClass().getComponentType().isArray()) {
seq = Array.newInstance(objectClass, size);
flatten(object, seq, 0);
} else {
seq = object;
}
cl_event event = new cl_event();
if (objectClass == boolean.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_char * size, Pointer.to((char[]) seq), 0, null, event);
}
if (objectClass == byte.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_char * size, Pointer.to((byte[]) seq), 0, null, event);
}
if (objectClass == char.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_short * size, Pointer.to((char[]) seq), 0, null, event);
}
if (objectClass == short.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_short * size, Pointer.to((short[]) seq), 0, null, event);
}
if (objectClass == int.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_int * size, Pointer.to((int[]) seq), 0, null, event);
}
if (objectClass == long.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_long * size, Pointer.to((long[]) seq), 0, null, event);
}
if (objectClass == float.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_float * size, Pointer.to((float[]) seq), 0, null, event);
}
if (objectClass == double.class) {
CL.clEnqueueWriteBuffer(queue, data, CL.CL_FALSE, 0, Sizeof.cl_double * size, Pointer.to((double[]) seq), 0, null, event);
}
setLoadingEvent(event);
CL.clFlush(queue);
}
public final void replaceLoadingEvent(cl_event overridingEvent) {
this.firstLoadingEvent = this.loadingEvent;
this.loadingEvent = overridingEvent;
}
public final void retrieveValue(Object target, Class<?> targetClass, int size) {
CL.clFlush(queue);
Object flatResult;
if (target.getClass().getComponentType().isArray()) {
flatResult = Array.newInstance(targetClass, size);
} else {
flatResult = target;
}
if (targetClass == boolean.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_char, Pointer.to((char[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == byte.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_char, Pointer.to((byte[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == char.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_short, Pointer.to((char[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == short.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_short, Pointer.to((short[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == int.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_int, Pointer.to((int[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == long.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_long, Pointer.to((long[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == float.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_float, Pointer.to((float[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
if (targetClass == double.class) {
CL.clEnqueueReadBuffer(queue, data, CL.CL_TRUE, 0, size * Sizeof.cl_double, Pointer.to((double[]) flatResult), 1, new cl_event[]{loadingEvent}, null);
}
CL.clFlush(queue);
if (target.getClass().getComponentType().isArray()) {
expand(flatResult, target, 0);
}
}
public final cl_event getLoadingEvent() {
return loadingEvent;
}
public final void setLoadingEvent(cl_event event) {
this.loadingEvent = event;
}
public final void destroy() {
if (firstLoadingEvent != null) {
CL.clReleaseEvent(firstLoadingEvent);
}
CL.clReleaseEvent(loadingEvent);
CL.clReleaseMemObject(data);
}
@Override
public String toString() {
return "Data " + dataId + " (" + data + ") created by " + loadingEvent + " fills " + size + " bytes ";
}
}
private static int baseSize(Class aClass) {
if (aClass == boolean.class) {
return Sizeof.cl_char;
}
if (aClass == byte.class) {
return Sizeof.cl_char;
}
if (aClass == char.class) {
return Sizeof.cl_char;
}
if (aClass == short.class) {
return Sizeof.cl_short;
}
if (aClass == int.class) {
return Sizeof.cl_int;
}
if (aClass == long.class) {
return Sizeof.cl_long;
}
if (aClass == float.class) {
return Sizeof.cl_float;
}
if (aClass == double.class) {
return Sizeof.cl_double;
}
return Sizeof.POINTER;
}
private static int expand(Object seq, Object o, int offset) {
int read;
Class<?> oClass = o.getClass();
if (oClass.isArray()) {
if (oClass.getComponentType().isArray()) {
read = 0;
for (int componentId = 0; componentId < Array.getLength(o); componentId++) {
read += expand(seq, Array.get(o, componentId), offset + read);
}
} else {
System.arraycopy(seq, offset, o, 0, Array.getLength(o));
read = Array.getLength(o);
}
} else {
Array.set(o, offset, seq);
read = 1;
}
return read;
}
private static int flatten(Object o, Object seq, int offset) {
int written;
Class<?> oClass = o.getClass();
if (oClass.isArray()) {
if (oClass.getComponentType().isArray()) {
written = 0;
for (int componentId = 0; componentId < Array.getLength(o); componentId++) {
written += flatten(Array.get(o, componentId), seq, offset + written);
}
} else {
System.arraycopy(o, 0, seq, offset, Array.getLength(o));
written = Array.getLength(o);
}
} else {
Array.set(seq, offset, o);
written = 1;
}
return written;
}
}
| 37.936111 | 173 | 0.576701 |
5d0946e0172b3aed6c90429349e918e86b8ea0f7 | 489 | package com.example.zju.markmark;
import android.graphics.PointF;
/**
* Created by 本 on 2017-11-27.
*/
public class Bang {
private PointF mOrigin;
private PointF mCurrent;
public Bang(PointF origin) {
mOrigin = origin;
mCurrent = origin;
}
public PointF getCurrent() {
return mCurrent;
}
public void setCurrent(PointF current) {
mCurrent = current;
}
public PointF getOrigin() {
return mOrigin;
}
} | 15.774194 | 44 | 0.609407 |
b9deb13582b063da9fec7d06110a08b57c6b1048 | 809 | package ru.greenpix.civilization.buildings.wonders;
import org.bukkit.Location;
import ru.greenpix.civilization.buildings.Structure;
import ru.greenpix.civilization.buildings.Style;
import ru.greenpix.civilization.buildings.common.Cottage;
import ru.greenpix.civilization.objects.Town;
import ru.greenpix.mysql.api.Result;
public class TheGreatPyramid extends Wonder {
public TheGreatPyramid(Result result, Structure str) {
super(result, str);
}
public TheGreatPyramid(Town town, Location location, Style style) {
super(town, location, style);
}
@Override
public double getValue(String type) {
if(type == MONEY) {
return getStructure().getInt("buffs.income-cottage") * getTown().getBuildings(Cottage.class).size()
- getStructure().getTax();
}
return super.getValue(type);
}
}
| 26.966667 | 102 | 0.76267 |
64bc0a746d139914e8ec1289f4a011ce90a4222c | 803 | package reposense.git;
import java.nio.file.Paths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import reposense.git.exception.GitBranchException;
import reposense.template.GitTestTemplate;
public class GitRevParseTest extends GitTestTemplate {
@Test
public void assertBranchExists_withExistingBranch_success() throws Exception {
config.setBranch("master");
GitRevParse.assertBranchExists(config, Paths.get(config.getRepoRoot()));
}
@Test
public void assertBranchExists_withNonExistentBranch_throwsGitBranchException() {
config.setBranch("nonExistentBranch");
Assertions.assertThrows(GitBranchException.class, () -> GitRevParse.assertBranchExists(config,
Paths.get(config.getRepoRoot())));
}
}
| 30.884615 | 102 | 0.753425 |
ee0137064c768b398aedbb81857fb59e45cf50e7 | 3,196 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.components.composite;
import java.util.Iterator;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUIWithLog;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.Composite;
import com.vaadin.ui.HasComponents;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
@Widgetset("com.vaadin.DefaultWidgetSet")
public class CompositeChainUI extends AbstractTestUIWithLog {
private Label innermostComponent;
private Composite innerComposite;
private Composite outerComposite;
private VerticalLayout container;
private HorizontalLayout layout;
@Override
protected void setup(VaadinRequest request) {
createComposite();
layout = new HorizontalLayout(outerComposite);
container = new VerticalLayout(layout);
addComponent(container);
Button updateCaption = new Button("Update caption");
updateCaption.addClickListener(event -> innermostComponent
.setCaption(innermostComponent.getCaption() + " - updated"));
addComponent(updateCaption);
Button replaceWithAnotherComposite = new Button(
"Replace with another Composite", event -> {
Composite oldOuter = outerComposite;
createComposite();
layout.replaceComponent(oldOuter, outerComposite);
});
addComponent(replaceWithAnotherComposite);
logHierarchy();
}
private void createComposite() {
innermostComponent = new Label("Label text");
innermostComponent.setCaption("Label caption");
innermostComponent.setId("innermost");
innerComposite = new Composite(innermostComponent);
outerComposite = new Composite(innerComposite);
}
private void logHierarchy() {
String msg = "Hierarchy: ";
if (container != null) {
msg += getHierarchy(container);
}
log(msg);
}
private static String getHierarchy(Component component) {
String msg = component.getClass().getSimpleName();
if (component instanceof HasComponents) {
Iterator<Component> it = ((HasComponents) component).iterator();
if (it.hasNext()) {
Component content = it.next();
if (content != null) {
msg += " -> " + getHierarchy(content);
}
}
}
return msg;
}
}
| 33.642105 | 80 | 0.668023 |
d98f861bc9aa8f489b6a579c71daa02e4dcabbc4 | 3,421 | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. 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 org.cloudifysource.shell.exceptions;
import org.apache.commons.lang.StringUtils;
/**
* @author noak
* @since 2.0.0
*
* Extends {@link CLIException}, includes more details to support
* validation errors.
*/
public class CLIValidationException extends CLIException {
private static final long serialVersionUID = 4004719704284906595L;
private final int exitCode;
private final String reasonCode;
private final String verboseData;
private final Object[] args;
/**
* Constructor.
*
* @param cause
* The Throwable that caused this exception to be thrown.
* @param reasonCode
* A reason code, by which a formatted message can be retrieved
* from the message bundle
* @param exitCode
* The JVM will exit with the given exit code
* @param args
* Optional arguments to embed in the formatted message
*/
public CLIValidationException(final Throwable cause, final int exitCode, final String reasonCode,
final Object... args) {
super("reasonCode: " + reasonCode, cause);
this.exitCode = exitCode;
this.args = args;
this.reasonCode = reasonCode;
this.verboseData = null;
}
/**
* Constructor.
*
* @param exitCode
* The JVM will exit with the given exit code
* @param reasonCode
* A reason code, by which a formatted message can be retrieved
* from the message bundle
* @param args
* Optional arguments to embed in the formatted message
*/
public CLIValidationException(final int exitCode, final String reasonCode, final Object... args) {
super("reasonCode: " + reasonCode);
this.exitCode = exitCode;
this.reasonCode = reasonCode;
this.args = args;
this.verboseData = null;
}
/**
* Gets the exit code.
*
* @return The exit code related to this validation exception
*/
public int getExitCode() {
return exitCode;
}
/**
* Gets the reason code.
*
* @return A reason code, by which a formatted message can be retrieved from
* the message bundle
*/
public String getReasonCode() {
return reasonCode;
}
/**
* Gets the arguments that complete the reason-code based message.
*
* @return An array of arguments
*/
public Object[] getArgs() {
return args;
}
/**
* Gets the verbose data.
* @return verbose data
*/
public String getVerboseData() {
return verboseData;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "CLIValidationException, reason code: " + reasonCode + ", message arguments: "
+ StringUtils.join(args, ", ");
}
}
| 27.368 | 99 | 0.646595 |
015c8edd1db1bc0a3bf495670ed434828f1129cf | 8,806 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: test.proto
package com.example.mentor.proto;
/**
* <pre>
* The request message containing the user's name.
* </pre>
*
* Protobuf type {@code GrpcService.GetPictureRequest}
*/
public final class GetPictureRequest extends
com.google.protobuf.GeneratedMessageLite<
GetPictureRequest, GetPictureRequest.Builder> implements
// @@protoc_insertion_point(message_implements:GrpcService.GetPictureRequest)
GetPictureRequestOrBuilder {
private GetPictureRequest() {
}
public static final int FROM_FIELD_NUMBER = 1;
private int from_;
/**
* <code>optional uint32 from = 1;</code>
*/
public int getFrom() {
return from_;
}
/**
* <code>optional uint32 from = 1;</code>
*/
private void setFrom(int value) {
from_ = value;
}
/**
* <code>optional uint32 from = 1;</code>
*/
private void clearFrom() {
from_ = 0;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (from_ != 0) {
output.writeUInt32(1, from_);
}
}
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (from_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, from_);
}
memoizedSerializedSize = size;
return size;
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static com.example.mentor.proto.GetPictureRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static com.example.mentor.proto.GetPictureRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static com.example.mentor.proto.GetPictureRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.example.mentor.proto.GetPictureRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
/**
* <pre>
* The request message containing the user's name.
* </pre>
*
* Protobuf type {@code GrpcService.GetPictureRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
com.example.mentor.proto.GetPictureRequest, Builder> implements
// @@protoc_insertion_point(builder_implements:GrpcService.GetPictureRequest)
com.example.mentor.proto.GetPictureRequestOrBuilder {
// Construct using com.example.mentor.proto.GetPictureRequest.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <code>optional uint32 from = 1;</code>
*/
public int getFrom() {
return instance.getFrom();
}
/**
* <code>optional uint32 from = 1;</code>
*/
public Builder setFrom(int value) {
copyOnWrite();
instance.setFrom(value);
return this;
}
/**
* <code>optional uint32 from = 1;</code>
*/
public Builder clearFrom() {
copyOnWrite();
instance.clearFrom();
return this;
}
// @@protoc_insertion_point(builder_scope:GrpcService.GetPictureRequest)
}
protected final Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
Object arg0, Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new com.example.mentor.proto.GetPictureRequest();
}
case IS_INITIALIZED: {
return DEFAULT_INSTANCE;
}
case MAKE_IMMUTABLE: {
return null;
}
case NEW_BUILDER: {
return new Builder();
}
case VISIT: {
Visitor visitor = (Visitor) arg0;
com.example.mentor.proto.GetPictureRequest other = (com.example.mentor.proto.GetPictureRequest) arg1;
from_ = visitor.visitInt(from_ != 0, from_,
other.from_ != 0, other.from_);
if (visitor == com.google.protobuf.GeneratedMessageLite.MergeFromVisitor
.INSTANCE) {
}
return this;
}
case MERGE_FROM_STREAM: {
com.google.protobuf.CodedInputStream input =
(com.google.protobuf.CodedInputStream) arg0;
com.google.protobuf.ExtensionRegistryLite extensionRegistry =
(com.google.protobuf.ExtensionRegistryLite) arg1;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 8: {
from_ = input.readUInt32();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw new RuntimeException(e.setUnfinishedMessage(this));
} catch (java.io.IOException e) {
throw new RuntimeException(
new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this));
} finally {
}
}
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
if (PARSER == null) { synchronized (com.example.mentor.proto.GetPictureRequest.class) {
if (PARSER == null) {
PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);
}
}
}
return PARSER;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:GrpcService.GetPictureRequest)
private static final com.example.mentor.proto.GetPictureRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new GetPictureRequest();
DEFAULT_INSTANCE.makeImmutable();
}
public static com.example.mentor.proto.GetPictureRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<GetPictureRequest> PARSER;
public static com.google.protobuf.Parser<GetPictureRequest> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
| 32.614815 | 109 | 0.671701 |
b3fdf7795bb016127faf004d71fe19b2e0a62594 | 4,926 | // Copyright 2017 The Nomulus Authors. 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 google.registry.model.tmch;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.collect.ImmutableMap;
import com.googlecode.objectify.Key;
import google.registry.model.tmch.ClaimsListShard.ClaimsListRevision;
import google.registry.model.tmch.ClaimsListShard.UnshardedSaveException;
import google.registry.testing.AppEngineExtension;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ClaimsListShard}. */
public class ClaimsListShardTest {
@RegisterExtension
public final AppEngineExtension appEngine =
AppEngineExtension.builder().withDatastoreAndCloudSql().build();
private final int shardSize = 10;
@Test
void test_unshardedSaveFails() {
assertThrows(
UnshardedSaveException.class,
() ->
tm()
.transact(
() -> {
ClaimsListShard claimsList =
ClaimsListShard.create(
tm().getTransactionTime(), ImmutableMap.of("a", "b"));
claimsList.id = 1; // Without an id this won't save anyways.
claimsList.parent = ClaimsListRevision.createKey();
ofy().saveWithoutBackup().entity(claimsList).now();
}));
}
@Test
void testGet_safelyLoadsEmptyClaimsList_whenNoShardsExist() {
assertThat(ClaimsListShard.get().labelsToKeys).isEmpty();
assertThat(ClaimsListShard.get().creationTime).isEqualTo(START_OF_TIME);
}
@Test
void test_savesAndGets_withSharding() {
// Create a ClaimsList that will need 4 shards to save.
Map<String, String> labelsToKeys = new HashMap<>();
for (int i = 0; i <= shardSize * 3; i++) {
labelsToKeys.put(Integer.toString(i), Integer.toString(i));
}
DateTime now = DateTime.now(UTC);
// Save it with sharding, and make sure that reloading it works.
ClaimsListShard unsharded = ClaimsListShard.create(now, ImmutableMap.copyOf(labelsToKeys));
unsharded.saveToDatastore(shardSize);
assertThat(ClaimsListShard.get().labelsToKeys).isEqualTo(unsharded.labelsToKeys);
List<ClaimsListShard> shards1 = ofy().load().type(ClaimsListShard.class).list();
assertThat(shards1).hasSize(4);
assertThat(ClaimsListShard.get().getClaimKey("1")).hasValue("1");
assertThat(ClaimsListShard.get().getClaimKey("a")).isEmpty();
assertThat(ClaimsListShard.getCurrentRevision()).isEqualTo(shards1.get(0).parent);
// Create a smaller ClaimsList that will need only 2 shards to save.
labelsToKeys = new HashMap<>();
for (int i = 0; i <= shardSize; i++) {
labelsToKeys.put(Integer.toString(i), Integer.toString(i));
}
unsharded = ClaimsListShard.create(now.plusDays(1), ImmutableMap.copyOf(labelsToKeys));
unsharded.saveToDatastore(shardSize);
ofy().clearSessionCache();
assertThat(ClaimsListShard.get().labelsToKeys).hasSize(unsharded.labelsToKeys.size());
assertThat(ClaimsListShard.get().labelsToKeys).isEqualTo(unsharded.labelsToKeys);
List<ClaimsListShard> shards2 = ofy().load().type(ClaimsListShard.class).list();
assertThat(shards2).hasSize(2);
// Expect that the old revision is deleted.
assertThat(ClaimsListShard.getCurrentRevision()).isEqualTo(shards2.get(0).parent);
}
/**
* Returns a created claims list shard with the specified parent key for testing purposes only.
*/
public static ClaimsListShard createTestClaimsListShard(
DateTime creationTime,
ImmutableMap<String, String> labelsToKeys,
Key<ClaimsListRevision> revision) {
ClaimsListShard claimsList = ClaimsListShard.create(creationTime, labelsToKeys);
claimsList.isShard = true;
claimsList.parent = revision;
return claimsList;
}
}
| 42.102564 | 97 | 0.72026 |
935e8cc09984db0be2307f346e9be2dc81555941 | 288 | package fr.pizzeria.admin.metier;
public enum PizzaEventType {
CREATE("Create"), UPDATE("Update"), DELETE("Delete");
private String name = "";
/**
* @param name
*/
PizzaEventType(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
| 14.4 | 54 | 0.652778 |
7087cbd9a5a8eb083d81b4d56d35b3944d942282 | 198 | package solid.openclosed.after;
import java.math.BigDecimal;
public class ContractorEmployee implements Employee {
@Override
public BigDecimal getSalary() {
return null;
}
}
| 15.230769 | 53 | 0.712121 |
919f85f01d8d318017a07caf4e77fe38e37110fd | 11,814 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.client.graph.hlrc;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.client.graph.Connection;
import org.elasticsearch.client.graph.GraphExploreResponse;
import org.elasticsearch.client.graph.Vertex;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.client.AbstractHlrcXContentTestCase;
import org.elasticsearch.protocol.xpack.graph.Connection.ConnectionId;
import org.elasticsearch.test.AbstractXContentTestCase;
import org.junit.Assert;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static org.hamcrest.Matchers.equalTo;
public class GraphExploreResponseTests extends AbstractHlrcXContentTestCase<
org.elasticsearch.protocol.xpack.graph.GraphExploreResponse,
GraphExploreResponse> {
static final Function<Vertex.VertexId, org.elasticsearch.protocol.xpack.graph.Vertex.VertexId> VERTEX_ID_FUNCTION =
vId -> new org.elasticsearch.protocol.xpack.graph.Vertex.VertexId(vId.getField(), vId.getTerm());
static final Function<Vertex, org.elasticsearch.protocol.xpack.graph.Vertex> VERTEX_FUNCTION =
v -> new org.elasticsearch.protocol.xpack.graph.Vertex(v.getField(), v.getTerm(), v.getWeight(),
v.getHopDepth(), v.getBg(), v.getFg());
@Override
public GraphExploreResponse doHlrcParseInstance(XContentParser parser) throws IOException {
return GraphExploreResponse.fromXContent(parser);
}
@Override
public org.elasticsearch.protocol.xpack.graph.GraphExploreResponse convertHlrcToInternal(GraphExploreResponse instance) {
return new org.elasticsearch.protocol.xpack.graph.GraphExploreResponse(instance.getTookInMillis(), instance.isTimedOut(),
instance.getShardFailures(), convertVertices(instance), convertConnections(instance), instance.isReturnDetailedInfo());
}
public Map<org.elasticsearch.protocol.xpack.graph.Vertex.VertexId, org.elasticsearch.protocol.xpack.graph.Vertex> convertVertices(
GraphExploreResponse instance) {
final Collection<Vertex.VertexId> vertexIds = instance.getVertexIds();
final Map<org.elasticsearch.protocol.xpack.graph.Vertex.VertexId, org.elasticsearch.protocol.xpack.graph.Vertex> vertexMap =
new LinkedHashMap<>(vertexIds.size());
for (Vertex.VertexId vertexId : vertexIds) {
final Vertex vertex = instance.getVertex(vertexId);
vertexMap.put(VERTEX_ID_FUNCTION.apply(vertexId), VERTEX_FUNCTION.apply(vertex));
}
return vertexMap;
}
public Map<ConnectionId, org.elasticsearch.protocol.xpack.graph.Connection> convertConnections(GraphExploreResponse instance) {
final Collection<Connection.ConnectionId> connectionIds = instance.getConnectionIds();
final Map<ConnectionId,org.elasticsearch.protocol.xpack.graph.Connection> connectionMap= new LinkedHashMap<>(connectionIds.size());
for (Connection.ConnectionId connectionId : connectionIds) {
final Connection connection = instance.getConnection(connectionId);
final ConnectionId connectionId1 = new ConnectionId(VERTEX_ID_FUNCTION.apply(connectionId.getSource()),
VERTEX_ID_FUNCTION.apply(connectionId.getTarget()));
final org.elasticsearch.protocol.xpack.graph.Connection connection1 = new org.elasticsearch.protocol.xpack.graph.Connection(
VERTEX_FUNCTION.apply(connection.getFrom()), VERTEX_FUNCTION.apply(connection.getTo()), connection.getWeight(),
connection.getDocCount());
connectionMap.put(connectionId1, connection1);
}
return connectionMap;
}
@Override
protected org.elasticsearch.protocol.xpack.graph.GraphExploreResponse createTestInstance() {
return createInstance(0);
}
private static org.elasticsearch.protocol.xpack.graph.GraphExploreResponse createInstance(int numFailures) {
int numItems = randomIntBetween(4, 128);
boolean timedOut = randomBoolean();
boolean showDetails = randomBoolean();
long overallTookInMillis = randomNonNegativeLong();
Map<org.elasticsearch.protocol.xpack.graph.Vertex.VertexId, org.elasticsearch.protocol.xpack.graph.Vertex> vertices =
new HashMap<>();
Map<ConnectionId,
org.elasticsearch.protocol.xpack.graph.Connection> connections = new HashMap<>();
ShardOperationFailedException [] failures = new ShardOperationFailedException [numFailures];
for (int i = 0; i < failures.length; i++) {
failures[i] = new ShardSearchFailure(new ElasticsearchException("an error"));
}
//Create random set of vertices
for (int i = 0; i < numItems; i++) {
org.elasticsearch.protocol.xpack.graph.Vertex v = new org.elasticsearch.protocol.xpack.graph.Vertex("field1",
randomAlphaOfLength(5), randomDouble(), 0,
showDetails? randomIntBetween(100, 200):0,
showDetails? randomIntBetween(1, 100):0);
vertices.put(v.getId(), v);
}
//Wire up half the vertices randomly
org.elasticsearch.protocol.xpack.graph.Vertex[] vs =
vertices.values().toArray(new org.elasticsearch.protocol.xpack.graph.Vertex[vertices.size()]);
for (int i = 0; i < numItems/2; i++) {
org.elasticsearch.protocol.xpack.graph.Vertex v1 = vs[randomIntBetween(0, vs.length-1)];
org.elasticsearch.protocol.xpack.graph.Vertex v2 = vs[randomIntBetween(0, vs.length-1)];
if(v1 != v2) {
org.elasticsearch.protocol.xpack.graph.Connection conn = new org.elasticsearch.protocol.xpack.graph.Connection(v1, v2,
randomDouble(), randomLongBetween(1, 10));
connections.put(conn.getId(), conn);
}
}
return new org.elasticsearch.protocol.xpack.graph.GraphExploreResponse(overallTookInMillis, timedOut, failures,
vertices, connections, showDetails);
}
private static org.elasticsearch.protocol.xpack.graph.GraphExploreResponse createTestInstanceWithFailures() {
return createInstance(randomIntBetween(1, 128));
}
@Override
protected org.elasticsearch.protocol.xpack.graph.GraphExploreResponse doParseInstance(XContentParser parser) throws IOException {
return org.elasticsearch.protocol.xpack.graph.GraphExploreResponse.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
@Override
protected boolean assertToXContentEquivalence() {
return false;
}
@Override
protected String[] getShuffleFieldsExceptions() {
return new String[]{"vertices", "connections"};
}
protected Predicate<String> getRandomFieldsExcludeFilterWhenResultHasErrors() {
return field -> field.startsWith("responses");
}
@Override
protected void assertEqualInstances(org.elasticsearch.protocol.xpack.graph.GraphExploreResponse expectedInstance,
org.elasticsearch.protocol.xpack.graph.GraphExploreResponse newInstance) {
Assert.assertThat(newInstance.getTook(), equalTo(expectedInstance.getTook()));
Assert.assertThat(newInstance.isTimedOut(), equalTo(expectedInstance.isTimedOut()));
Comparator<org.elasticsearch.protocol.xpack.graph.Connection> connComparator =
Comparator.comparing(o -> o.getId().toString());
org.elasticsearch.protocol.xpack.graph.Connection[] newConns =
newInstance.getConnections().toArray(new org.elasticsearch.protocol.xpack.graph.Connection[0]);
org.elasticsearch.protocol.xpack.graph.Connection[] expectedConns =
expectedInstance.getConnections().toArray(new org.elasticsearch.protocol.xpack.graph.Connection[0]);
Arrays.sort(newConns, connComparator);
Arrays.sort(expectedConns, connComparator);
Assert.assertArrayEquals(expectedConns, newConns);
//Sort the vertices lists before equality test (map insertion sequences can cause order differences)
Comparator<org.elasticsearch.protocol.xpack.graph.Vertex> comparator = Comparator.comparing(o -> o.getId().toString());
org.elasticsearch.protocol.xpack.graph.Vertex[] newVertices =
newInstance.getVertices().toArray(new org.elasticsearch.protocol.xpack.graph.Vertex[0]);
org.elasticsearch.protocol.xpack.graph.Vertex[] expectedVertices =
expectedInstance.getVertices().toArray(new org.elasticsearch.protocol.xpack.graph.Vertex[0]);
Arrays.sort(newVertices, comparator);
Arrays.sort(expectedVertices, comparator);
Assert.assertArrayEquals(expectedVertices, newVertices);
ShardOperationFailedException[] newFailures = newInstance.getShardFailures();
ShardOperationFailedException[] expectedFailures = expectedInstance.getShardFailures();
Assert.assertEquals(expectedFailures.length, newFailures.length);
}
/**
* Test parsing {@link org.elasticsearch.protocol.xpack.graph.GraphExploreResponse} with inner failures as they
* don't support asserting on xcontent equivalence, given exceptions are not parsed back as the same original class.
* We run the usual {@link AbstractXContentTestCase#testFromXContent()} without failures, and this other test with
* failures where we disable asserting on xcontent equivalence at the end.
*/
public void testFromXContentWithFailures() throws IOException {
Supplier<org.elasticsearch.protocol.xpack.graph.GraphExploreResponse> instanceSupplier =
GraphExploreResponseTests::createTestInstanceWithFailures;
//with random fields insertion in the inner exceptions, some random stuff may be parsed back as metadata,
//but that does not bother our assertions, as we only want to test that we don't break.
boolean supportsUnknownFields = true;
//exceptions are not of the same type whenever parsed back
boolean assertToXContentEquivalence = false;
AbstractXContentTestCase.testFromXContent(
AbstractXContentTestCase.NUMBER_OF_TEST_RUNS, instanceSupplier, supportsUnknownFields, getShuffleFieldsExceptions(),
getRandomFieldsExcludeFilterWhenResultHasErrors(), this::createParser, this::doParseInstance,
this::assertEqualInstances, assertToXContentEquivalence, ToXContent.EMPTY_PARAMS);
}
}
| 52.977578 | 139 | 0.726426 |
a1280ecf9bc8d4d77686f39ef457baaa1fec3e5d | 4,306 | package xmminer.xmserver.xmgraph.xmdnode.xmdatamanage;
import java.util.*;
import java.util.Vector;
import xmminer.xmlib.xmfileprocess.*;
import xmminer.xmlib.xmtable.*;
public class CXMCalculateMetaDataManager
{
private CXMMetaDataReader cdr;
private CXMMetaDataSaver cds;
private String project;
private String p_arc;
private String column_value;
private String[] column_list;
private String[] column_property;
private String[] cal_result_value;
private int cal_filter_index = 3;
private int column_filter_index = 5;
private int total_rows;
private Hashtable cal_result_h = new Hashtable();
private Hashtable column_property_h = new Hashtable();
private CXMNullCheck cnc = new CXMNullCheck();
private Hashtable cal_result_file = new Hashtable();
private String unique_file_name;
public CXMCalculateMetaDataManager()
{}
public void setMetaData(String project_name, String previous_arc)
{
project = project_name;
p_arc = previous_arc;
getPreviousArcMeta();
}
public void setCalResult(Hashtable i_h)
{
cal_result_h = i_h;
}
public int getTotalRows()
{
return total_rows;
}
public void setCalResultFile(Hashtable i_h)
{
cal_result_file = i_h;
}
public void close()
{
saveMetaData();
}
private void saveMetaData()
{
setPreviousArcMetaData();
setFilteringMetaData();
}
private void getPreviousArcMeta()
{
cdr = new CXMMetaDataReader();
cdr.setFileStatus(project,p_arc);
column_list = cdr.getProfiles("COLUMN_LIST");
total_rows = Integer.parseInt(cdr.getProfile("NUMBER_OF_ROWS"));
if (!cnc.nullCheck(column_list))
{
for (int i=0; i<column_list.length; i++)
{
column_property = cdr.getProfiles(column_list[i]);
column_property_h.put(column_list[i],column_property);
}
}
cdr.close();
}
private void setPreviousArcMetaData()
{
try
{
cds = new CXMMetaDataSaver();
cds.setFileStatus(project,p_arc);
Enumeration hEum = cal_result_h.keys();
while(hEum.hasMoreElements())
{
column_value = (String) hEum.nextElement();
cal_result_value = (String[]) cal_result_h.get(column_value);
if (!cnc.nullCheck(cal_result_value[cal_filter_index]))
{
column_property = (String[]) column_property_h.get(column_value);
column_property[column_filter_index] = "filtered";
cds.setProfiles(column_value,column_property);
}
}
cds.setProfile("FILTERING_FILE",p_arc+"_filtering");
cds.close();
} catch(Exception e)
{System.out.println("set_previous_arc_meta_error");}
cds.setProfile("FILTERING_FILE",p_arc+"_filtering");
cds.close();
}
private void setFilteringMetaData()
{
cds = new CXMMetaDataSaver();
cds.setFileStatus(project,p_arc+"_filtering");
cds.setProfile("filtering_arc",p_arc);
try
{
Enumeration hEum = cal_result_h.keys();
while(hEum.hasMoreElements())
{
column_value = (String) hEum.nextElement();
cal_result_value = (String[]) cal_result_h.get(column_value);
cds.setProfiles(column_value+"_cal_result",cal_result_value);
}
} catch(Exception e)
{System.out.println("set_cal_result_error");}
try
{
Enumeration hEum = cal_result_file.keys();
while(hEum.hasMoreElements())
{
column_value = (String) hEum.nextElement();
unique_file_name = (String) cal_result_file.get(column_value);
cds.setProfile(column_value+"_unique_value_file",unique_file_name);
}
} catch(Exception e)
{System.out.println("set_unique_file_error");}
cds.close();
}
}
| 30.978417 | 130 | 0.588017 |
fb1cd8d736a920c8a5d068be84354da49fd15c3d | 4,073 | package com.github.sardine;
import com.github.sardine.model.Principal;
import javax.xml.namespace.QName;
public class DavPrincipal
{
public static final String KEY_SELF = "self";
public static final String KEY_UNAUTHENTICATED = "unauthenticated";
public static final String KEY_AUTHENTICATED = "authenticated";
public static final String KEY_ALL = "all";
/**
* <p>
* A "principal" is a distinct human or computational actor that
* initiates access to network resources. In this protocol, a
* principal is an HTTP resource that represents such an actor.
* </p>
* <p>
* The DAV:principal element identifies the principal to which this ACE
* applies.
* </p>
* <p>
* <!ELEMENT principal (href | all | authenticated | unauthenticated
* | property | self)>
* </p>
* <p>
* The current user matches DAV:href only if that user is authenticated
* as being (or being a member of) the principal identified by the URL
* contained by that DAV:href.
* </p>
* <p>
* Either a href or one of all,authenticated,unauthenticated,property,self.
* </p>
* <p>
* DAV:property not supported.
* </p>
*/
public static enum PrincipalType
{
/**
* Principal is a String reference to an existing principal (url)
*/
HREF,
/**
* Principal is String as one of the special values: all, authenticated, unauthenticated, self
*/
KEY,
/**
* Principal is QNAME referencing a property (eg: DAV::owner, custom:someGroupId) that itself contains a href to
* an existing principal
*/
PROPERTY
}
private final PrincipalType principalType;
private final String value;
private final QName property;
private final String displayName;
public DavPrincipal(PrincipalType principalType, String value, String name)
{
this(principalType, value, null, name);
}
protected DavPrincipal(PrincipalType principalType, String value, QName property, String name)
{
if (value != null && principalType == PrincipalType.PROPERTY)
{
throw new IllegalArgumentException("Principal type property can't have a string value");
}
if (property != null && principalType != PrincipalType.PROPERTY)
{
throw new IllegalArgumentException("Principal type " + principalType.name() + " property is not allowed to have a QName property");
}
this.principalType = principalType;
this.value = value;
this.property = property;
this.displayName = name;
}
public DavPrincipal(PrincipalType principalType, QName property, String name)
{
this(principalType, null, property, name);
}
public DavPrincipal(Principal principal)
{
this.displayName = null;
if (principal.getHref() != null)
{
this.principalType = PrincipalType.HREF;
this.value = principal.getHref();
this.property = null;
}
else if (principal.getProperty() != null)
{
this.principalType = PrincipalType.PROPERTY;
this.value = null;
this.property = new QName(principal.getProperty().getProperty().getNamespaceURI(),
principal.getProperty().getProperty().getLocalName());
}
else if (principal.getAll() != null || principal.getAuthenticated() != null || principal.getUnauthenticated() != null || principal.getSelf() != null)
{
this.principalType = PrincipalType.KEY;
this.property = null;
if (principal.getAll() != null)
{
this.value = KEY_ALL;
}
else if (principal.getAuthenticated() != null)
{
this.value = KEY_AUTHENTICATED;
}
else if (principal.getUnauthenticated() != null)
{
this.value = KEY_UNAUTHENTICATED;
}
else
{
this.value = KEY_SELF;
}
}
else
{
this.principalType = null;
this.value = null;
this.property = null;
}
}
public PrincipalType getPrincipalType()
{
return principalType;
}
public String getValue()
{
return value;
}
public QName getProperty()
{
return property;
}
public String getDisplayName()
{
return displayName;
}
public String toString()
{
return "[principalType=" + principalType + ", value=" + value
+ ", property=" + property + ", displayName=" + displayName + "]";
}
}
| 25.298137 | 151 | 0.690646 |
01e00fe8ba34d5e687975e27e545c0c4a57d53f3 | 1,323 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.application.OsgiFramework;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author Simon Thoresen Hult
*/
public class NonWorkingOsgiFramework implements OsgiFramework {
@Override
public List<Bundle> installBundle(String bundleLocation) {
throw new UnsupportedOperationException();
}
@Override
public void startBundles(List<Bundle> bundles, boolean privileged) {
throw new UnsupportedOperationException();
}
@Override
public void refreshPackages() {
throw new UnsupportedOperationException();
}
@Override
public BundleContext bundleContext() {
return null;
}
@Override
public List<Bundle> bundles() {
return Collections.emptyList();
}
@Override
public List<Bundle> getBundles(Bundle requestingBundle) {
return Collections.emptyList();
}
@Override
public void allowDuplicateBundles(Collection<Bundle> bundles) { }
@Override
public void start() {
}
@Override
public void stop() {
}
}
| 22.05 | 104 | 0.694633 |
1f7259cb67cad2aa72449ab8ffcf477043c6a22c | 3,371 | package com.bindstone.transport.service;
import com.bindstone.transport.repository.TransportRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ImportService {
private final ExportService exportService;
public ImportService(ExportService exportService) {
this.exportService = exportService;
}
public void importData() throws FileNotFoundException, XMLStreamException {
System.out.println("Clear data:");
exportService.clear();
System.out.println("Start import data:");
Instant start = Instant.now();
importDataExec();
Instant end = Instant.now();
Duration interval = Duration.between(start, end);
System.out.println("Execution time in seconds: " + interval.getSeconds());
}
private void importDataExec() throws FileNotFoundException, XMLStreamException {
FileInputStream fi = new FileInputStream("/Users/qs/Documents/PROTO/couch-transport/data/parc-automobile-202003.xml");
//FileInputStream fi = new FileInputStream("/Users/qs/Documents/PROTO/couch-transport/data/sample.xml");
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader reader = xmlInputFactory.createXMLEventReader(fi);
reader.nextEvent(); // Skip Title
reader.nextEvent(); // Skip Header
List list = new ArrayList< HashMap <String, Object>>();
Map store = new HashMap<String, Object>();
String key = null;
Object data = null;
while (reader.hasNext()) {
XMLEvent nextEvent = reader.nextEvent();
if (nextEvent.isStartElement()) {
StartElement elem = nextEvent.asStartElement();
if(!"VEHICLE".equals(elem.getName().toString())) {
key = elem.getName().toString();
}
}
if (nextEvent.isCharacters()) {
data = nextEvent.asCharacters().getData();
}
if (nextEvent.isEndElement()) {
EndElement elem = nextEvent.asEndElement();
if("VEHICLE".equals(elem.getName().toString())) {
store.put("_id", store.get("PVRNUM"));
list.add(store);
store = new HashMap <String,Object>();
if (list.size() > 100) {
exportService.write(list);
list.clear();
System.out.print(".");
}
} else {
if (key != null && data != null) {
store.put(key,data);
}
key = null;
data = null;
}
}
}
exportService.write(list);
}
}
| 35.114583 | 126 | 0.605458 |
d330d0eb3f1132b064d1f0a234ef6890f116202c | 13,825 | package com.carpediem.homer.funswitch;
import android.animation.Animator;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
/**
* Created by homer on 16-6-11.
*/
public class FunSwitch extends View implements ValueAnimator.AnimatorUpdateListener,ValueAnimator.AnimatorListener{
private final static float DEFAULT_WIDTH_HEIGHT_PERCENT = 0.65f;
private final static float FACE_ANIM_MAX_FRACTION = 1.4f;
private final static float NORMAL_ANIM_MAX_FRACTION = 1.0f;
private float mWidthAndHeightPercent ;
private float mWidth;
private float mHeight;
private float mPaddingLeft;
private float mPaddingTop;
private float mPaddingBottom;
private float mPaddingRight;
private float mTransitionLength;
private Path mBackgroundPath;
private Path mFacePath;
//paint
private int mOffBackgroundColor = 0xffcccccc;
private int mOnBackgroundColor = 0xff33ccff;
private int mCurrentColor = mOffBackgroundColor;
// animation
private ValueAnimator mValueAnimator;
private Interpolator mInterpolator = new AccelerateDecelerateInterpolator();
private float mAnimationFraction = 0.0f;
private int mFaceColor = 0xffffffff;
private Paint mPaint;
private float mFaceRadius;
private float mCenterX;
private float mCenterY;
private boolean mIsOpen = false;
private boolean mIsDuringAnimation = false;
private long mOnAnimationDuration = 850L;
private long mOffAnimationDuration = (long)(mOnAnimationDuration * NORMAL_ANIM_MAX_FRACTION / FACE_ANIM_MAX_FRACTION);
public FunSwitch(Context context) {
super(context);
init(context);
}
public FunSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FunSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mWidthAndHeightPercent = DEFAULT_WIDTH_HEIGHT_PERCENT;
mPaint = new Paint();
setState(false);
// TODO: View ID 和 setSavedEnable都很重要的。
setSaveEnabled(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) (width * DEFAULT_WIDTH_HEIGHT_PERCENT);
setMeasuredDimension(width,height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//TODO:还有padding的问题偶!!!
mWidth = w;
mHeight = h;
float top = 0;
float left = 0;
float bottom = h*0.8f; //下边预留0.2空间来画阴影
float right = w;
RectF backgroundRecf = new RectF(left,top,bottom,bottom);
mBackgroundPath = new Path();
//TODO:???????????
mBackgroundPath.arcTo(backgroundRecf,90,180);
backgroundRecf.left = right - bottom;
backgroundRecf.right = right;
mBackgroundPath.arcTo(backgroundRecf,270,180);
mBackgroundPath.close();
float radius = (bottom / 2) * 0.98f;
mCenterX =(top+bottom)/2;
mCenterY = (left+bottom)/2;
mFaceRadius = radius;
mTransitionLength = right - bottom;
RectF faceRecf = new RectF(mCenterX-mFaceRadius,mCenterY-mFaceRadius,mCenterX+mFaceRadius,mCenterY+mFaceRadius);
mFacePath = new Path();
mFacePath.arcTo(faceRecf,90,180);
mFacePath.arcTo(faceRecf,270,180);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawBackground(canvas);
drawForeground(canvas);
}
private void drawBackground(Canvas canvas) {
mPaint.setColor(mCurrentColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawPath(mBackgroundPath,mPaint);
mPaint.reset();
}
private void drawForeground(Canvas canvas) {
//移动画布
canvas.save();
canvas.translate(getForegroundTransitionValue(),0);
drawFace(canvas, mAnimationFraction);
canvas.restore();
}
public void drawFace(Canvas canvas,float fraction) {
mPaint.setAntiAlias(true);
//面部背景
mPaint.setColor(mFaceColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawPath(mFacePath,mPaint);
translateAndClipFace(canvas,fraction);
drawEye(canvas,fraction);
drawMouth(canvas,fraction);
}
private void translateAndClipFace(Canvas canvas,float fraction) {
//截掉超出face的部分。
canvas.clipPath(mFacePath);
float faceTransition ;
//TODO:合理的转动区间,眼睛出现和消失的时间比为1:1,所以当fraction=0.25时,应该只显示侧脸
if (fraction >=0.0f && fraction <0.5f) {
faceTransition = fraction * mFaceRadius *4;
} else if (fraction <=NORMAL_ANIM_MAX_FRACTION){
faceTransition = - (NORMAL_ANIM_MAX_FRACTION - fraction) * mFaceRadius * 4;
} else if (fraction <=(NORMAL_ANIM_MAX_FRACTION+FACE_ANIM_MAX_FRACTION)/2) {
faceTransition = (fraction - NORMAL_ANIM_MAX_FRACTION) * mFaceRadius * 2;
} else {
faceTransition = (FACE_ANIM_MAX_FRACTION - fraction) * mFaceRadius * 2;
}
canvas.translate(faceTransition,0);
}
private void drawEye(Canvas canvas,float fraction) {
float scale;
float startValue = 1.2f;
float middleValue = (startValue + FACE_ANIM_MAX_FRACTION) /2; //1.3
if (fraction >= startValue && fraction <= middleValue) {
scale = (middleValue - fraction) * 10; //0.4f是最小缩放比
} else if (fraction > middleValue && fraction <= FACE_ANIM_MAX_FRACTION) {
scale = (fraction - middleValue) * 10 ;
} else {
scale = 1.0f;
}
// 双眼
Log.e("SACLE","scale is "+scale);
float eyeRectWidth = mFaceRadius * 0.25f ;
float eyeRectHeight = mFaceRadius * 0.35f;
float eyeXOffSet = mFaceRadius * 0.14f;
float eyeYOffSet = mFaceRadius * 0.12f;
float leftEyeCenterX = mCenterX - eyeXOffSet - eyeRectWidth/2;
float leftEyeCenterY = mCenterY - eyeYOffSet - eyeRectHeight/2;
float rightEyeCenterX = mCenterX + eyeXOffSet + eyeRectWidth/2;
eyeRectHeight *= scale; //眨眼缩放
float eyeLeft = leftEyeCenterX - eyeRectWidth/2 ;
float eyeTop = leftEyeCenterY - eyeRectHeight/2;
float eyeRight = leftEyeCenterX + eyeRectWidth/2;
float eyeBottom = leftEyeCenterY + eyeRectHeight/2;
RectF leftEye = new RectF(eyeLeft,eyeTop,eyeRight,eyeBottom);
eyeLeft = rightEyeCenterX - eyeRectWidth/2;
eyeRight = rightEyeCenterX + eyeRectWidth/2;
RectF rightEye = new RectF(eyeLeft,eyeTop,eyeRight,eyeBottom);
mPaint.setColor(mCurrentColor);
mPaint.setStyle(Paint.Style.FILL);
//眨眼动画
canvas.drawOval(leftEye,mPaint);
canvas.drawOval(rightEye,mPaint);
}
private void drawMouth(Canvas canvas,float fraction) {
//TODO:使用贝塞尔曲线来画嘴
float eyeRectWidth = mFaceRadius * 0.2f;
float eyeXOffSet = mFaceRadius * 0.14f;
float eyeYOffSet = mFaceRadius * 0.21f;
float mouthWidth = (eyeRectWidth + eyeXOffSet) * 2; //嘴的长度正好和双眼之间的距离一样
float mouthHeight = (mFaceRadius * 0.05f);
float mouthLeft = mCenterX - mouthWidth / 2;
float mouthTop = mCenterY + eyeYOffSet; // mCenterY是face的原点
//嘴巴
if (fraction <=0.75) { //
canvas.drawRect(mouthLeft, mouthTop, mouthLeft + mouthWidth, mouthTop + mouthHeight, mPaint);
} else {
Path path = new Path();
path.moveTo(mouthLeft,mouthTop);
float controlX = mouthLeft + mouthWidth/2;
float controlY = mouthTop + mouthHeight + mouthHeight * 15 * (fraction - 0.75f);
path.quadTo(controlX,controlY,mouthLeft+mouthWidth,mouthTop);
path.close();
canvas.drawPath(path,mPaint);
}
}
private float getForegroundTransitionValue() {
float result;
if (mIsOpen) {
if (mIsDuringAnimation) {
result = mAnimationFraction > NORMAL_ANIM_MAX_FRACTION ?
mTransitionLength : mTransitionLength * mAnimationFraction;
} else {
result = mTransitionLength;
}
} else {
if (mIsDuringAnimation) {
result = mTransitionLength * mAnimationFraction;
} else {
result = 0;
}
}
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("TEST","onTouchEvent");
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
if (mIsDuringAnimation) {
return true;
}
if (mIsOpen) {
startCloseAnimation();
mIsOpen = false;
} else {
startOpenAnimation();
mIsOpen = true;
}
return true;
}
return super.onTouchEvent(event);
}
private void startOpenAnimation() {
mValueAnimator = ValueAnimator.ofFloat(0.0f, FACE_ANIM_MAX_FRACTION);
mValueAnimator.setDuration(mOnAnimationDuration);
mValueAnimator.addUpdateListener(this);
mValueAnimator.addListener(this);
mValueAnimator.setInterpolator(mInterpolator);
mValueAnimator.start();
startColorAnimation();
}
private void startCloseAnimation() {
mValueAnimator = ValueAnimator.ofFloat(NORMAL_ANIM_MAX_FRACTION,0);
mValueAnimator.setDuration(mOffAnimationDuration);
mValueAnimator.addUpdateListener(this);
mValueAnimator.addListener(this);
mValueAnimator.setInterpolator(mInterpolator);
mValueAnimator.start();
startColorAnimation();
}
private void startColorAnimation() {
int colorFrom = mIsOpen?mOnBackgroundColor:mOffBackgroundColor; //mIsOpen为true则表示要启动关闭的动画
int colorTo = mIsOpen? mOffBackgroundColor:mOnBackgroundColor;
long duration = mIsOpen? mOffAnimationDuration:mOnAnimationDuration;
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setInterpolator(mInterpolator);
colorAnimation.setDuration(duration); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
mCurrentColor = (int)animator.getAnimatedValue();
}
});
colorAnimation.start();
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Log.e("TEST",animation.getAnimatedValue()+" ");
mAnimationFraction = (float)animation.getAnimatedValue();
invalidate();
}
@Override
public void onAnimationStart(Animator animation) {
mIsDuringAnimation = true;
}
@Override
public void onAnimationEnd(Animator animation) {
mIsDuringAnimation = false;
}
@Override
public void onAnimationCancel(Animator animation) {
mIsDuringAnimation = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
mIsDuringAnimation = true;
}
public void setState(boolean open) {
mIsOpen = open;
refreshState();
}
public void refreshState() {
mCurrentColor = mIsOpen ? mOnBackgroundColor : mOffBackgroundColor;
invalidate();
}
@Override
protected Parcelable onSaveInstanceState() {
Log.e("TEST","onSave");
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isOpen = mIsOpen ? 1:0;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
Log.e("TEST","onRestore");
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(state);
boolean result = ss.isOpen == 1;
setState(result);
}
static class SavedState extends BaseSavedState {
int isOpen;
public SavedState(Parcel source) {
super(source);
isOpen = source.readInt();
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(isOpen);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[0];
}
};
}
}
| 33.968059 | 122 | 0.638481 |
0c95d3ba08a91cf304ab8279fe59dd0115ec7d5f | 659 | package fr.syncrase.ecosyst.domain;
import static org.assertj.core.api.Assertions.assertThat;
import fr.syncrase.ecosyst.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class PlanteTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Plante.class);
Plante plante1 = new Plante();
plante1.setId(1L);
Plante plante2 = new Plante();
plante2.setId(plante1.getId());
assertThat(plante1).isEqualTo(plante2);
plante2.setId(2L);
assertThat(plante1).isNotEqualTo(plante2);
plante1.setId(null);
assertThat(plante1).isNotEqualTo(plante2);
}
}
| 27.458333 | 57 | 0.6783 |
4e8fe3877acedd27a7e94cd8f1a2c3ab18a73f56 | 1,003 | package cn.smallmartial.demo.web;
import cn.smallmartial.demo.annotation.AutoIdempotent;
import cn.smallmartial.demo.service.TokenService;
import cn.smallmartial.demo.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author smallmartial
* @Date 2020/4/16
* @Email smallmarital@qq.com
*/
@RestController
public class BusinessController {
@Autowired
private TokenService tokenService;
@GetMapping("/get/token")
public Object getToken(){
String token = tokenService.createToken();
return ResponseUtil.ok(token) ;
}
@AutoIdempotent
@GetMapping("/test/Idempotence")
public Object testIdempotence() {
String token = "接口幂等性测试";
return ResponseUtil.ok(token) ;
}
} | 27.108108 | 62 | 0.749751 |
dbc2eb24c8d3afe7b7c544ded77f5259b2504d97 | 3,661 | /*
* Copyright (C) 2017 Julien Viet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package examples;
import io.reactiverse.reactivex.pgclient.*;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.vertx.docgen.Source;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
@Source
public class RxExamples {
public void simpleQuery01Example(PgPool pool) {
// A simple query
Single<PgRowSet> single = pool.rxQuery("SELECT * FROM users WHERE id='julien'");
// Execute the query
single.subscribe(result -> {
System.out.println("Got " + result.size() + " rows ");
}, err -> {
System.out.println("Failure: " + err.getMessage());
});
}
public void streamingQuery01Example(PgPool pool) {
// Create a flowable
Observable<Row> observable = pool.rxGetConnection()
.flatMapObservable(conn -> conn
.rxPrepare("SELECT * FROM users WHERE first_name LIKE $1")
.flatMapObservable(pq -> {
// Fetch 50 rows at a time
PgStream<Row> stream = pq.createStream(50, Tuple.of("julien"));
return stream.toObservable();
})
// Close the connection after usage
.doAfterTerminate(conn::close));
// Then subscribe
observable.subscribe(row -> {
System.out.println("User: " + row.getString("last_name"));
}, err -> {
System.out.println("Error: " + err.getMessage());
}, () -> {
System.out.println("End of stream");
});
}
public void streamingQuery02Example(PgPool pool) {
// Create a flowable
Flowable<Row> flowable = pool.rxGetConnection()
.flatMapPublisher(conn -> conn.rxPrepare("SELECT * FROM users WHERE first_name LIKE $1")
.flatMapPublisher(pq -> {
// Fetch 50 rows at a time
PgStream<Row> stream = pq.createStream(50, Tuple.of("julien"));
return stream.toFlowable();
}));
// Then subscribe
flowable.subscribe(new Subscriber<Row>() {
private Subscription sub;
@Override
public void onSubscribe(Subscription subscription) {
sub = subscription;
subscription.request(1);
}
@Override
public void onNext(Row row) {
sub.request(1);
System.out.println("User: " + row.getString("last_name"));
}
@Override
public void onError(Throwable err) {
System.out.println("Error: " + err.getMessage());
}
@Override
public void onComplete() {
System.out.println("End of stream");
}
});
}
public void transaction01Example(PgPool pool) {
Completable completable = pool
.rxBegin()
.flatMapCompletable(tx -> tx
.rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Julien','Viet')")
.flatMap(result -> tx.rxQuery("INSERT INTO Users (first_name,last_name) VALUES ('Emad','Alblueshi')"))
.flatMapCompletable(result -> tx.rxCommit()));
completable.subscribe(() -> {
// Transaction succeeded
}, err -> {
// Transaction failed
});
}
}
| 29.524194 | 110 | 0.643813 |
9bb2b97b8c889ff7a9f939cc403976e9727982e3 | 676 | package org.aion.avm.core.miscvisitors.interfaceVisitor;
public class ClassWithMultipleFieldSuffix {
interface InnerInterface {
int a = 1;
String b = "abc";
Object c = new Object();
class FIELDS{ }
class FIELDS0{ }
class FIELDS1{ }
class FIELDS2{ }
class FIELDS3{ }
class FIELDS4{ }
class FIELDS5{ }
class FIELDS6{ }
class FIELDS7{ }
class FIELDS8{ }
class FIELDS9{ }
class FIELDS10{ }
class FIELDS11{ }
class FIELDS12{ }
class FIELDS13{ }
class FIELDS14{ }
class FIELDS15{ }
class FIELDS17{ }
}
}
| 23.310345 | 56 | 0.538462 |
f233658ffe5799f81118faa929728a0ac2f8c89a | 41,218 | import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
/**
* Auto-generated code below aims at helping you parse the standard input according to the problem statement.
**/
class Tron
{
static Random RAND = new Random();
static final boolean DEBUG = true;
static final boolean RELEASE = false;
static final int NB_MOTOS = 2;
static int MY_ID = 0;
public static void ass(String p_s)
{
if (!RELEASE)
System.err.println(" === ERROR === : " + p_s);
}
public static void db(String p_s)
{
if (DEBUG && !RELEASE)
System.err.println("Dbg : " + p_s);
}
public void run()
{
Scanner in = new Scanner(System.in);
Grid g = new Grid();
Moto[] motos = new Moto[NB_MOTOS];
for (int i = 0; i < NB_MOTOS; i++)
// motos[i] = new Moto(i, new StrMonteCarloTreeSearch(i));
// motos[i] = new Moto(i, new StrWallHugger(i));
// motos[i] = new Moto(i, new StrCouard(i));
motos[i] = new Moto(i, new StrMiniMaxCutter(i));
State s = new State(g, motos);
int turn = 0;
// game loop
while (true)
{
int N = in.nextInt(); // total number of players (2 to 4).
int P = in.nextInt(); // your player number (0 to 3).
MY_ID = P;
for (int i = 0; i < N; i++)
{
int oY = in.nextInt(); // starting X coordinate of lightcycle (or -1)
int oX = in.nextInt(); // starting Y coordinate of lightcycle (or -1)
int nY = in.nextInt(); // new X coordinate of lightcycle (can be == X0 if you play before this player)
int nX = in.nextInt(); // new Y coordinate of lightcycle (can be == Y0 if you play before this player)
db("upd : " + i + "-> (" + oX + "," + oY + ") -> (" + nX + "," + nY + ")");
s.upd(turn, i, oX, oY, nX, nY);
}
// System.err.println(g);
Direction d = motos[P].decide(turn, s);
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
// A single line with UP, DOWN, LEFT or RIGHT
System.out.println(d.toAction());
turn++;
}
}
public static void main(String args[])
{
new Tron().run();
}
public static void fillArea(int x, int y, int original, int fill, int[][] arr)
{
int maxX = arr.length - 1;
int maxY = arr[0].length - 1;
int[][] stack = new int[(maxX + 1) * (maxY + 1)][2];
int index = 0;
stack[0][0] = x;
stack[0][1] = y;
arr[x][y] = fill;
while (index >= 0)
{
x = stack[index][0];
y = stack[index][1];
index--;
if ((x > 0) && (arr[x - 1][y] == original))
{
arr[x - 1][y] = fill;
index++;
stack[index][0] = x - 1;
stack[index][1] = y;
}
if ((x < maxX) && (arr[x + 1][y] == original))
{
arr[x + 1][y] = fill;
index++;
stack[index][0] = x + 1;
stack[index][1] = y;
}
if ((y > 0) && (arr[x][y - 1] == original))
{
arr[x][y - 1] = fill;
index++;
stack[index][0] = x;
stack[index][1] = y - 1;
}
if ((y < maxY) && (arr[x][y + 1] == original))
{
arr[x][y + 1] = fill;
index++;
stack[index][0] = x;
stack[index][1] = y + 1;
}
}
}
/**
* A* Algorithm
*
* @param p_o
* Origin
* @param p_g
* Goal
* @param p_map
* Map : A 2D Grid
* @return A path from Origin to Goal, origin <b>NOT</b> included, goal included. Empty if there is no path from
* origin to goal.
*/
public static List<Position> aStar(Position p_o, Position p_g, Grid p_map)
{
Tron pl = new Tron();
LinkedList<Position> path = new LinkedList<>();
TreeMap<AStar2DNode, Integer> open = new TreeMap<>();
HashSet<AStar2DNode> close = new HashSet<>();
open.put(pl.new AStar2DNode(p_o, 0, 0), 0);
// Find path to goal
while (!open.isEmpty() && !open.firstKey().p.equals(p_g))
{
AStar2DNode current = open.pollFirstEntry().getKey();
close.add(current);
for (Position p : current.p.casesAutour())
if (p_map.isAccessible(p))
{
int cost = current.g + 1;
AStar2DNode neighbor = pl.new AStar2DNode(p, cost, p.distanceL1(p_g));
neighbor.prev = current;
if (open.containsKey(neighbor) && (open.get(neighbor) - neighbor.h) > neighbor.g)
open.remove(neighbor);
if (!open.containsKey(neighbor) && !close.contains(neighbor))
open.put(neighbor, neighbor.h + neighbor.g);
}
}
// reconstruct path if possible
if (!open.isEmpty() && open.firstKey().p.equals(p_g))
{
AStar2DNode current = open.firstKey();
while (!current.p.equals(p_o))
{
path.addFirst(current.p);
current = current.prev;
}
}
return path;
}
public class AStar2DNode implements Comparable<AStar2DNode>
{
Position p;
int g;
int h;
AStar2DNode prev = null;
public AStar2DNode(Position p_p, int p_g, int p_h)
{
this.p = p_p;
this.g = p_g;
this.h = p_h;
}
/**
* Redéfinition.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((this.p == null) ? 0 : this.p.hashCode());
return result;
}
/**
* Redéfinition.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
AStar2DNode other = (AStar2DNode) obj;
if (this.p == null)
{
if (other.p != null)
return false;
}
else if (!this.p.equals(other.p))
return false;
return true;
}
@Override
public int compareTo(AStar2DNode p_o)
{
return (this.g + this.h) - (p_o.g + p_o.h);
}
}
public class Dijkstra
{
private int[][] grid;
private int[][] maze;
private Position goal;
private Position start;
private ArrayList<Position> path = new ArrayList<Position>();
/**
* Constructeur
*
* @param maze
* @param start
* @param goal
*/
public Dijkstra(int[][] maze, Position start, Position goal)
{
this.maze = maze;
this.grid = new int[maze.length][maze[0].length];
for (int i = 0; i < this.grid.length; i++)
for (int j = 0; j < this.grid[0].length; j++)
if (maze[i][j] == 0)
this.grid[i][j] = -1;
else
this.grid[i][j] = Integer.MAX_VALUE;
this.start = start;
this.goal = goal;
}
private boolean nearEquals(double p_d, double p_d2)
{
if (Math.abs(p_d - p_d2) < 0.01)
return true;
else
return false;
}
/**
* Tiens Toé !
*
* @return
*/
public ArrayList<Position> solve()
{
this.grid[this.goal.x][this.goal.y] = 0;
for (Position around : this.goal.casesAutour())
this.grid[around.x][around.y] = this.goal.distanceL15(around);
boolean modif = true;
while ((this.grid[this.start.x][this.start.y] == Integer.MAX_VALUE) && modif)
{
modif = false;
for (int i = 0; i < this.grid.length; i++)
for (int j = 0; j < this.grid[0].length; j++)
if (this.grid[i][j] < Integer.MAX_VALUE && this.grid[i][j] > -1)
{
Position now = new Position(i, j);
for (Position a : now.casesAutour())
if (this.maze[a.x][a.y] != 0
&& this.grid[a.x][a.y] > this.grid[now.x][now.y] + now.distanceL15(a))
{
this.grid[a.x][a.y] = this.grid[now.x][now.y] + now.distanceL15(a);
modif = true;
}
}
}
if (!modif)
return this.path;
Position curr = new Position(this.start);
int v = this.grid[this.start.x][this.start.y];
int stopper = 0;
while (v > 0 && stopper < Math.max(this.grid.length, this.grid[0].length))
{
for (Position nex : curr.casesAutour())
{
Position next = nex;
int g = this.grid[next.x][next.y];
int d = v - curr.distanceL15(next);
if (this.nearEquals(g, d))
{
this.path.add(next);
v -= curr.distanceL15(next);
curr = next;
break;
}
}
stopper++;
}
if (this.path.size() == 1)
this.path.add(this.goal);
return this.path;
}
/**
* Redéfinition.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder s = new StringBuilder("");
for (int i = 0; i < this.maze.length; i++)
{
for (int j = 0; j < this.maze[0].length; j++)
if (this.path.contains(new Position(i, j)))
s.append("X");
else
s.append((this.maze[i][j] == 0 ? "0" : "1"));
s.append("\n");
}
s.append("\n");
for (int i = 0; i < this.maze.length; i++)
{
for (int j = 0; j < this.maze[0].length; j++)
if (this.path.contains(new Position(i, j)))
s.append("X");
else
s.append((this.grid[i][j] < 0 ? "0" : (this.grid[i][j] > 10 ? "Z" : (this.grid[i][j]) + "")));
s.append("\n");
}
return s.toString();
}
}
public enum Direction
{
/**
* définitions de l'énumération. type de directions.
*/
N, S, E, W;
/**
* Renvoie la direction inverse à p_dir
*
* @param p_dir
* @return
*/
public Direction inverse()
{
switch (this)
{
case N:
return S;
case S:
return N;
case W:
return E;
case E:
return W;
default:
return null;
}
}
public String toAction()
{
switch (this)
{
case N:
return "UP";
case S:
return "DOWN";
case W:
return "LEFT";
case E:
return "RIGHT";
default:
return "";
}
}
/**
* Redéfinition pour débugage de la méthode toString.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
switch (this)
{
case N:
return "N";
case S:
return "S";
case W:
return "O";
case E:
return "E";
default:
return "";
}
}
}
enum Distance
{
MANHATTAN, CHEBYSHEV, EUCLIDEAN;
/**
* ¸ Dit si oui ou non, deux positions sont à une certain range selon un mesure donnée.
*
* @param p_p1
* Position 1
* @param p_p2
* Position 2
* @param p_d
* La mesure choisie
* @param p_r
* la distance
* @return vrai si p1 est à moins que p_r de p2 selon la mesure choisie
*/
public boolean inside(Position p_p1, Position p_p2, int p_r)
{
switch (this)
{
case MANHATTAN:
return p_p1.distanceL1(p_p2) <= p_r;
case CHEBYSHEV:
return p_p1.distanceL15(p_p2) <= p_r;
default:
return p_p1.distanceL2(p_p2) <= p_r;
}
}
}
public class Grid
{
public static final int VIDE = 8;
public final static int MY = 30;
public final static int MX = 20;
int[][] g = new int[MX][MY];
Position[] m = new Position[NB_MOTOS];
public Grid()
{
for (int x = 0; x < MX; x++)
for (int y = 0; y < MY; y++)
this.g[x][y] = VIDE;
}
@Override
public Grid clone()
{
Grid gg = new Grid();
for (int x = 0; x < MX; x++)
for (int y = 0; y < MY; y++)
gg.g[x][y] = this.g[x][y];
for (int i = 0; i < this.m.length; i++)
gg.m[i] = this.m[i];
return gg;
}
public boolean isAccessible(Position p_p)
{
return this.isInside(p_p) && this.g[p_p.x][p_p.y] == VIDE;
}
public boolean isInside(Position p_p)
{
return p_p.x >= 0 && p_p.x < MX && p_p.y >= 0 && p_p.y < MY;
}
@Override
public String toString()
{
StringBuilder s = new StringBuilder();
s.append("|");
for (int x = 0; x < MY; x++)
s.append("_");
s.append("|\n|");
for (int x = 0; x < MX; x++)
{
for (int y = 0; y < MY; y++)
if (this.g[x][y] != VIDE)
s.append("" + this.g[x][y]);
else
s.append(" ");
s.append("|\n|");
}
for (int x = 0; x < MY; x++)
s.append("_");
s.append("|\n");
return s.toString();
}
public void upd(int p_turn, int nb, int ox, int oy, int nx, int ny)
{
if (ox == -1) // nb is dead;
{
for (int x = 0; x < MX; x++)
for (int y = 0; y < MY; y++)
if (this.g[x][y] == nb)
this.g[x][y] = VIDE;
this.m[nb] = new Position(-1, -1);
}
else
{
// incohérence mais pas les premiers tours qui sont l'init de la position des motos
if (this.g[ox][oy] != nb && p_turn > this.m.length)
System.err.println("Erreur de saisie précédente ? --- LOOK INTO IT !");
this.g[nx][ny] = nb;
this.m[nb] = new Position(nx, ny);
}
}
public int whosThere(Position p_p)
{
return this.g[p_p.x][p_p.y];
}
}
public abstract class IStrategy
{
int id = -1;
public IStrategy(int p_id)
{
this.id = p_id;
}
public abstract Direction decide(int p_turn, State p_s);
}
public class Moto
{
int id;
Position p;
IStrategy s;
public Moto(int p_id, IStrategy p_s)
{
this.id = p_id;
this.s = p_s;
}
@Override
public Moto clone()
{
Moto m = new Moto(this.id, this.s);
m.p = this.p;
return m;
}
public Direction decide(int p_turn, State p_s)
{
return this.s.decide(p_turn, p_s);
}
public boolean isDead()
{
return this.p.equals(new Position(-1, -1));
}
@Override
public String toString()
{
return "[" + this.id + ":" + this.p + "]";
}
public void upd(int nx, int ny)
{
this.p = new Position(nx, ny);
}
}
public class Position
{
/**
* Position en x
*/
final public int x;
/**
* ¸ Position en y
*/
final public int y;
/**
* Constructeur d'initialisation. Initialise un objet Position avec sa position en x et en y
*
* @param p_X
* position en x
* @param p_Y
* position en y
*/
public Position(int p_X, int p_Y)
{
this.x = p_X;
this.y = p_Y;
}
/**
* Constructeur par copie. Initialise un objet Position avec la position en x et en y
*
* @param p_p
* position
*/
public Position(Position p_p)
{
this.x = p_p.x;
this.y = p_p.y;
}
/**
* Retourne l'ensemble des positions autour de la position courante.
*
* @return
*/
public HashSet<Position> casesAutour()
{
HashSet<Position> s = new HashSet<Position>();
for (Direction d : Direction.values())
s.add(this.relativePos(d));
return s;
}
/**
* Renvoie la distance (de Manhattan) entre deux position
*
* @param p_rel
* La position relative
* @return la distance de Manhattan entre la position courante et la position relative
*/
public int distanceL1(Position p_o)
{
return Math.abs(this.x - p_o.x) + Math.abs(this.y - p_o.y);
}
/**
* Renvoie la distance de Chebyshev entre deux positions
*
* @param p_rel
* La position relative
* @return la distance de Chebyshev calculée par max(abs(x1-x2),abs(y1-y2))
*/
public int distanceL15(Position p_rel)
{
return Math.max(Math.abs(this.x - p_rel.x), Math.abs(this.y - p_rel.y));
}
/**
* Retourne la distance L2 (euclidienne) entre deux positions
*
* @param p_rel
* La position relative
* @return la distance euclidienne entre la position courante et la position relative
*/
public double distanceL2(Position p_rel)
{
return Math.sqrt(Math.pow(this.x - p_rel.x, 2) + Math.pow(this.y - p_rel.y, 2));
}
/**
* Renvoie la distance (Infinity) entre deux position
*
* @param p_rel
* La position relative
* @return la distance L-infty entre la position courante et la position relative
*/
public int distanceLI(Position p_o)
{
return Math.max(Math.abs(this.x - p_o.x), Math.abs(this.y - p_o.y));
}
/**
* Redéfinition.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
Position other = (Position) obj;
if (this.x != other.x)
return false;
if (this.y != other.y)
return false;
return true;
}
/**
* Calcule les positions dans un certain range selon une certaine mesure.
*
* @param p_r
* le range
* @param p_d
* la mesure
* @return un ensemble de positions
*/
private HashSet<Position> getInRange(int p_r, Distance p_d)
{
HashSet<Position> s = new HashSet<Position>();
for (int x = 0; x <= p_r; x++)
{
int y = 0;
Position p = new Position(this.x + x, this.y + y);
while (p_d.inside(this, p, p_r))
{
s.add(p);
s.add(new Position(this.x - x, this.y + y));
s.add(new Position(this.x + x, this.y - y));
s.add(new Position(this.x - x, this.y - y));
p = new Position(this.x + x, this.y + ++y);
}
}
return s;
}
/**
* Calcule les position dans le range d'une certaine distance de Manhattan
*
* @param p_r
* @return
*/
public HashSet<Position> getInRangeL1(int p_r)
{
return this.getInRange(p_r, Distance.MANHATTAN);
}
/**
* Calcule les position dans le range d'une certaine distance Euclidienne
*
* @param p_r
* @return
*/
public HashSet<Position> getInRangeL2(int p_r)
{
return this.getInRange(p_r, Distance.EUCLIDEAN);
}
/**
* Redéfinition.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + this.x;
result = prime * result + this.y;
return result;
}
/**
* Retourne la direction relative d'une position par rapport à la position courante.
*
* @param p_Pos
* La position dont on cherche la direction
* @return La direction relative à p_Pos
*/
public Direction relativeDir(Position p_Pos)
{
if (this.equals(p_Pos))
throw new IllegalArgumentException(
"Il n'est pas possible de calculer la direction de la position courante.");
double theta = (Math.atan2(p_Pos.y - this.y, p_Pos.x - this.x));
if (theta < 0)
theta += Math.PI * 2;
// System.out.println(theta);
Direction[] dir = { Direction.S, Direction.E, Direction.N, Direction.W, Direction.S };
int i = 0;
double search = Math.PI / 8;
while (theta > search)
{
i++;
search += Math.PI / 2;
}
return dir[i];
}
/**
* Retourne une nouvelle position relative selon la direction passée en paramètre.
*
* @param p_Direction
* une direction donnée
* @return newPos une nouvelle position
*/
public Position relativePos(Direction p_Direction)
{
Position newPos = null;
if (p_Direction == null)
return this;
switch (p_Direction)
{
case N:
newPos = new Position(this.x - 1, this.y);
break;
case S:
newPos = new Position(this.x + 1, this.y);
break;
case E:
newPos = new Position(this.x, this.y + 1);
break;
case W:
newPos = new Position(this.x, this.y - 1);
break;
default:
}
return newPos;
}
/**
* Redéfinition.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "" + this.x + " " + this.y + "";
}
}
public class MinMaxSearchNode
{
HashMap<Direction, MinMaxSearchNode> nx = new HashMap<>();
double v = Double.NEGATIVE_INFINITY;
Direction best = null;
State s;
public MinMaxSearchNode(State p_s)
{
this.s = p_s;
}
public void expand(int p_id)
{
List<Direction> possible = this.s.getAcc(p_id);
if (possible.isEmpty())
if (p_id == MY_ID)
this.v = -100;
else
this.v = 100;
else
for (Direction d : possible)
this.nx.put(d, new MinMaxSearchNode(this.s.next(0, p_id, d)));
}
public void value(int p_id)
{
db("Value in :: " + "(" + this.nx.isEmpty() + ")" + this + "");
if (this.nx.isEmpty()) // Leafs
{
Position mp = this.s.getPos(MY_ID);
Position op = this.s.getPos(1 - MY_ID);
if (aStar(mp, op, this.s.g).isEmpty())
{ // Then we are sperated
Grid gc = this.s.g.clone();
fillArea(mp.x, mp.y, Grid.VIDE, 10 + MY_ID, gc.g);
fillArea(op.x, op.y, Grid.VIDE, 10 + 1 - MY_ID, gc.g);
int mc = 0, oc = 0;
for (int x = 0; x < Grid.MX; x++)
for (int y = 0; y < Grid.MY; y++)
{
if (gc.g[x][y] == 10 + MY_ID)
mc++;
if (gc.g[x][y] == 10 + 1 - MY_ID)
oc++;
}
this.v = 12 + ((float) Math.abs(mc - oc)) / ((float) Math.max(mc, oc)) * 86;
if (oc > mc)
this.v *= -1;
// the result should be between -12..-99 when the opponent has more space
// and between 12..99 when we have more space !
}
else
this.v = 0;
db("Leaf :: " + this + "");
}
else if (p_id == MY_ID) // my turn
{
this.v = Double.NEGATIVE_INFINITY;
// Max over subnodes
for (Entry<Direction, MinMaxSearchNode> n : this.nx.entrySet())
if (n.getValue().v > this.v)
{
this.v = n.getValue().v;
this.best = n.getKey();
}
}
else // others turn
{
this.v = Double.POSITIVE_INFINITY;
// Min over subnodes
for (Entry<Direction, MinMaxSearchNode> n : this.nx.entrySet())
if (n.getValue().v < this.v)
{
this.v = n.getValue().v;
this.best = n.getKey();
}
}
// db("Value out :: " + this + "");
}
/**
* Redéfinition.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "[ v=" + this.v + ", best=" + this.best + ", nx=" + this.nx + "]";
}
}
public class State
{
Grid g;
Moto[] m;
public State(Grid p_g, Moto[] p_motos)
{
this.g = p_g;
this.m = p_motos;
}
public ArrayList<Direction> getAcc(int nb)
{
ArrayList<Direction> possible = new ArrayList<>();
Position p = this.getPos(nb);
for (Direction d : Direction.values())
if (this.g.isAccessible(p.relativePos(d)))
possible.add(d);
return possible;
}
public Position getPos(int nb)
{
if (!this.m[nb].p.equals(this.g.m[nb]))
ass("/!\\/!\\/!\\ State Coherence Error /!\\/!\\/!\\");
return this.g.m[nb];
}
public State next(int p_t, int p_id, Direction p_act)
{
// Clone all motos
Moto[] mc = new Moto[this.m.length];
for (int i = 0; i < this.m.length; i++)
mc[i] = this.m[i].clone();
State n = new State(this.g.clone(), mc);
Position op = mc[p_id].p;
Position np = op.relativePos(p_act);
if (!this.g.isAccessible(np))
db(op + "/" + p_act + "->" + np);
n.upd(p_t + 1, p_id, op.x, op.y, np.x, np.y);
return n;
}
@Override
public String toString()
{
return Arrays.toString(this.m) + "\n" + this.g;
}
public void upd(int p_turn, int nb, int ox, int oy, int nx, int ny)
{
this.g.upd(p_turn, nb, ox, oy, nx, ny);
this.m[nb].upd(nx, ny);
// Assertion :
if (p_turn > this.m.length)
for (Moto mm : this.m)
if (!mm.p.equals(this.g.m[mm.id]))
ass("/!\\/!\\/!\\ State Coherence Error /!\\/!\\/!\\");
}
}
public class StrCouard extends IStrategy
{
public StrCouard(int p_id)
{
super(p_id);
}
@Override
public Direction decide(int p_t, State p_s)
{
Direction dir = Direction.N;
TreeMap<Double, Direction> t = new TreeMap<>();
Position p = p_s.getPos(this.id);
Position op = p_s.getPos(1 - this.id);
for (Direction d : p_s.getAcc(this.id))
t.put(p.relativePos(d).distanceL2(op), d);
System.err.println(t);
if (!t.isEmpty())
return t.lastEntry().getValue();
else
return dir;
}
}
public class StrMiniMaxCutter extends StrWallHugger
{
public StrMiniMaxCutter(int p_id)
{
super(p_id);
// this.TIME_LEFT = 10;
// this.TRAJ_LENGTH = 100;
}
@Override
public Direction decide(int p_t, State p_s)
{
Direction dir = super.decide(p_t, p_s);
Position meP = p_s.getPos(this.id);
Position oP = p_s.getPos(1 - this.id);
// Distance with other player is less than 5
if (meP.distanceL1(oP) < 5) // do minimax
{
MinMaxSearchNode s = new MinMaxSearchNode(p_s);
s.expand(this.id);
for (MinMaxSearchNode ss : s.nx.values())
{
ss.expand(1 - this.id);
for (MinMaxSearchNode sss : ss.nx.values())
{
sss.expand(this.id);
for (MinMaxSearchNode ssss : sss.nx.values())
ssss.value(Grid.VIDE);
sss.value(this.id);
}
ss.value(1 - this.id);
}
s.value(this.id);
db(s + "");
dir = s.best;
}
else
{
// Cut the grid according to possible dirs
// and flood them to count the possible points
}
return dir;
}
}
public class StrMonteCarloTreeSearch extends StrRandomAccessible
{
public int TIME_LEFT = 98;
public int TRAJ_LENGTH = 200;
public StrMonteCarloTreeSearch(int p_id)
{
super(p_id);
}
@Override
public Direction decide(int p_t, State p_s)
{
Direction dir = super.decide(p_t, p_s);
long timer_start = System.currentTimeMillis();
int[] val = new int[Direction.values().length];
ArrayList<Direction> possible = p_s.getAcc(this.id);
StrRandomAccessible str = new StrRandomAccessible(this.id);
StrRandomAccessible advStr = new StrRandomAccessible(1 - this.id);
while (System.currentTimeMillis() - timer_start < this.TIME_LEFT)
for (Direction d : possible)
{
int vald = 0;
Direction fd = d;
State ns = p_s;
while (fd != null && vald < this.TRAJ_LENGTH)
{
vald++;
ns = ns.next(p_t, this.id, fd);
Direction advD = advStr.decide(p_t, ns);
if (advD == null)
vald = this.TRAJ_LENGTH;
else
ns = ns.next(p_t + vald, 1 - this.id, advD);
fd = str.decide(p_t, ns);
}
val[d.ordinal()] += vald;
}
TreeMap<Integer, Direction> t = new TreeMap<>();
for (Direction d : possible)
t.put(val[d.ordinal()], d);
System.err.println(t);
if (!t.isEmpty())
return t.lastEntry().getValue();
else
return dir;
}
}
public class StrRandomAccessible extends IStrategy
{
public StrRandomAccessible(int p_id)
{
super(p_id);
}
@Override
public Direction decide(int p_t, State p_s)
{
Direction dir = Direction.N;
if (this.id == -1)
{
ass("Deciding for no moto ! How the FUCK !");
return dir;
}
List<Direction> possible = p_s.getAcc(this.id);
// System.err.println("p : " + p_s.getPos(this.id) + " -> " + possible);
Collections.shuffle(possible);
if (possible.isEmpty())
// db("I'm f*ck*ng BLOCKED !");
return null;
return possible.get(0);
}
}
public class StrWallHugger extends IStrategy
{
final List<Direction> ORDER = Arrays.asList(Direction.values());
public StrWallHugger(int p_id)
{
super(p_id);
Collections.shuffle(this.ORDER);
}
@Override
public Direction decide(int p_t, State p_s)
{
Direction d = this.ORDER.get(0);
for (Direction c : this.ORDER)
{
Position p = p_s.getPos(this.id).relativePos(c);
if (p_s.g.isAccessible(p))
for (Position pp : p.casesAutour())
if (!p_s.g.isAccessible(pp))
d = c;
}
return d;
}
}
public class Vector2D extends Point2D.Double
{
/*
* (non-Javadoc)
*
* @see java.awt.geom.Point2D.Double#Point2D.Double()
*/
public Vector2D()
{
super();
}
/*
* (non-Javadoc)
*
* @see java.awt.geom.Point2D.Double#Point2D.Double()
*/
public Vector2D(double x, double y)
{
super(x, y);
}
/**
* Copy constructor
*/
public Vector2D(Vector2D v)
{
this.x = v.x;
this.y = v.y;
}
/** Product of components of the vector: compenentProduct( <x y>) = x*y. */
public double componentProduct()
{
return this.x * this.y;
}
/** Componentwise product: <this.x*rhs.x, this.y*rhs.y> */
public Vector2D componentwiseProduct(Vector2D rhs)
{
return new Vector2D(this.x * rhs.x, this.y * rhs.y);
}
/**
* Since Vector2D works only in the x-y plane, (u x v) points directly along the z axis. This function returns
* the value on the z axis that (u x v) reaches.
*
* @return signed magnitude of (this x rhs)
*/
public double crossProduct(Vector2D rhs)
{
return this.x * rhs.y - this.y * rhs.x;
}
/** Dot product of the vector and rhs */
public double dotProduct(Vector2D rhs)
{
return this.x * rhs.x + this.y * rhs.y;
}
/**
* @return the radius (length, modulus) of the vector in polar coordinates
*/
public double getR()
{
return Math.sqrt(this.x * this.x + this.y * this.y);
}
/**
* @return the angle (argument) of the vector in polar coordinates in the range [-pi/2, pi/2]
*/
public double getTheta()
{
return Math.atan2(this.y, this.x);
}
/**
* An alias for getR()
*
* @return the length of this
*/
public double length()
{
return this.getR();
}
/** The difference of the vector and rhs: this - rhs */
public Vector2D minus(Vector2D rhs)
{
return new Vector2D(this.x - rhs.x, this.y - rhs.y);
}
/** The sum of the vector and rhs */
public Vector2D plus(Vector2D rhs)
{
return new Vector2D(this.x + rhs.x, this.y + rhs.y);
}
/** Product of the vector and scalar */
public Vector2D scalarMult(double scalar)
{
return new Vector2D(scalar * this.x, scalar * this.y);
}
/*
* (non-Javadoc)
*
* @see java.awt.geom.Point2D.Double#setLocation(double, double)
*/
public void set(double x, double y)
{
super.setLocation(x, y);
}
/**
* Sets the vector given polar arguments.
*
* @param r
* The new radius
* @param t
* The new angle, in radians
*/
public void setPolar(double r, double t)
{
super.setLocation(r * Math.cos(t), r * Math.sin(t));
}
/** Sets the vector's radius, preserving its angle. */
public void setR(double r)
{
double t = this.getTheta();
this.setPolar(r, t);
}
/** Sets the vector's angle, preserving its radius. */
public void setTheta(double t)
{
double r = this.getR();
this.setPolar(r, t);
}
/** Polar version of the vector, with radius in x and angle in y */
public Vector2D toPolar()
{
return new Vector2D(Math.sqrt(this.x * this.x + this.y * this.y), Math.atan2(this.y, this.x));
}
/** Rectangular version of the vector, assuming radius in x and angle in y */
public Vector2D toRect()
{
return new Vector2D(this.x * Math.cos(this.y), this.x * Math.sin(this.y));
}
@Override
public String toString()
{
return "<" + this.x + ", " + this.y + ">";
}
/**
* Returns a new vector with the same direction as the vector but with length 1, except in the case of zero
* vectors, which return a copy of themselves.
*/
public Vector2D unitVector()
{
if (this.getR() != 0)
return new Vector2D(this.x / this.getR(), this.y / this.getR());
return new Vector2D(0, 0);
}
}
}
| 28.173616 | 118 | 0.430249 |
37344361ff276860a029dcacbc741e0f5d8ed94c | 897 | package org.symly.cli.validation;
import java.util.Collection;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
public interface Constraint {
Optional<String> violation();
static Constraint of(String constraint, BooleanSupplier validator) {
return new SimpleConstraint(() -> constraint, validator);
}
static <T> Constraint ofArg(String name, T value, String reason, Predicate<T> validator) {
return new SimpleConstraint(
() -> String.format("Argument <%s> (%s): %s", name, value, reason),
() -> validator.test(value));
}
static <T> Constraint ofArg(String name, Collection<T> values, String reason, Predicate<T> validator) {
return new Constraints(values.stream()
.map(value -> ofArg(name, value, reason, validator))
.toList());
}
}
| 32.035714 | 107 | 0.665552 |
ad84752531838822c122b2d192523e0c6da5b404 | 6,362 | package com.skjanyou.javafx.inter.impl;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Set;
import com.skjanyou.javafx.anno.FxAnnotation.FxController;
import com.skjanyou.javafx.anno.FxAnnotation.FxDecorator;
import com.skjanyou.javafx.anno.FxAnnotation.ResponsiveBean;
import com.skjanyou.javafx.bean.LoadResult;
import com.skjanyou.javafx.core.BeanProperty;
import com.skjanyou.javafx.core.BeanPropertyHelper;
import com.skjanyou.javafx.inter.BeanPropertyBuilder;
import com.skjanyou.javafx.inter.FxControllerFactory;
import com.skjanyou.javafx.inter.FxControllerFactoryProperty;
import com.skjanyou.javafx.inter.FxEventDispatcher;
import com.skjanyou.javafx.inter.FxFXMLLoader;
import com.skjanyou.javafx.inter.JavaFxDecorator;
import com.sun.javafx.fxml.BeanAdapter;
import javafx.beans.property.Property;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
@SuppressWarnings("restriction")
public class DefaultFxControllerFactory implements FxControllerFactory,FxControllerFactoryProperty {
/** 事件分发器 **/
private FxEventDispatcher eventDispatcher;
/** FXML加载器 **/
private FxFXMLLoader fxmlLoader;
/** Controller类 **/
private Class<?> controllerClass;
/** Controller注解类 **/
private FxController fxControllerAnno;
/** Controller类上面的装饰器注解类 **/
private FxDecorator fxDecorator;
/** Controller实例对象 **/
private Object proxyController;
/** Root对象 **/
private Parent parent;
/** 加载的结果,包括Root对象和Controller类 **/
private LoadResult loadResult;
/** 用于展示用的Stage **/
private Stage stage;
/** Scene **/
private Scene scene;
public DefaultFxControllerFactory( Class<?> controllerClass ) {
this.controllerClass = controllerClass;
this.fxControllerAnno = controllerClass.getAnnotation(FxController.class);
if( fxControllerAnno == null ) {
throw new RuntimeException("Controller类上面必须携带FxController注解");
}
this.fxDecorator = controllerClass.getAnnotation(FxDecorator.class);
}
@Override
public FxEventDispatcher getFxEventDispatcher() {
return this.eventDispatcher = this.eventDispatcher == null ? new DefaultFxEventDispatcher(this.proxyController,this.controllerClass) : this.eventDispatcher;
}
@Override
public FxFXMLLoader getFxFXMLLoader() {
return this.fxmlLoader = this.fxmlLoader == null ? new DefaultFxFXMLLoader( this.controllerClass ) : this.fxmlLoader;
}
@Override
public LoadResult createController() {
if( this.loadResult == null ) {
this.loadResult = initControllerBean();
this.parent = loadResult.getParent();
this.proxyController = loadResult.getController();
this.stage = loadResult.getStage();
EventHandler<Event> handler = getFxEventDispatcher().getEventHandler();
this.parent.addEventFilter(Event.ANY, handler);
initFxml( this.proxyController,this.parent );
initDecorator( this.proxyController,this.parent,this.stage );
initEventHandler( this.proxyController,this.parent );
initResponsiveBean( this.proxyController,this.parent );
}
return this.loadResult;
}
/**
* 初始化窗口修饰器
* @param proxyController
* @param parent
*/
private void initDecorator(Object proxyController, Parent parent,Stage stage) {
if( this.fxDecorator == null ) {
this.scene = new Scene(this.parent);
return ;
}
try {
String fxml = this.fxDecorator.fxml();
Class<?> configClass = this.fxDecorator.config();
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(Thread.currentThread().getContextClassLoader().getResource(fxml));
Pane root = fxmlLoader.load();
Object controller = fxmlLoader.getController();
if( controller.getClass() != configClass ) {
throw new IllegalArgumentException(String.format("FXML文件{%s}配置的controller必须为{%s}", fxml,configClass.toString()));
}
JavaFxDecorator decorator = (JavaFxDecorator) controller;
decorator.addContent(parent).initDecorator(stage,this.fxDecorator);
this.scene = new Scene(root);
this.scene.setFill(Color.TRANSPARENT);
this.stage.initStyle(StageStyle.TRANSPARENT);
this.loadResult.setScene(this.scene);
this.loadResult.setParent(root);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 初始化Controller类
*/
protected LoadResult initControllerBean() {
FxFXMLLoader fxmlLoader = getFxFXMLLoader();
return fxmlLoader.loader();
}
protected void initFxml(Object controller,Parent parent) {
}
protected void initEventHandler(Object controller,Parent parent) {
FxEventDispatcher eventDispatcher = getFxEventDispatcher();
parent.addEventFilter(Event.ANY, eventDispatcher.getEventHandler());
}
@SuppressWarnings({ "rawtypes" })
protected void initResponsiveBean(Object controller,Parent parent) {
Field[] fields = this.controllerClass.getDeclaredFields();
for (Field field : fields) {
ResponsiveBean respBean = field.getAnnotation(ResponsiveBean.class);
if( respBean != null ) {
String[] binds = respBean.value();
Class<?> clazz = field.getType();
BeanProperty beanProperty = new BeanPropertyHelper(clazz).builder();
try {
field.setAccessible(true);
Object propertyBean = beanProperty.getBean();
field.set(controller, propertyBean);
for (String express : binds) {
// card_id=#testText.text
String key = express.split("=")[0];
String selector = express.split("=")[1].split("\\.")[0];
String property = express.split("=")[1].split("\\.")[1];
Set<Node> set = parent.lookupAll(selector);
for( Node node : set ) {
BeanAdapter beanAdapter = new BeanAdapter(node);
ObservableValue value = beanAdapter.getPropertyModel(property);
Property p = (Property) value;
BeanPropertyBuilder.bind(propertyBean,key,p);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
| 32.963731 | 158 | 0.718485 |
718b103912a606a255075bf50f3d994bca3be784 | 6,710 | /**
* generated by Xtext 2.13.0
*/
package io.typefox.xtext.langserver.example.myDsl.impl;
import io.typefox.xtext.langserver.example.myDsl.MyDslPackage;
import io.typefox.xtext.langserver.example.myDsl.exclude_attributes_definition;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>exclude attributes definition</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link io.typefox.xtext.langserver.example.myDsl.impl.exclude_attributes_definitionImpl#getAttribute_reference <em>Attribute reference</em>}</li>
* <li>{@link io.typefox.xtext.langserver.example.myDsl.impl.exclude_attributes_definitionImpl#getAttribute_reference2 <em>Attribute reference2</em>}</li>
* </ul>
*
* @generated
*/
public class exclude_attributes_definitionImpl extends MinimalEObjectImpl.Container implements exclude_attributes_definition
{
/**
* The default value of the '{@link #getAttribute_reference() <em>Attribute reference</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttribute_reference()
* @generated
* @ordered
*/
protected static final String ATTRIBUTE_REFERENCE_EDEFAULT = null;
/**
* The cached value of the '{@link #getAttribute_reference() <em>Attribute reference</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttribute_reference()
* @generated
* @ordered
*/
protected String attribute_reference = ATTRIBUTE_REFERENCE_EDEFAULT;
/**
* The default value of the '{@link #getAttribute_reference2() <em>Attribute reference2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttribute_reference2()
* @generated
* @ordered
*/
protected static final String ATTRIBUTE_REFERENCE2_EDEFAULT = null;
/**
* The cached value of the '{@link #getAttribute_reference2() <em>Attribute reference2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttribute_reference2()
* @generated
* @ordered
*/
protected String attribute_reference2 = ATTRIBUTE_REFERENCE2_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected exclude_attributes_definitionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return MyDslPackage.Literals.EXCLUDE_ATTRIBUTES_DEFINITION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getAttribute_reference()
{
return attribute_reference;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAttribute_reference(String newAttribute_reference)
{
String oldAttribute_reference = attribute_reference;
attribute_reference = newAttribute_reference;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE, oldAttribute_reference, attribute_reference));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getAttribute_reference2()
{
return attribute_reference2;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAttribute_reference2(String newAttribute_reference2)
{
String oldAttribute_reference2 = attribute_reference2;
attribute_reference2 = newAttribute_reference2;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE2, oldAttribute_reference2, attribute_reference2));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE:
return getAttribute_reference();
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE2:
return getAttribute_reference2();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE:
setAttribute_reference((String)newValue);
return;
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE2:
setAttribute_reference2((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE:
setAttribute_reference(ATTRIBUTE_REFERENCE_EDEFAULT);
return;
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE2:
setAttribute_reference2(ATTRIBUTE_REFERENCE2_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE:
return ATTRIBUTE_REFERENCE_EDEFAULT == null ? attribute_reference != null : !ATTRIBUTE_REFERENCE_EDEFAULT.equals(attribute_reference);
case MyDslPackage.EXCLUDE_ATTRIBUTES_DEFINITION__ATTRIBUTE_REFERENCE2:
return ATTRIBUTE_REFERENCE2_EDEFAULT == null ? attribute_reference2 != null : !ATTRIBUTE_REFERENCE2_EDEFAULT.equals(attribute_reference2);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (attribute_reference: ");
result.append(attribute_reference);
result.append(", attribute_reference2: ");
result.append(attribute_reference2);
result.append(')');
return result.toString();
}
} //exclude_attributes_definitionImpl
| 28.553191 | 174 | 0.684054 |
5877fc796b0e82279ce1735edfaf611e47a9841c | 180 | package net.opengrabeso.glg2d.examples;
public class LWJGLG2DExample {
public static void main(String[] args) {
LWJGLExampleFactory.display(new G2DExample());
}
}
| 22.5 | 54 | 0.716667 |
e3941f2a8e59c47e2ddbdb46e08d6d26850acf38 | 11,029 | package com.gymnast.view.home.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import com.gymnast.R;
import com.gymnast.data.net.API;
import com.gymnast.utils.CacheUtils;
import com.gymnast.utils.DialogUtil;
import com.gymnast.utils.JSONParseUtil;
import com.gymnast.utils.LiveUtil;
import com.gymnast.utils.PicassoUtil;
import com.gymnast.utils.PostUtil;
import com.gymnast.view.BaseFragment;
import com.gymnast.view.live.activity.MoreLiveActivity;
import com.gymnast.view.live.entity.LiveItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class StandFragment extends BaseFragment implements View.OnClickListener{
@BindView(R.id.stand_tab) TabLayout tab;
@BindView(R.id.stand_vp) ViewPager vp;
ImageView ivBigPic1,ivBigPic2,ivBigPic3,ivBigPic4;
TextView tvLiveNumber,tvTitle,stand_more;
LinearLayout llYuGao;
ArrayList<String> bitmapList=new ArrayList<>();
ArrayList<String> titleList=new ArrayList<>();
ArrayList<String> numberList=new ArrayList<>();
List<LiveItem> liveItems=new ArrayList<>();
int k=0;
LiveItem liveItem=null;
LiveItem liveItemA=null;
LiveItem liveItemB=null;
LiveItem liveItemC=null;
LiveItem liveItemD=null;
public static final int HANDLE_PICS=1;
public static final int DATA_READY_OK=2;
public static final int UPDATE_STATE_OK=3;
public static final int MAINUSER_IN_OK=4;
public static final int MAINUSER_IN_ERROR=5;
public static final int OTHERUSER_IN_OK=6;
public static final int OTHERUSER_IN_ERROR=7;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case UPDATE_STATE_OK:
Toast.makeText(getActivity(), "您开启了直播", Toast.LENGTH_SHORT).show();
LiveUtil.doNext(getActivity(), liveItem);
break;
case MAINUSER_IN_OK:
Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show();
LiveUtil.doNext(getActivity(), liveItem);
break;
case MAINUSER_IN_ERROR:
DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!");
break;
case OTHERUSER_IN_OK:
Toast.makeText(getActivity(),"您已进入直播室",Toast.LENGTH_SHORT).show();
LiveUtil.doNext(getActivity(), liveItem);
break;
case OTHERUSER_IN_ERROR:
DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!");
break;
case DATA_READY_OK:
if (timer==null){
TimerTask task=new TimerTask() {
@Override
public void run() {
k+=1;
handler.sendEmptyMessage(HANDLE_PICS) ;
}
};
timer=new Timer();
timer.schedule(task,0, 5000);
}
break;
case HANDLE_PICS:
int bigIndex=k%4;
int smallIndexA=0;
int smallIndexB=0;
int smallIndexC=0;
switch (bigIndex){
case 0:smallIndexA=1;smallIndexB=2;smallIndexC=3;break;
case 1:smallIndexA=2;smallIndexB=3;smallIndexC=0;break;
case 2:smallIndexA=3;smallIndexB=0;smallIndexC=1;break;
case 3:smallIndexA=0;smallIndexB=1;smallIndexC=2;break;
}
liveItemA=liveItems.get(bigIndex);
liveItemB=liveItems.get(smallIndexA);
liveItemC=liveItems.get(smallIndexB);
liveItemD=liveItems.get(smallIndexC);
String bitmapBig=bitmapList.get(bigIndex);
String bitmapSmallA=bitmapList.get(smallIndexA);
String bitmapSmallB=bitmapList.get(smallIndexB);
String bitmapSmallC=bitmapList.get(smallIndexC);
PicassoUtil.handlePic(getActivity(), bitmapBig, ivBigPic1, 1280, 720);
tvLiveNumber.setText(numberList.get(bigIndex));
tvTitle.setText(titleList.get(bigIndex));
PicassoUtil.handlePic(getActivity(), bitmapSmallA, ivBigPic2, 1280, 720);
PicassoUtil.handlePic(getActivity(), bitmapSmallB, ivBigPic3, 1280, 720);
PicassoUtil.handlePic(getActivity(), bitmapSmallC, ivBigPic4, 1280, 720);
ivBigPic1.invalidate();
tvLiveNumber.invalidate();
tvTitle.invalidate();
ivBigPic2.invalidate();
ivBigPic3.invalidate();
ivBigPic4.invalidate();
llYuGao.setVisibility(View.GONE);
llYuGao.invalidate();
break;
}
}
};
String[] titles = new String[]{"广场", "大咖", "世界杯", "NBA", "WTA", "冠军杯", "亚冠"};
private Timer timer;
public static FragmentStatePagerAdapter pa;
StandSquareFragment standSquareFragment;
ACupFragment aCupFragment;
AsiaCupFragment asiaCupFragment;
BigCupFragment bigCupFragment;
NBAFragment nbaFragment;
WorldCupFragment worldCupFragment;
WTAFragment wtaFragment;
FragmentManager manager;
public static Fragment mCurrentFragment;
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tab.setTabGravity(TabLayout.GRAVITY_FILL);
tab.setTabMode(TabLayout.MODE_SCROLLABLE);
if(savedInstanceState==null){
standSquareFragment = new StandSquareFragment();
bigCupFragment = new BigCupFragment();
worldCupFragment = new WorldCupFragment();
nbaFragment = new NBAFragment();
wtaFragment = new WTAFragment();
aCupFragment = new ACupFragment();
asiaCupFragment = new AsiaCupFragment();
manager= getChildFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(standSquareFragment,""+1);
transaction.add(bigCupFragment, "" + 2);
transaction.add(worldCupFragment, "" + 3);
transaction.add(nbaFragment, "" + 4);
transaction.add(wtaFragment, "" + 5);
transaction.add(aCupFragment, "" + 6);
transaction.add(asiaCupFragment, "" + 7);
transaction.commit();
}
pa = new FragmentStatePagerAdapter(manager) {
@Override public Fragment getItem(int position) {
if (position==0){
return standSquareFragment.newInstance("测试", "" + 1, getActivity());
}else if (position==1){
return bigCupFragment.newInstance("测试", "" + 2,getActivity());
}else if (position==2){
return worldCupFragment.newInstance("测试", "" + 3,getActivity());
}else if (position==3){
return nbaFragment.newInstance("测试", "" + 4,getActivity());
}else if (position==4){
return wtaFragment.newInstance("测试", "" + 5,getActivity());
}else if (position==5){
return aCupFragment.newInstance("测试", "" + 6,getActivity());
}else if (position==6){
return asiaCupFragment.newInstance("测试", "" + 7,getActivity());
}
return null;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
@Override public int getCount() {
return titles.length;
}
@Override public CharSequence getPageTitle(int position) {
return titles[position];
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentFragment = (Fragment)object;
super.setPrimaryItem(container, position, object);
}
};
vp.setAdapter(pa);
vp.setOffscreenPageLimit(6);
tab.setupWithViewPager(vp);
initData();
}
public static Fragment getCurrentFragment() {
return mCurrentFragment;
}
@Override protected int getLayout() {
return R.layout.fragment_stand;
}
@Override protected void initViews(Bundle savedInstanceState) {
ivBigPic1= (ImageView) getActivity().findViewById(R.id.ivBigPic1);
ivBigPic2= (ImageView) getActivity().findViewById(R.id.ivBigPic2);
ivBigPic3= (ImageView) getActivity().findViewById(R.id.ivBigPic3);
ivBigPic4= (ImageView) getActivity().findViewById(R.id.ivBigPic4);
tvLiveNumber= (TextView) getActivity().findViewById(R.id.tvLiveNumber);
stand_more= (TextView) getActivity().findViewById(R.id.stand_more);
tvTitle= (TextView) getActivity().findViewById(R.id.tvTitle);
llYuGao= (LinearLayout) getActivity().findViewById(R.id.llYuGao);
}
@Override protected void initListeners() {
ivBigPic1.setOnClickListener(this);
ivBigPic2.setOnClickListener(this);
ivBigPic3.setOnClickListener(this);
ivBigPic4.setOnClickListener(this);
stand_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().startActivity(new Intent(getActivity(), MoreLiveActivity.class));
}
});
}
protected void initData() {
ArrayList<String> cacheData= (ArrayList<String>) CacheUtils.readJson(getActivity(), StandFragment.this.getClass().getName() + ".json");
if (cacheData==null||cacheData.size()==0) {
new Thread() {
@Override
public void run() {
String uri = API.BASE_URL + "/v1/deva/get";
HashMap<String, String> parms = new HashMap<String, String>();
parms.put("area", "2");
String result = PostUtil.sendPostMessage(uri, parms);
JSONParseUtil.parseNetDataStandBanner(getActivity(),result,StandFragment.this.getClass().getName() + ".json",bitmapList,titleList,numberList,liveItems,handler,DATA_READY_OK);
}
}.start();
}else {
JSONParseUtil.parseLocalDataStandBanner(getActivity(), StandFragment.this.getClass().getName() + ".json", bitmapList, titleList, numberList, liveItems, handler, DATA_READY_OK);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivBigPic1:
liveItem=liveItemA;
LiveUtil.doIntoLive(getActivity(), handler, liveItem);
break;
case R.id.ivBigPic2:
liveItem=liveItemB;
LiveUtil.doIntoLive(getActivity(), handler, liveItem);
break;
case R.id.ivBigPic3:
liveItem=liveItemC;
LiveUtil.doIntoLive(getActivity(), handler, liveItem);
break;
case R.id.ivBigPic4:
liveItem=liveItemD;
LiveUtil.doIntoLive(getActivity(), handler, liveItem);
break;
}
}
@Override
public void onDestroy() {
handler.removeMessages(HANDLE_PICS);
timer.cancel();
super.onDestroy();
}
}
| 39.530466 | 186 | 0.673769 |
1a9e065f4d888ed479bb226ffd65a77d5665a4f7 | 2,776 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.be.components.utils;
import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RelationshipInfo;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import java.util.Collections;
public class RelationsBuilder {
private RequirementCapabilityRelDef relation;
public RelationsBuilder() {
relation = new RequirementCapabilityRelDef();
RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo();
RelationshipImpl relationship = new RelationshipImpl();
requirementAndRelationshipPair.setRelationships(relationship);
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
capReqRel.setRelation(requirementAndRelationshipPair);
relation.setRelationships(Collections.singletonList(capReqRel));
}
public RelationsBuilder setFromNode(String fromNode) {
relation.setFromNode(fromNode);
return this;
}
public RelationsBuilder setRequirementName(String reqName) {
relation.resolveSingleRelationship().getRelation().setRequirement(reqName);
return this;
}
public RelationsBuilder setRelationType(String type) {
relation.resolveSingleRelationship().getRelation().getRelationship().setType(type);
return this;
}
public RelationsBuilder setCapabilityUID(String uid) {
relation.resolveSingleRelationship().getRelation().setCapabilityUid(uid);
return this;
}
public RelationsBuilder setToNode(String toNode) {
relation.setToNode(toNode);
return this;
}
public RequirementCapabilityRelDef build() {
return relation;
}
}
| 37.513514 | 94 | 0.661383 |
8f6fa8fe7820a7b7a93063df2a3c08f31a6a7e7d | 828 | package ca.gc.aafc.seqdb.api.testsupport.factories;
import java.util.UUID;
import ca.gc.aafc.seqdb.api.entities.sanger.PcrBatchItem;
public class PcrBatchItemFactory implements TestableEntityFactory<PcrBatchItem> {
@Override
public PcrBatchItem getEntityInstance() {
return newPcrBatchItem().build();
}
/**
* Static method that can be called to return a configured builder that can be further customized
* to return the actual entity object, call the .build() method on a builder.
* @return Pre-configured builder with all mandatory fields set
*/
public static PcrBatchItem.PcrBatchItemBuilder newPcrBatchItem() {
return PcrBatchItem.builder()
.uuid(UUID.randomUUID())
.createdBy("test user")
.wellColumn(5)
.wellRow("B")
.group("dina");
}
}
| 26.709677 | 99 | 0.705314 |
87ee44b0593e3a6417e53aa29ce43c96651177e8 | 585 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (almaslvl@gmail.com).
* See LICENSE for details.
*/
package com.almasb.fxgl.core.util;
/**
* Represents a predicate (boolean-valued function) of one argument.
*
* @param <T> the type of the input to the predicate
*/
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param arg the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T arg);
}
| 22.5 | 72 | 0.651282 |
c3f505bc2b9292c9c1a879a454e9d1fe6536af12 | 313 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.coviam.t3login.service;
import com.coviam.t3login.dto.AccessTokenDTO;
import com.coviam.t3login.entity.Login;
public interface GoogleService {
Login getGmailDetails(AccessTokenDTO var1);
}
| 22.357143 | 60 | 0.779553 |
0c71dde758ede81199bd86bd10de6359ea955417 | 6,079 | /*
* 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.iceberg.expressions;
import java.math.BigDecimal;
import java.time.DateTimeException;
import java.util.UUID;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.data.TimeConversions;
import org.apache.iceberg.types.Types;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.junit.Assert;
import org.junit.Test;
public class TestStringLiteralConversions {
@Test
public void testStringToStringLiteral() {
Literal<CharSequence> string = Literal.of("abc");
Assert.assertSame("Should return same instance", string, string.to(Types.StringType.get()));
}
@Test
public void testStringToDateLiteral() {
Literal<CharSequence> dateStr = Literal.of("2017-08-18");
Literal<Integer> date = dateStr.to(Types.DateType.get());
// use Avro's date conversion to validate the result
Schema avroSchema = LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT));
TimeConversions.DateConversion avroConversion = new TimeConversions.DateConversion();
int avroValue = avroConversion.toInt(
new LocalDate(2017, 8, 18),
avroSchema, avroSchema.getLogicalType());
Assert.assertEquals("Date should match", avroValue, (int) date.value());
}
@Test
public void testStringToTimeLiteral() {
// use Avro's time conversion to validate the result
Schema avroSchema = LogicalTypes.timeMicros().addToSchema(Schema.create(Schema.Type.LONG));
TimeConversions.LossyTimeMicrosConversion avroConversion =
new TimeConversions.LossyTimeMicrosConversion();
Literal<CharSequence> timeStr = Literal.of("14:21:01.919");
Literal<Long> time = timeStr.to(Types.TimeType.get());
long avroValue = avroConversion.toLong(
new LocalTime(14, 21, 1, 919),
avroSchema, avroSchema.getLogicalType());
Assert.assertEquals("Time should match", avroValue, (long) time.value());
}
@Test
public void testStringToTimestampLiteral() {
// use Avro's timestamp conversion to validate the result
Schema avroSchema = LogicalTypes.timestampMicros().addToSchema(Schema.create(Schema.Type.LONG));
TimeConversions.LossyTimestampMicrosConversion avroConversion =
new TimeConversions.LossyTimestampMicrosConversion();
// Timestamp with explicit UTC offset, +00:00
Literal<CharSequence> timestampStr = Literal.of("2017-08-18T14:21:01.919+00:00");
Literal<Long> timestamp = timestampStr.to(Types.TimestampType.withZone());
long avroValue = avroConversion.toLong(
new LocalDateTime(2017, 8, 18, 14, 21, 1, 919).toDateTime(DateTimeZone.UTC),
avroSchema, avroSchema.getLogicalType());
Assert.assertEquals("Timestamp should match", avroValue, (long) timestamp.value());
// Timestamp without an explicit zone should be UTC (equal to the previous converted value)
timestampStr = Literal.of("2017-08-18T14:21:01.919");
timestamp = timestampStr.to(Types.TimestampType.withoutZone());
Assert.assertEquals("Timestamp without zone should match UTC",
avroValue, (long) timestamp.value());
// Timestamp with an explicit offset should be adjusted to UTC
timestampStr = Literal.of("2017-08-18T14:21:01.919-07:00");
timestamp = timestampStr.to(Types.TimestampType.withZone());
avroValue = avroConversion.toLong(
new LocalDateTime(2017, 8, 18, 21, 21, 1, 919).toDateTime(DateTimeZone.UTC),
avroSchema, avroSchema.getLogicalType());
Assert.assertEquals("Timestamp without zone should match UTC",
avroValue, (long) timestamp.value());
}
@Test(expected = DateTimeException.class)
public void testTimestampWithZoneWithoutZoneInLiteral() {
// Zone must be present in literals when converting to timestamp with zone
Literal<CharSequence> timestampStr = Literal.of("2017-08-18T14:21:01.919");
timestampStr.to(Types.TimestampType.withZone());
}
@Test(expected = DateTimeException.class)
public void testTimestampWithoutZoneWithZoneInLiteral() {
// Zone must not be present in literals when converting to timestamp without zone
Literal<CharSequence> timestampStr = Literal.of("2017-08-18T14:21:01.919+07:00");
timestampStr.to(Types.TimestampType.withoutZone());
}
@Test
public void testStringToUUIDLiteral() {
UUID expected = UUID.randomUUID();
Literal<CharSequence> uuidStr = Literal.of(expected.toString());
Literal<UUID> uuid = uuidStr.to(Types.UUIDType.get());
Assert.assertEquals("UUID should match", expected, uuid.value());
}
@Test
public void testStringToDecimalLiteral() {
BigDecimal expected = new BigDecimal("34.560");
Literal<CharSequence> decimalStr = Literal.of("34.560");
Literal<BigDecimal> decimal = decimalStr.to(Types.DecimalType.of(9, 3));
Assert.assertEquals("Decimal should have scale 3", 3, decimal.value().scale());
Assert.assertEquals("Decimal should match", expected, decimal.value());
Assert.assertNull("Wrong scale in conversion should return null",
decimalStr.to(Types.DecimalType.of(9, 2)));
Assert.assertNull("Wrong scale in conversion should return null",
decimalStr.to(Types.DecimalType.of(9, 4)));
}
}
| 41.074324 | 100 | 0.734331 |
9ddf9f5293002d5f5da1f7a64c93a439ee8ea01c | 2,488 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.spring.initializr.generator.buildsystem.maven;
import io.spring.initializr.generator.buildsystem.Build;
import io.spring.initializr.generator.buildsystem.BuildItemResolver;
import io.spring.initializr.generator.buildsystem.MavenRepositoryContainer;
import io.spring.initializr.generator.buildsystem.maven.MavenBuildSettings.Builder;
/**
* Maven-specific {@linkplain Build build configuration}.
*
* @author Andy Wilkinson
* @author Stephane Nicoll
*/
public class MavenBuild extends Build {
private final MavenBuildSettings.Builder settings = new Builder();
private final MavenResourceContainer resources = new MavenResourceContainer();
private final MavenResourceContainer testResources = new MavenResourceContainer();
private final MavenPluginContainer plugins = new MavenPluginContainer();
public MavenBuild(BuildItemResolver buildItemResolver) {
super(buildItemResolver);
}
public MavenBuild() {
this(null);
}
@Override
public MavenBuildSettings.Builder settings() {
return this.settings;
}
@Override
public MavenBuildSettings getSettings() {
return this.settings.build();
}
/**
* Return the {@linkplain MavenResource resource container} to use to configure main
* resources.
* @return the {@link MavenRepositoryContainer} for main resources
*/
public MavenResourceContainer resources() {
return this.resources;
}
/**
* Return the {@linkplain MavenResource resource container} to use to configure test
* resources.
* @return the {@link MavenRepositoryContainer} for test resources
*/
public MavenResourceContainer testResources() {
return this.testResources;
}
/**
* Return the {@linkplain MavenPluginContainer plugin container} to use to configure
* plugins.
* @return the {@link MavenPluginContainer}
*/
public MavenPluginContainer plugins() {
return this.plugins;
}
}
| 28.930233 | 85 | 0.764469 |
3aab9fcd4ae6bdcc83ec7aebbaea60da504e19f4 | 2,102 | /*-
* -\-\-
* FastForward Core
* --
* Copyright (C) 2016 - 2018 Spotify AB
* --
* 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.spotify.ffwd.serializer;
import com.spotify.ffwd.cache.WriteCache;
import com.spotify.ffwd.model.Metric;
import com.spotify.proto.Spotify100;
import java.util.Collection;
import org.xerial.snappy.Snappy;
/**
* Spotify100ProtoSerializer is intended to reduce the amount of data transferred between
* the publisher and the consumer. It useful when being used with Google Pubsub, because the
* client does not have native compression like Kafka.
*
* Compression is done with the snappy library via JNI.
*/
public class Spotify100ProtoSerializer implements Serializer {
@Override
public byte[] serialize(final Metric metric) throws Exception {
throw new UnsupportedOperationException("Not supported");
}
@Override
public byte[] serialize(Collection<Metric> metrics, WriteCache writeCache) throws Exception {
final Spotify100.Batch.Builder batch = Spotify100.Batch.newBuilder();
for (Metric metric : metrics) {
if (!writeCache.checkCacheOrSet(metric)) {
batch.addMetric(serializeMetric(metric));
}
}
return Snappy.compress(batch.build().toByteArray());
}
private Spotify100.Metric serializeMetric(final Metric metric) {
return Spotify100.Metric.newBuilder()
.setKey(metric.getKey())
.setTime(metric.getTime().getTime())
.setValue(metric.getValue())
.putAllTags(metric.getTags())
.putAllResource(metric.getResource())
.build();
}
}
| 32.84375 | 95 | 0.724072 |
e7673ac9c8298dda81bf885f163ac7bd18dc283f | 1,769 | package com.boyscouts.util.schedule;
/*
* Tim Cutler
*/
public class Slot
{
/**
*
* @uml.property name="race"
*/
private int race = -1;
/**
*
* @uml.property name="track"
*/
private int track = -1;
public static final Player empty = new Player();
public static final Player emptyReserved = new Player();
/**
*
* @uml.property name="player"
* @uml.associationEnd multiplicity="(1 1)" inverse="slots:com.boyscouts.util.schedule.Player"
*/
Player player = null;
public Slot( int race, int track )
{
this.race = race;
this.track = track;
player = empty;
}
public String toString()
{
return "slot(" + race + "," + track + ")";
}
/**
*
* @uml.property name="player"
*/
public Player getPlayer()
{
return player;
}
/**
*
* @uml.property name="race"
*/
public int getRace()
{
return race;
}
/**
*
* @uml.property name="track"
*/
public int getTrack()
{
return track;
}
public Player assignPlayer( Player player )
{
Player old = this.player;
this.player.removeSlot(this);
this.player = player;
this.player.assignSlot(this);
return old;
}
public Player setEmpty()
{
Player old = this.player;
this.player.removeSlot(this);
this.player = empty;
return old;
}
public Player setEmptyReserved()
{
Player old = this.player;
this.player.removeSlot(this);
this.player = emptyReserved;
return old;
}
public boolean IsEmpty()
{
return this.player == empty;
}
public boolean IsEmptyReserved()
{
return this.player == emptyReserved;
}
}
| 16.847619 | 97 | 0.554551 |
87adc9d2de7cf2c56fc147713995bd43f8f71eaa | 2,724 | package org.jnd.microservices.sso.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@CrossOrigin
@RestController
@RequestMapping("/api")
public class SSOController {
private static final Logger log = LoggerFactory.getLogger(SSOController.class);
@Value( "${sso.server}" )
String sso_server;
@Value( "${sso.realm}" )
String realm;
@Value( "${sso.client_id}" )
String client_id;
@Value( "${sso.client_secret}" )
String client_secret;
@Value( "${sso.redirect_uri}" )
String redirect_uri;
@Value( "${sso.grant_type}" )
String grant_type;
@RequestMapping(value = "/handle-oauth", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> login(@RequestHeader HttpHeaders headers, @RequestParam(name = "code") String code) {
log.info("handle-oauth");
log.info("code : "+code);
log.info("sso_server : "+sso_server);
String sso_uri = sso_server+"auth/realms/"+realm+"/protocol/openid-connect/token";
log.info("sso_uri : "+sso_uri);
String post_body = "grant_type="+grant_type+"&redirect_uri="+redirect_uri+"&client_id="+client_id+"&client_secret="+client_secret+"&code="+code;
log.info("post_body : "+post_body);
for (String key : headers.keySet()) {
log.info(key+" : "+headers.get(key));
}
HttpHeaders outheaders = new HttpHeaders();
outheaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
HttpEntity<String> request = new HttpEntity<>(post_body, outheaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> exchange = null;
try {
exchange =
restTemplate.exchange(
sso_uri,
HttpMethod.POST,
request,
String.class);
}
catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<String>("Error", null, HttpStatus.SERVICE_UNAVAILABLE);
}
String response = exchange.getBody();
return new ResponseEntity<String>(response, null, HttpStatus.OK);
}
@RequestMapping(value = "/health", method = RequestMethod.GET)
public String ping() {
return "OK";
}
}
| 30.954545 | 152 | 0.640602 |
c653683b955be28f892781783bc47d97a1181303 | 24,292 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2007-2013 SSAC(Systems of Social Accounting Consortium)
* <author> Yasunari Ishizuka (PieCake,Inc.)
* <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> Yuji Onuki (Statistics Bureau)
* <author> Shungo Sakaki (Tokyo University of Technology)
* <author> Akira Sasaki (HOSEI UNIVERSITY)
* <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)FSDateTimeFormatsTest.java 2.2.1 2015/07/20
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.aadl.runtime.util.internal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import junit.framework.TestCase;
/**
* Test for FSDateTimeFormats class.
* @version 2.2.1
* @since 2.2.1
*/
public class FSDateTimeFormatsTest extends TestCase
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
//------------------------------------------------------------
// Internal methods
//------------------------------------------------------------
protected int calcHashCode(FSDateTimeFormats dtf) {
int h = Boolean.valueOf(dtf._useDefault).hashCode();
if (dtf._patterns != null && !dtf._patterns.isEmpty()) {
for (SimpleDateFormat sdf : dtf._patterns) {
h = 31 * h + (sdf==null ? 0 : sdf.hashCode());
}
} else {
h = 31 * h + 0;
}
return h;
}
protected String toEnquotedString(String fieldString) {
if (fieldString == null)
return null;
if (fieldString.isEmpty())
return fieldString;
if (fieldString.indexOf(',') < 0 && fieldString.indexOf('\"') < 0) {
return fieldString;
}
fieldString = fieldString.replaceAll("\\\"", "\"\"");
return "\"" + fieldString + "\"";
}
//------------------------------------------------------------
// Inner classes
//------------------------------------------------------------
static protected class TestPatternData {
public final String inputString;
public final String patternString;
public final SimpleDateFormat dtformat;
public final String validDateTime;
public final String invalidDateTime;
public TestPatternData(String strInputString, String strPatternString, String strValidDateTime, String strInvalidDateTime) {
inputString = strInputString;
patternString = strPatternString;
dtformat = (strPatternString==null ? null : new SimpleDateFormat(strPatternString));
validDateTime = strValidDateTime;
invalidDateTime = strInvalidDateTime;
}
}
//------------------------------------------------------------
// Test data
//------------------------------------------------------------
// invalid default datetimes
static protected final String[] invalidDefaultValues = {
null,
"",
"20150718 12:34:56.123",
"2015/07,18 12:34:56.123",
"2015_07_18 12:34:56.123",
"2015-07-18 12-34-56.123",
"2015/07/18 123456.123",
"2015",
" 2015 07 18 12 34 56 123",
"12:34:56.123",
};
// default datetimes
static protected final String[][] validDefaultValues = {
{"2015-07-18 12:34:56.123", "2015/07/18 12:34:56.123"},
{"2015.07.18 12:34:56.123", "2015/07/18 12:34:56.123"},
{"2015/07/18 12:34:56.123", "2015/07/18 12:34:56.123"},
{" 2015-07-18 12:34:56.123", "2015/07/18 12:34:56.123"},
{"2015.7.18 12:4:56", "2015/07/18 12:04:56.000"},
{" 2015/7/8 12:34 ", "2015/07/08 12:34:00.000"},
{"2015/7/8", "2015/07/08 00:00:00.000"},
};
// custom patterns
static protected final TestPatternData[] customPatterns = {
new TestPatternData("yyyy.MM.dd G 'at' HH:mm:ss z", "yyyy.MM.dd G 'at' HH:mm:ss z",
"2001.07.04 西暦 at 12:08:56 JST", "2001.07.04 AD mat 12:08:56 PDT"),
new TestPatternData("\" yyyy.MM.dd G \"\"'at'\"\" HH:mm:ss z \"", "yyyy.MM.dd G \"'at'\" HH:mm:ss z",
"2001.07.04 西暦 \"at\" 12:08:56 JST", "2001.07.04 AD at 12:08:56 PDT"),
new TestPatternData("\"EEE, MMM d, ''yy\"", "EEE, MMM d, ''yy",
"水, 7 4, '01", "Wed, Jul 4, \"01"),
new TestPatternData("\"EEE, MMM d, \"\"yy\"", "EEE, MMM d, \"yy",
"水, 7 4, \"01", "Wed, Jul 4, '01"),
new TestPatternData("yyyyy.MMMMM.dd GGG hh:mm aaa", "yyyyy.MMMMM.dd GGG hh:mm aaa",
"02001.7月.04 西暦 12:08 午後", "02001.July.04 12:08 PM"),
new TestPatternData("\" yyyyy.MMMMM.dd GGG hh:mm aaa\"", "yyyyy.MMMMM.dd GGG hh:mm aaa",
"02001.7月.04 西暦 12:08 午後", "02001.July.04 12:08 PM"),
new TestPatternData("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"2001-07-04T12:08:56.235+0900", "2001-07-04 12:08:56.235-0700"),
new TestPatternData("\"yyyy-MM-dd\"\"'T'\"\"HH:mm:ss.SSSZ \"", "yyyy-MM-dd\"'T'\"HH:mm:ss.SSSZ",
"2001-07-04\"T\"12:08:56.235+0900", "2001-07-04T12:08:56.235-0700"),
};
//------------------------------------------------------------
// Test cases
//------------------------------------------------------------
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#isSingleDefaultPatternString(java.lang.String)}.
*/
public void testIsSingleDefaultPatternString() {
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString("default"));
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString("DEFAULT"));
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString("dEfAuLt"));
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString("DeFaUlT"));
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString(" default "));
assertTrue(FSDateTimeFormats.isSingleDefaultPatternString(" DEFAULT "));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString(null));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString(""));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString("def ault"));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString("hoge"));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString(" "));
assertFalse(FSDateTimeFormats.isSingleDefaultPatternString("yyyy/mm/dd hh:MM:ss.sss"));
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#isValidSinglePatternString(java.lang.String)}.
*/
public void testIsValidSinglePatternString() {
assertTrue(FSDateTimeFormats.isValidSinglePatternString("default"));
assertTrue(FSDateTimeFormats.isValidSinglePatternString("DEFAULT"));
assertTrue(FSDateTimeFormats.isValidSinglePatternString("dEfAuLt"));
assertTrue(FSDateTimeFormats.isValidSinglePatternString("DeFaUlT"));
assertTrue(FSDateTimeFormats.isValidSinglePatternString("yyyy-MM-dd HH:mm:ss.SSS"));
assertTrue(FSDateTimeFormats.isValidSinglePatternString(" yyyy "));
assertTrue(FSDateTimeFormats.isValidSinglePatternString("HH''mm\"ss"));
assertFalse(FSDateTimeFormats.isValidSinglePatternString(null));
assertFalse(FSDateTimeFormats.isValidSinglePatternString(""));
assertFalse(FSDateTimeFormats.isValidSinglePatternString("abcdefG"));
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#FSDateTimeFormats()}.
*/
public void testFSDateTimeFormats() {
FSDateTimeFormats dtf = new FSDateTimeFormats();
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#FSDateTimeFormats(java.lang.String)}.
*/
public void testFSDateTimeFormatsString() {
FSDateTimeFormats dtf;
// check null
dtf = new FSDateTimeFormats(null);
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check empty
dtf = new FSDateTimeFormats("");
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check only space
dtf = new FSDateTimeFormats(" ");
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check multi fields, but space only
dtf = new FSDateTimeFormats(" , , , ");
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check default
dtf = new FSDateTimeFormats(" deFAUlt ");
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertTrue(dtf._useDefault);
assertNull(dtf._patterns);
// check custom only
StringBuffer buffer1 = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
for (int index = 0; index < customPatterns.length; ++index) {
String strHeader = "index[" + index + "]:";
TestPatternData pdata = customPatterns[index];
dtf = new FSDateTimeFormats(pdata.inputString);
assertFalse(strHeader, dtf._useDefault);
assertNotNull(strHeader, dtf._patterns);
assertEquals(strHeader, 1, dtf._patterns.size());
String strPattern = dtf.toPatternsString(false);
assertEquals(strHeader, pdata.patternString, strPattern);
if (index > 0) {
buffer1.append(',');
buffer2.append(',');
}
buffer1.append(pdata.inputString);
buffer2.append(pdata.patternString);
}
String strAllInputString = buffer1.toString();
String strAllPatternString = buffer2.toString();
dtf = new FSDateTimeFormats(strAllInputString);
assertFalse(dtf._useDefault);
assertNotNull(dtf._patterns);
assertEquals(customPatterns.length, dtf._patterns.size());
assertEquals(strAllPatternString, dtf.toPatternsString(false));
// with default
strAllInputString = strAllInputString + ",DeFaULt," + strAllInputString;
strAllPatternString = strAllPatternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + strAllPatternString;
dtf = new FSDateTimeFormats(strAllInputString);
assertTrue(dtf._useDefault);
assertNotNull(dtf._patterns);
assertEquals(customPatterns.length*2+1, dtf._patterns.size());
assertEquals(strAllPatternString, dtf.toPatternsString(false));
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#isOnlyDefaultFormat()}.
*/
public void testIsOnlyDefaultFormat() {
FSDateTimeFormats dtf;
// check null
dtf = new FSDateTimeFormats(null);
assertTrue(dtf.isOnlyDefaultFormat());
// check empty
dtf = new FSDateTimeFormats("");
assertTrue(dtf.isOnlyDefaultFormat());
// check only space
dtf = new FSDateTimeFormats(" ");
assertTrue(dtf.isOnlyDefaultFormat());
// check multi fields, but space only
dtf = new FSDateTimeFormats(" , , , ");
assertTrue(dtf.isOnlyDefaultFormat());
// check default
dtf = new FSDateTimeFormats(" deFAUlt ");
assertTrue(dtf.isOnlyDefaultFormat());
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertTrue(dtf.isOnlyDefaultFormat());
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertFalse(dtf.isOnlyDefaultFormat());
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertFalse(dtf.isOnlyDefaultFormat());
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#isUseDefaultFormats()}.
*/
public void testIsUseDefaultFormats() {
FSDateTimeFormats dtf;
// check null
dtf = new FSDateTimeFormats(null);
assertTrue(dtf.isUseDefaultFormats());
// check empty
dtf = new FSDateTimeFormats("");
assertTrue(dtf.isUseDefaultFormats());
// check only space
dtf = new FSDateTimeFormats(" ");
assertTrue(dtf.isUseDefaultFormats());
// check multi fields, but space only
dtf = new FSDateTimeFormats(" , , , ");
assertTrue(dtf.isUseDefaultFormats());
// check default
dtf = new FSDateTimeFormats(" deFAUlt ");
assertTrue(dtf.isUseDefaultFormats());
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertTrue(dtf.isUseDefaultFormats());
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertFalse(dtf.isUseDefaultFormats());
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertTrue(dtf.isUseDefaultFormats());
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#hashCode()}.
*/
public void testHashCode() {
FSDateTimeFormats dtf;
// check default
dtf = new FSDateTimeFormats();
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check null
dtf = new FSDateTimeFormats(null);
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check empty
dtf = new FSDateTimeFormats("");
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check only space
dtf = new FSDateTimeFormats(" ");
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check multi fields, but space only
dtf = new FSDateTimeFormats(" , , , ");
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check default
dtf = new FSDateTimeFormats(" deFAUlt ");
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(calcHashCode(dtf), dtf.hashCode());
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(calcHashCode(dtf), dtf.hashCode());
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#equals(java.lang.Object)}.
*/
public void testEqualsObject() {
// check default
FSDateTimeFormats dtf11 = new FSDateTimeFormats();
FSDateTimeFormats dtf21 = new FSDateTimeFormats();
// check default multi fields
FSDateTimeFormats dtf12 = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
FSDateTimeFormats dtf22 = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
FSDateTimeFormats dtf13 = new FSDateTimeFormats(strInputString);
FSDateTimeFormats dtf23 = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf13.toPatternsString(false));
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
FSDateTimeFormats dtf14 = new FSDateTimeFormats(strInputString);
FSDateTimeFormats dtf24 = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf14.toPatternsString(false));
// chekc equals
assertEquals(dtf11, dtf21);
assertEquals(dtf12, dtf22);
assertEquals(dtf13, dtf23);
assertEquals(dtf14, dtf24);
assertEquals(dtf11, dtf12);
assertFalse(dtf11.equals(dtf13));
assertFalse(dtf13.equals(dtf14));
assertFalse(dtf14.equals(dtf11));
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#toPatternsString(boolean)}.
*/
public void testToPatternsString() {
FSDateTimeFormats dtf;
// check default
dtf = new FSDateTimeFormats();
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(true));
// check null
dtf = new FSDateTimeFormats(null);
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(true));
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(true));
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
String strEnquotString = toEnquotedString(customPatterns[0].patternString) + "," + toEnquotedString(customPatterns[1].patternString);
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(strEnquotString, dtf.toPatternsString(true));
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
strEnquotString = toEnquotedString(customPatterns[0].patternString)
+ "," + toEnquotedString(FSDateTimeFormats.DefaultSpecifier)
+ "," + toEnquotedString(customPatterns[1].patternString);
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(strEnquotString, dtf.toPatternsString(true));
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#toString()}.
*/
public void testToString() {
FSDateTimeFormats dtf;
// check default
dtf = new FSDateTimeFormats();
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toString());
// check null
dtf = new FSDateTimeFormats(null);
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toString());
// check default multi fields
dtf = new FSDateTimeFormats(" deFAUlt ,default,\"default\", DEFAULT");
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toPatternsString(false));
assertEquals(FSDateTimeFormats.DefaultSpecifier, dtf.toString());
// check no default fields
String strInputString = customPatterns[0].inputString + "," + customPatterns[1].inputString;
String strPatternString = customPatterns[0].patternString + "," + customPatterns[1].patternString;
String strEnquotString = toEnquotedString(customPatterns[0].patternString) + "," + toEnquotedString(customPatterns[1].patternString);
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(strEnquotString, dtf.toString());
// check mixed fields
strInputString = customPatterns[0].inputString + ",DeFauLT," + customPatterns[1].inputString;
strPatternString = customPatterns[0].patternString + "," + FSDateTimeFormats.DefaultSpecifier + "," + customPatterns[1].patternString;
strEnquotString = toEnquotedString(customPatterns[0].patternString)
+ "," + toEnquotedString(FSDateTimeFormats.DefaultSpecifier)
+ "," + toEnquotedString(customPatterns[1].patternString);
dtf = new FSDateTimeFormats(strInputString);
assertEquals(strPatternString, dtf.toPatternsString(false));
assertEquals(strEnquotString, dtf.toString());
}
/**
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#parse(java.lang.String)}.
* Test method for {@link ssac.aadl.runtime.util.internal.FSDateTimeFormats#format(java.util.Calendar)}.
*/
public void testFormatAndParse() {
FSDateTimeFormats dtf;
// default
dtf = new FSDateTimeFormats();
//--- invalid default format
for (int index = 0; index < invalidDefaultValues.length; ++index) {
String strHeader = "index[" + index + "]:";
Calendar cal = dtf.parse(invalidDefaultValues[index]);
assertNull(strHeader, cal);
}
//--- valid default format
for (int index = 0; index < validDefaultValues.length; ++index) {
String strHeader = "index[" + index + "]:";
String strInput = validDefaultValues[index][0];
String strOutput = validDefaultValues[index][1];
Calendar cal = dtf.parse(strInput);
assertNotNull(strHeader, cal);
String strResult = dtf.format(cal);
assertEquals(strHeader, strOutput, strResult);
}
// custom patterns
StringBuffer buffer1 = new StringBuffer();
for (int index = 0; index < customPatterns.length; ++index) {
String strHeader = "index[" + index + "]:";
TestPatternData pdata = customPatterns[index];
String strInvalid = pdata.invalidDateTime;
dtf = new FSDateTimeFormats(pdata.inputString);
//--- invalid
Calendar cal = dtf.parse(strInvalid);
assertNull(strHeader, cal);
//--- valid
String strValid = pdata.validDateTime;
cal = dtf.parse(strValid);
assertNotNull(strHeader, cal);
String strFormatted = dtf.format(cal);
assertEquals(strHeader, strValid, strFormatted);
//--- current
Calendar calCurrent = Calendar.getInstance();
String strCurrent = dtf.format(calCurrent);
assertNotNull(strHeader, strCurrent);
cal = dtf.parse(strCurrent);
assertNotNull(strHeader, cal);
String strResult = dtf.format(cal);
assertEquals(strHeader, strCurrent, strResult);
if (index > 0) {
buffer1.append(',');
}
buffer1.append(pdata.inputString);
}
// check all patterns
String strValid = "2001-07-04\"T\"12:08:56.235+0900";
String strAnswer = "2001.07.04 西暦 at 12:08:56 JST";
String strAllInputString = buffer1.toString();
dtf = new FSDateTimeFormats(strAllInputString);
Calendar cal = dtf.parse(strValid);
assertNotNull(cal);
String strResult = dtf.format(cal);
assertEquals(strAnswer, strResult);
// check first default
strAnswer = "2001/07/04 12:08:56.235";
dtf = new FSDateTimeFormats("default," + strAllInputString);
assertTrue(dtf.isUseDefaultFormats());
assertFalse(dtf.isOnlyDefaultFormat());
cal = dtf.parse(strValid);
assertNotNull(cal);
strResult = dtf.format(cal);
assertEquals(strAnswer, strResult);
}
}
| 39.307443 | 136 | 0.69208 |
6c5bd8a774dbefa4688b5da29b3125969cd96e52 | 3,521 | /*
* Copyright 2020 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.protobuf;
import com.google.protobuf.GeneratedMessageV3;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.internal.serialization.impl.ObjectDataInputStream;
import com.hazelcast.internal.serialization.impl.ObjectDataOutputStream;
import com.hazelcast.jet.protobuf.Messages.Person;
import com.hazelcast.nio.serialization.StreamSerializer;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ProtobufSerializerTest {
private static final InternalSerializationService SERIALIZATION_SERVICE =
new DefaultSerializationServiceBuilder().build();
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void when_instantiatedWithArbitraryClass_then_throws() {
// When
// Then
assertThatThrownBy(() -> new ProtobufSerializer(Object.class, 1) { })
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void when_instantiatedWithTypeId_then_returnsIt() {
// Given
int typeId = 13;
// When
StreamSerializer<Person> serializer = ProtobufSerializer.from(Person.class, typeId);
// Then
assertThat(serializer.getTypeId()).isEqualTo(typeId);
}
@Test
public void when_serializes_then_isAbleToDeserialize() {
// Given
Person original = Person.newBuilder().setName("Joe").setAge(18).build();
StreamSerializer<Person> serializer = ProtobufSerializer.from(Person.class, 1);
// When
Person transformed = deserialize(serializer, serialize(serializer, original));
// Then
assertThat(transformed).isEqualTo(original);
}
private static <T extends GeneratedMessageV3> byte[] serialize(StreamSerializer<T> serializer, T object) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectDataOutputStream output = new ObjectDataOutputStream(baos, SERIALIZATION_SERVICE)) {
serializer.write(output, object);
return baos.toByteArray();
} catch (IOException ioe) {
throw sneakyThrow(ioe);
}
}
private static <T extends GeneratedMessageV3> T deserialize(StreamSerializer<T> serializer, byte[] bytes) {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectDataInputStream input = new ObjectDataInputStream(bais, SERIALIZATION_SERVICE)) {
return serializer.read(input);
} catch (IOException ioe) {
throw sneakyThrow(ioe);
}
}
}
| 37.457447 | 111 | 0.724226 |
438e060e4c9d12ec003b6f9fa6b657f76e267898 | 1,029 | package de.daxu.swamp.api.containertemplate.dto;
import de.daxu.swamp.common.ValueObject;
public class PortMappingDTO extends ValueObject {
private Integer internal;
private Integer external;
@SuppressWarnings("unused")
private PortMappingDTO() {
}
private PortMappingDTO(Integer internal, Integer external) {
this.internal = internal;
this.external = external;
}
public Integer getInternal() {
return internal;
}
public Integer getExternal() {
return external;
}
public static class Builder {
private Integer internal;
private Integer external;
public Builder withInternal(Integer internal) {
this.internal = internal;
return this;
}
public Builder withExternal(Integer external) {
this.external = external;
return this;
}
public PortMappingDTO build() {
return new PortMappingDTO(internal, external);
}
}
}
| 21.893617 | 64 | 0.62585 |
4122e65fa40d2f14dcacc8f4686e243b39cca975 | 2,416 | // Copyright (C) 2005, Free Software Foundation, Inc.
//
// This file is part of Mauve.
//
// Mauve is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// Mauve is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA, 02110-1301 USA.
//
// Tags: JDK1.2
package gnu.testlet.java.security.AccessController;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.security.*;
/**
* Checks that unchecked exceptions are properly thrown and checked
* exceptions are properly wrapped.
*
* Written by Mark J. Wielaard. Suggested by Nicolas Geoffray.
*/
public class doPrivileged implements Testlet, PrivilegedExceptionAction {
// The thing to throw.
private Throwable t;
public void test(TestHarness harness) {
doPrivileged pea = new doPrivileged();
pea.t = new NullPointerException();
try {
AccessController.doPrivileged(pea);
} catch (NullPointerException npe) {
harness.check(true);
} catch (Throwable tt) {
harness.debug(tt);
harness.check(false);
}
pea.t = new java.io.IOException();
try {
AccessController.doPrivileged(pea);
} catch (PrivilegedActionException pae) {
harness.check(pea.t, pae.getCause());
} catch (Throwable tt) {
harness.debug(tt);
harness.check(false);
}
pea.t = new ThreadDeath();
try {
AccessController.doPrivileged(pea);
} catch (ThreadDeath td) {
harness.check(true);
} catch (Throwable tt) {
harness.debug(tt);
harness.check(false);
}
}
public Object run() throws Exception {
if (t instanceof Error) {
throw (Error) t;
} else {
throw (Exception) t;
}
}
}
| 29.82716 | 73 | 0.633692 |
16884c274229028aef99d4cd82796064e6555c35 | 474 | package com.rbinternational.awstools.awsjwtvalidator;
import io.jsonwebtoken.io.Encoders;
import java.net.URL;
import java.security.PublicKey;
public class MockPublicKeyReader implements PublicKeyReader {
private PublicKey publicKey;
public MockPublicKeyReader(PublicKey publicKey) {
this.publicKey = publicKey;
}
@Override
public String readPublicKey(URL url) {
return Encoders.BASE64.encode(this.publicKey.getEncoded());
}
}
| 21.545455 | 67 | 0.746835 |
a11924ee26bc27137d68ce848027c882ed15bc44 | 1,444 | package com.winston.aop.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author Winston.Wang
* @version 1.0
* @Description: Aspect类用来织如我们的代码
* @date 2019/6/19
*/
/**
* 要想使用注解来实现Aspect代理类,
* 把该类注册到AOP代理中,没有实现接口,这边使用的是cglib代理, CglibAopProxy
* @EnableAspectJAutoProxy开启直接支持
* xml中,使用<aop:aspectj-autoproxy proxy-target-class="true"/> true:使用cglib代理,false使用jdk代理。不配
* 根据是否实现接口匹配
*/
@Aspect
@EnableAspectJAutoProxy
public class SecuredAspect {
private static Logger logger = LoggerFactory.getLogger(SecuredAspect.class);
/**
* 定义切点
*/
@Pointcut(value = "@annotation(secured)")
public void callAt(Secured secured){
}
/**
* 定义通知类型
* 通过ProceedingJoinPoint当前执行的方法校验通过可以往下执行
* secured 注解参数
*/
@Around("callAt(secured)")
public Object around(ProceedingJoinPoint point, Secured secured) throws Throwable{
if(secured.isLocked()){
logger.info("aop拦截:"+point.getSignature().toLongString()+"is Locked");
return null;
}
logger.info("aop通过:"+point.getSignature().toLongString()+"is UnLocked");
//校验通过继续往下执行
return point.proceed();
}
}
| 26.740741 | 95 | 0.700831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.