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
|
|---|---|---|---|---|---|
5a36dbec78e20ce83579ddd8928b66ad1644bc9b
| 4,000
|
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.tools.jib.filesystem;
import com.google.common.collect.ImmutableList;
import com.google.common.io.MoreFiles;
import com.google.common.io.RecursiveDeleteOption;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
/** Static methods for operating on the filesystem. */
public class FileOperations {
/**
* Copies {@code sourceFiles} to the {@code destDir} directory.
*
* @param sourceFiles the list of source files.
* @param destDir the directory to copy the files to.
* @throws IOException if the copy fails.
*/
public static void copy(ImmutableList<Path> sourceFiles, Path destDir) throws IOException {
for (Path sourceFile : sourceFiles) {
PathConsumer copyPathConsumer =
path -> {
// Creates the same path in the destDir.
Path destPath = destDir.resolve(sourceFile.getParent().relativize(path));
if (Files.isDirectory(path)) {
Files.createDirectories(destPath);
} else {
Files.copy(path, destPath);
}
};
if (Files.isDirectory(sourceFile)) {
new DirectoryWalker(sourceFile).walk(copyPathConsumer);
} else {
copyPathConsumer.accept(sourceFile);
}
}
}
/**
* Acquires an exclusive {@link FileLock} on the {@code file} and opens an {@link OutputStream} to
* write to it. The file will be created if it does not exist, or truncated to length 0 if it does
* exist. The {@link OutputStream} must be closed to release the lock.
*
* <p>The locking mechanism should not be used as a concurrency management feature. Rather, this
* should be used as a way to prevent concurrent writes to {@code file}. Concurrent attempts to
* lock {@code file} will result in {@link OverlappingFileLockException}s.
*
* @param file the file to write to
* @return an {@link OutputStream} that writes to the file
* @throws IOException if an I/O exception occurs
*/
public static OutputStream newLockingOutputStream(Path file) throws IOException {
EnumSet<StandardOpenOption> createOrTruncate =
EnumSet.of(
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
// Channel is closed by outputStream.close().
FileChannel channel = FileChannel.open(file, createOrTruncate);
// Lock is released when channel is closed.
channel.lock();
return Channels.newOutputStream(channel);
}
/**
* Sets up a shutdown hook that tries to delete a file or directory.
*
* @param path the path to the file or directory
*/
public static void deleteRecursiveOnExit(Path path) {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
if (Files.exists(path)) {
try {
MoreFiles.deleteRecursively(path, RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException ignored) {
}
}
}));
}
private FileOperations() {}
}
| 36.036036
| 100
| 0.67325
|
d20077bb07bb75f15876f47b85380427eeef8dc6
| 2,409
|
package com.home.commonClient.net.sceneBaseResponse.unit;
import com.home.commonBase.data.scene.base.BulletData;
import com.home.commonClient.constlist.generate.GameResponseType;
import com.home.commonClient.constlist.generate.SceneBaseResponseType;
import com.home.commonClient.net.sceneBaseResponse.base.UnitSResponse;
import com.home.shine.bytes.BytesReadStream;
import com.home.shine.data.BaseData;
import com.home.shine.support.DataWriter;
import com.home.shine.support.pool.DataPool;
/** 单位发出子弹消息(generated by shine) */
public class AddBulletResponse extends UnitSResponse
{
/** 数据类型ID */
public static final int dataID=SceneBaseResponseType.AddBullet;
/** 子弹数据 */
public BulletData bullet;
public AddBulletResponse()
{
_dataID=SceneBaseResponseType.AddBullet;
}
/** 执行 */
@Override
protected void execute()
{
scene.getFightUnitAbs(instanceID).fight.addBullet(bullet,false,false);
}
/** 获取数据类名 */
@Override
public String getDataClassName()
{
return "AddBulletResponse";
}
/** 读取字节流(完整版) */
@Override
protected void toReadBytesFull(BytesReadStream stream)
{
super.toReadBytesFull(stream);
stream.startReadObj();
BaseData bulletT=stream.readDataFullNotNull();
if(bulletT!=null)
{
if(bulletT instanceof BulletData)
{
this.bullet=(BulletData)bulletT;
}
else
{
this.bullet=new BulletData();
if(!(bulletT.getClass().isAssignableFrom(BulletData.class)))
{
stream.throwTypeReadError(BulletData.class,bulletT.getClass());
}
this.bullet.shadowCopy(bulletT);
}
}
else
{
this.bullet=null;
}
stream.endReadObj();
}
/** 读取字节流(简版) */
@Override
protected void toReadBytesSimple(BytesReadStream stream)
{
super.toReadBytesSimple(stream);
this.bullet=(BulletData)stream.readDataSimpleNotNull();
}
/** 转文本输出 */
@Override
protected void toWriteDataString(DataWriter writer)
{
super.toWriteDataString(writer);
writer.writeTabs();
writer.sb.append("bullet");
writer.sb.append(':');
if(this.bullet!=null)
{
this.bullet.writeDataString(writer);
}
else
{
writer.sb.append("BulletData=null");
}
writer.writeEnter();
}
/** 回池 */
@Override
protected void toRelease(DataPool pool)
{
super.toRelease(pool);
this.bullet=null;
}
}
| 21.318584
| 73
| 0.684932
|
943b8c1576ae290e0065e54fbf574aa5fc78196f
| 1,606
|
package com.hirath.goldenberry.core.selector;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.hirath.goldenberry.api.function.Operation;
import com.hirath.goldenberry.core.InstanceExampleFactory;
class FromOperationSelector implements MatchingMethodSelector<Operation> {
public Optional<Method> selectMatchingMethod(Class<?> type, Operation operation) {
if(type == null || operation == null)
return Optional.empty();
List<Method> resolvedMethods = new ArrayList<>();
Object proxy = creationProxy(type, resolvedMethods);
MethodArgumentValues parameterValues = new MethodArgumentValues(proxy);
executeOperation(operation, parameterValues);
return Optional.of(resolvedMethods).filter(l -> !l.isEmpty()).map(l -> l.get(0));
}
private Object creationProxy(Class<?> type, List<Method> resolvedMethods) {
return Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, (p, method, args) -> {
resolvedMethods.add(method);
return InstanceExampleFactory.anyOf(method.getReturnType());
});
}
private void executeOperation(Operation operation, MethodArgumentValues parameterValues) {
boolean executed = false;
do {
try {
operation.execute(parameterValues.toArray());
executed = true;
} catch (ClassCastException e) {
String[] classes = e.getMessage().split(" cannot be cast to ");
parameterValues.updateFirst(classes[0], classes[1]);
executed = false;
} catch (Exception e) {
executed = true;
}
} while (!executed);
}
}
| 34.170213
| 99
| 0.739726
|
9d2f4d65a0c3ea7410209e04bf94bec613d9b299
| 19,363
|
package com.itheima.audiocontrol;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
public class ContentFragment extends Fragment implements
OnSeekBarChangeListener, OnClickListener {
private static final int CROP_PHOTO = 1;
private static final int CHOICE_PHOTO = 2;
private TextView music_volume;
private TextView ring_volume;
private TextView system_volume;
private AudioManager am;
private SeekBar sb_music_volume;
private SeekBar sb_ring_volume;
private SeekBar sb_alarm_volume;
private SeekBar sb_system_volume;
private ImageButton ib_silent;
private SeekBar sb_notify_volume;
private FragmentActivity activity;
private ImageButton ib_setting;
private ImageButton ib_recovery;
private SharedPreferences current_volume;
private SharedPreferences checkbox_state;
private LinearLayout ll_content_root;
private SharedPreferences system_config;
private Bitmap bgResult;
private ImageButton ib_chang_bg;
Uri choice_imageUri;
private Bitmap bitmap;
private File choice_image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
current_volume = activity.getSharedPreferences("current_volume",
Context.MODE_PRIVATE);
checkbox_state = activity.getSharedPreferences("checkbox_state",
Context.MODE_PRIVATE);
system_config = activity.getSharedPreferences("system_config",
Context.MODE_PRIVATE);
choice_image = new File(Environment.getExternalStorageDirectory(),
"choice_image.jpg");
choice_imageUri = Uri.fromFile(choice_image);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragement_slide = View.inflate(activity,
R.layout.fragement_content, null);
intUI(fragement_slide);
// 动态随机更换壁纸
// randomChangeBg();
// 恢复之前设置的背景
try {
bitmap = BitmapFactory.decodeStream(activity.getContentResolver()
.openInputStream(choice_imageUri));
if (bitmap != null) {
Drawable drawable = new BitmapDrawable(bitmap);
// iv_bg.setImageBitmap(bitmap);
ll_content_root.setBackground(drawable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
boolean isWidgetRuning = system_config.getBoolean("isWidgetRuning",
false);
boolean serviceRunning = isServiceRunning();
if (!serviceRunning) {
if (isWidgetRuning) {
Intent intent = new Intent(activity, WidgetService.class);
activity.startService(intent);
// Toast.makeText(getActivity(), "后台一键静音服务已经重新启动...", 0).show();
ControlUtils.getToast(getActivity(), "后台一键静音服务已经重新启动...");
}
}
return fragement_slide;
}
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) activity
.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
System.out.println("运行的服务" + service.service.getClassName());
if ("com.itheima.audiocontrol.WidgetService".equals(service.service
.getClassName())) {
return true;
}
}
return false;
}
// /**
// * 随机更换壁纸
// */
// private void randomChangeBg() {
// int[] pic = new int[] { R.drawable.pc1, R.drawable.pc2, R.drawable.pc3,
// R.drawable.pc4, R.drawable.pc5, R.drawable.pc6, R.drawable.pc7 };
//
// Random random = new Random();
// int picNum = random.nextInt(7);
//
// Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
//
// BitmapFactory.decodeResource(getResources(), pic[picNum], opts);
// // 获取到图片的宽和高信息
// int imageWidth = opts.outWidth;
// int imageHeight = opts.outHeight;
// // 获取到屏幕对象
// Display display = activity.getWindowManager().getDefaultDisplay();
// // 获取到屏幕的真是宽和高
// int screenWidth = display.getWidth();
// int screenHeight = display.getHeight();
//
// // 计算缩放比例
// int widthScale = imageWidth / screenWidth;
// int heightScale = imageHeight / screenHeight;
// // 计算出最大的比例
// int scale = widthScale > heightScale ? widthScale : heightScale;
// // 使用缩放比例进行缩放加载图片
// opts.inJustDecodeBounds = false; // 加载器就会返回图片了
// // 配置该参数加载图片时 BitmapFactory 就会自动缩放图片
// opts.inSampleSize = scale;
// bgResult = BitmapFactory.decodeResource(getResources(), pic[picNum],
// opts);
// Drawable drawable = new BitmapDrawable(bgResult);
//
// ll_content_root.setBackground(drawable);
//
// // ll_content_root.setBackgroundResource(pic[picNum]);
// }
@Override
public void onDestroyView() {
if (bitmap != null) {
bitmap.recycle();
}
super.onDestroyView();
}
private void intUI(View fragement_slide) {
music_volume = (TextView) fragement_slide
.findViewById(R.id.tv_show_music_volume);
ring_volume = (TextView) fragement_slide
.findViewById(R.id.tv_show_ring_volume);
system_volume = (TextView) fragement_slide
.findViewById(R.id.tv_show_system_volume);
ib_silent = (ImageButton) fragement_slide.findViewById(R.id.ib_silent);
ib_recovery = (ImageButton) fragement_slide
.findViewById(R.id.ib_recovery);
ib_setting = (ImageButton) fragement_slide
.findViewById(R.id.ib_setting);
ib_chang_bg = (ImageButton) fragement_slide
.findViewById(R.id.ib_chang_bg);
ll_content_root = (LinearLayout) fragement_slide
.findViewById(R.id.ll_content_root);
sb_music_volume = (SeekBar) fragement_slide
.findViewById(R.id.sb_music_volume);
sb_ring_volume = (SeekBar) fragement_slide
.findViewById(R.id.sb_ring_volume);
sb_alarm_volume = (SeekBar) fragement_slide
.findViewById(R.id.sb_alarm_volume);
sb_system_volume = (SeekBar) fragement_slide
.findViewById(R.id.sb_system_volume);
sb_notify_volume = (SeekBar) fragement_slide
.findViewById(R.id.sb_notify_volume);
am = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
// 获取最大媒体音量
int maxMusicVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
// 获取最大闹钟音量
int maxAlarmVolume = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);
// 获取最大铃声音量
int maxRingVolume = am.getStreamMaxVolume(AudioManager.STREAM_RING);
// 获取最大系统音量
int maxSystemVolume = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
// 获取最大通知音量
int maxNotifyVolume = am
.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
// 更新seekBar进度
updateSeekBarProgress();
// 设置seekBar最大值
sb_music_volume.setMax(maxMusicVolume);
sb_ring_volume.setMax(maxRingVolume);
sb_alarm_volume.setMax(maxAlarmVolume);
sb_system_volume.setMax(maxSystemVolume);
sb_notify_volume.setMax(maxNotifyVolume);
// 设置seekBar监听
sb_music_volume.setOnSeekBarChangeListener(this);
sb_ring_volume.setOnSeekBarChangeListener(this);
sb_alarm_volume.setOnSeekBarChangeListener(this);
sb_system_volume.setOnSeekBarChangeListener(this);
sb_notify_volume.setOnSeekBarChangeListener(this);
// 设置一键静音监听
ib_silent.setOnClickListener(this);
// 设置一键还原监听
ib_recovery.setOnClickListener(this);
// 设置侧边栏监听
ib_setting.setOnClickListener(this);
ib_chang_bg.setOnClickListener(this);
}
/**
* 各种点点击监听
*/
// boolean isSilentStyle = ;
@Override
public void onClick(View v) {
// 判断是否已经是静音模式
boolean isSilentMode = current_volume.getBoolean("isSilentMode", false);
switch (v.getId()) {
case R.id.ib_setting:
toggle();
break;
case R.id.ib_silent:
// 判断是否已经是静音模式
if (isSilentMode) {
break;
}
// 获取当前音量存入sp
// 获取当前系统音量
int currentMusicVolume = am
.getStreamVolume(AudioManager.STREAM_MUSIC);
int currentRingVolume = am
.getStreamVolume(AudioManager.STREAM_RING);
int currentSystemVolume = am
.getStreamVolume(AudioManager.STREAM_SYSTEM);
int currentAlarmVolume = am
.getStreamVolume(AudioManager.STREAM_ALARM);
int currentNotifyVolume = am
.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
// 判断,如果所有音量都为0.不进行存储。
// int allVolumeSum = currentMusicVolume1 + currentRingVolume1
// + currentSystemVolume1 + currentAlarmVolume1
// + currentNotifyVolume1;
// if (allVolumeSum != 0) {
// break;
// }
Editor edit = current_volume.edit();
edit.putInt("currentMusicVolume", currentMusicVolume);
edit.putInt("currentRingVolume", currentRingVolume);
edit.putInt("currentSystemVolume", currentSystemVolume);
edit.putInt("currentAlarmVolume", currentAlarmVolume);
edit.putInt("currentNotifyVolume", currentNotifyVolume);
// edit.putBoolean("idHaveSilent", true);
// 设置已经是静音模式
edit.putBoolean("isSilentMode", true);
edit.commit();
// 一键静音
oneKeySilent();
// 更新seekBar进度
updateSeekBarProgress();
break;
case R.id.ib_recovery:
// 从sp获取之前的音量
Editor edit1 = current_volume.edit();
// edit1.putBoolean("idHaveSilent", false);
// 设置不是静音模式
edit1.putBoolean("isSilentMode", false);
edit1.commit();
int currentMusicVolume2 = current_volume.getInt(
"currentMusicVolume", 0);
int currentRingVolume2 = current_volume.getInt("currentRingVolume",
0);
int currentSystemVolume2 = current_volume.getInt(
"currentSystemVolume", 0);
int currentAlarmVolume2 = current_volume.getInt(
"currentAlarmVolume", 0);
int currentNotifyVolume2 = current_volume.getInt(
"currentNotifyVolume", 0);
// 设置当前音量
// 设置所有音量存储的音量值
am.setStreamVolume(AudioManager.STREAM_MUSIC, currentMusicVolume2,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_SYSTEM,
currentSystemVolume2, AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_RING, currentRingVolume2,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_ALARM, currentAlarmVolume2,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
currentNotifyVolume2, AudioManager.FLAG_PLAY_SOUND);
// 更新seekBar进度
updateSeekBarProgress();
break;
// 更换背景逻辑
case R.id.ib_chang_bg:
//
// // 创建存储文件路径
//
// choice_image = new File(
// Environment.getExternalStorageDirectory(),
// "choice_image.jpg");
try {
if (choice_image.exists()) {
choice_image.delete();
}
choice_image.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");// 相片类型
startActivityForResult(intent, CHOICE_PHOTO);
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOICE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// 启动裁剪程序
int width = 500;
int hight = 890;
Uri data2 = data.getData();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data2, "image/*");
// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
intent.putExtra("scale", true);// 去黑边
intent.putExtra("scaleUpIfNeeded", true);// 去黑边
// <a target="_blank" href="http://www.2cto.com/kf/web/asp/"
// class="keylink"
// style="border:none; padding:0px; margin:0px; color:rgb(51,51,51); text-decoration:none; font-size:14px; background:none">asp</a>ectX
// aspectY 是宽高的比例
intent.putExtra("aspectX", 1);// 输出是X方向的比例
intent.putExtra("aspectY", 1.7);
// outputX outputY 是裁剪图片宽高,切忌不要再改动下列数字,会卡死
intent.putExtra("outputX", 1080);// 输出X方向的像素
intent.putExtra("outputY", 1920);
intent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, choice_imageUri);
intent.putExtra("return-data", false);// 设置为不返回数据
startActivityForResult(intent, CROP_PHOTO);
}
break;
case CROP_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// 启动显示程序
try {
bitmap = BitmapFactory.decodeStream(activity
.getContentResolver().openInputStream(
choice_imageUri));
Drawable drawable = new BitmapDrawable(bitmap);
// iv_bg.setImageBitmap(bitmap);
ll_content_root.setBackground(drawable);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
}
public void oneKeySilent() {
// 设置所有音量为零
am.setStreamVolume(AudioManager.STREAM_MUSIC, 0,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_SYSTEM, 0,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_RING, 0,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_ALARM, 0,
AudioManager.FLAG_PLAY_SOUND);
am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0,
AudioManager.FLAG_PLAY_SOUND);
}
private void toggle() {
MainActivity mianActivity = (MainActivity) activity;
SlidingMenu slidingMenu = mianActivity.getSlidingMenu();
slidingMenu.toggle();
}
/**
* 可以显示界面和交互的时候,更新音量界面
*/
@Override
public void onResume() {
super.onResume();
// 更新音量界面
updateSeekBarProgress();
boolean isWidgetRuning = system_config.getBoolean("isWidgetRuning",
false);
boolean serviceRunning = isServiceRunning();
if (!serviceRunning) {
if (isWidgetRuning) {
Intent intent = new Intent(activity, WidgetService.class);
activity.startService(intent);
// Toast.makeText(getActivity(), "后台一键静音服务已经重新启动...", 0).show();
ControlUtils.getToast(getActivity(), "后台一键静音服务已经重新启动...");
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
/**
* 监听系统音量按键
*
* @param keyCode
* @param event
* @param b
* @return
*/
public boolean onKeyDown(int keyCode, KeyEvent event, boolean b) {
// 获取保存在sp的checkBox状态,进行相应的设置
boolean cb_music_state = checkbox_state.getBoolean("cb_music", true);
boolean cb_ring_state = checkbox_state.getBoolean("cb_ring", true);
boolean cb_notify_state = checkbox_state.getBoolean("cb_notify", true);
boolean cb_alarm_state = checkbox_state.getBoolean("cb_alarm", true);
boolean cb_system_state = checkbox_state.getBoolean("cb_system", true);
// 获取手机当前音量值
switch (keyCode) {
// 音量减小
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (cb_music_state) {
// 调节音乐音量
am.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_ring_state) {
// 调节铃声音量
am.adjustStreamVolume(AudioManager.STREAM_RING,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_notify_state) {
// 调节通知音量
am.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_alarm_state) {
// 调节闹钟音量
am.adjustStreamVolume(AudioManager.STREAM_ALARM,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_system_state) {
// 调节系统音量
am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
// 更新seekBar进度
updateSeekBarProgress();
return true;
// 音量增大
case KeyEvent.KEYCODE_VOLUME_UP:
if (cb_music_state) {
// 调节音乐音量
am.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_ring_state) {
// 调节铃声音量
am.adjustStreamVolume(AudioManager.STREAM_RING,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_notify_state) {
// 调节通知音量
am.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_alarm_state) {
// 调节闹钟音量
am.adjustStreamVolume(AudioManager.STREAM_ALARM,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
if (cb_system_state) {
// 调节系统音量
am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
// 更新seekBar进度
updateSeekBarProgress();
return true;
}
return b;
}
/**
* 获取当前各种音量值,且更新seekBar进度
*/
public void updateSeekBarProgress() {
// 获取当前系统音量
int currentMusicVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
int currentRingVolume = am.getStreamVolume(AudioManager.STREAM_RING);
int currentSystemVolume = am
.getStreamVolume(AudioManager.STREAM_SYSTEM);
int currentAlarmVolume = am.getStreamVolume(AudioManager.STREAM_ALARM);
int currentNotifyVolume = am
.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
// 更新seekBar
sb_music_volume.setProgress(currentMusicVolume);
sb_ring_volume.setProgress(currentRingVolume);
sb_alarm_volume.setProgress(currentAlarmVolume);
sb_system_volume.setProgress(currentSystemVolume);
sb_notify_volume.setProgress(currentNotifyVolume);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
int id = seekBar.getId();
switch (id) {
case R.id.sb_music_volume:
System.out.println("当前当前媒体音量进度progress" + progress);
// 设置当前媒体音量值
am.setStreamVolume(AudioManager.STREAM_MUSIC, progress,
AudioManager.FLAG_PLAY_SOUND);
break;
case R.id.sb_ring_volume:
System.out.println("当前当前铃声音量值进度progress" + progress);
// 设置当前铃声音量值
am.setStreamVolume(AudioManager.STREAM_RING, progress,
AudioManager.FLAG_PLAY_SOUND);
break;
case R.id.sb_alarm_volume:
System.out.println("当前当前闹钟音量进度progress" + progress);
// 设置当前闹钟音量值
am.setStreamVolume(AudioManager.STREAM_ALARM, progress,
AudioManager.FLAG_PLAY_SOUND);
break;
case R.id.sb_system_volume:
System.out.println("当前当前系统音量进度progress" + progress);
// 设置当前系统音量值
am.setStreamVolume(AudioManager.STREAM_SYSTEM, progress,
AudioManager.FLAG_PLAY_SOUND);
case R.id.sb_notify_volume:
System.out.println("当前当前通知音量进度progress" + progress);
// 设置当前系统音量值
am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, progress,
AudioManager.FLAG_PLAY_SOUND);
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
| 25.851802
| 139
| 0.736611
|
f257d1fd0d9d8d0617b5aeb3f51062c5f05ae948
| 520
|
package fi.nls.paikkatietoikkuna.terrainprofile;
import java.util.List;
import org.geojson.LineString;
import org.geojson.LngLatAlt;
public class GeoJSONHelper {
public static double[] getCoordinates2D(LineString geom) {
List<LngLatAlt> list = geom.getCoordinates();
double[] arr = new double[list.size() * 2];
int i = 0;
for (LngLatAlt coord : list) {
arr[i++] = coord.getLongitude();
arr[i++] = coord.getLatitude();
}
return arr;
}
}
| 24.761905
| 62
| 0.619231
|
2873a139fb39b778c137e36b6b4bee2fc355aa75
| 2,085
|
package org.edmcouncil.spec.ontoviewer.toolkit.config;
import org.edmcouncil.spec.ontoviewer.configloader.configuration.service.ConfigurationService;
import org.edmcouncil.spec.ontoviewer.configloader.configuration.service.MemoryBasedConfigurationService;
import org.edmcouncil.spec.ontoviewer.core.ontology.DetailsManager;
import org.edmcouncil.spec.ontoviewer.core.ontology.OntologyManager;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.OwlDataHandler;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.RestrictionGraphDataHandler;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.extractor.OwlDataExtractor;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.handler.AnnotationsDataHandler;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.handler.IndividualDataHandler;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.handler.fibo.FiboDataHandler;
import org.edmcouncil.spec.ontoviewer.core.ontology.data.label.LabelProvider;
import org.edmcouncil.spec.ontoviewer.core.ontology.factory.CustomDataFactory;
import org.edmcouncil.spec.ontoviewer.core.ontology.updater.Updater;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
@Configuration
@Import({
AnnotationsDataHandler.class,
CustomDataFactory.class,
DetailsManager.class,
FiboDataHandler.class,
IndividualDataHandler.class,
LabelProvider.class,
OntologyManager.class,
OwlDataExtractor.class,
OwlDataHandler.class,
RestrictionGraphDataHandler.class,
})
@ComponentScan(
value = "org.edmcouncil.spec.ontoviewer.core",
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Updater.class)
}
)
public class ApplicationConfiguration {
@Bean
public ConfigurationService getConfigurationService() {
return new MemoryBasedConfigurationService();
}
}
| 44.361702
| 105
| 0.832134
|
ac89fc43cab8cfbdc3cd3e8ee069bef7fc6aaed7
| 4,270
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.DrivetrainSubsystem;
import frc.robot.subsystems.HoodSubsystem;
import frc.robot.subsystems.IndexerSubsystem;
import frc.robot.subsystems.PhotonVisionSubsystem;
import frc.robot.subsystems.ShooterSubsystem;
public class ShootInAuto extends CommandBase {
/** Creates a new Shoot. */
public ShooterSubsystem shooterSubsystem;
public HoodSubsystem hoodSubsystem;
public IndexerSubsystem indexerSubsystem;
public PhotonVisionSubsystem photonVisionSubsystem;
public DrivetrainSubsystem drivetrainSubsystem;
public PIDController rotationController;
public final Timer timer, timer2, timer3, timer4, timer5;
public boolean targetSeen = false;
public int shots = 0;
public boolean Lastbol = false;
public int numOfballs = 0;
public ShootInAuto(int numOfballs, ShooterSubsystem shooterSubsystem, HoodSubsystem hoodSubsystem, IndexerSubsystem indexerSubsystem, PhotonVisionSubsystem photonVisionSubsystem, DrivetrainSubsystem drivetrainSubsystem) {
this.indexerSubsystem = indexerSubsystem;
this.shooterSubsystem = shooterSubsystem;
this.hoodSubsystem = hoodSubsystem;
this.photonVisionSubsystem = photonVisionSubsystem;
this.drivetrainSubsystem = drivetrainSubsystem;
this.numOfballs = numOfballs;
timer = new Timer();
timer2 = new Timer();
timer3 = new Timer();
timer4 = new Timer();
timer5 = new Timer();
rotationController = new PIDController(.08, .025, 0);
shots = 0;
Lastbol = false;
addRequirements(shooterSubsystem, hoodSubsystem, indexerSubsystem, photonVisionSubsystem, drivetrainSubsystem);
// Use addRequirements() here to declare subsystem dependencies.
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
shots = 0;
Lastbol = false;
timer.reset();
timer2.reset();
timer3.reset();
timer4.reset();
timer4.start();
timer5.reset();
timer5.start();
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if(Lastbol != indexerSubsystem.topBeamBreak.get() && !Lastbol){
shots += 1;
}
Lastbol = false;
double d = photonVisionSubsystem.getDistanceToGoalMeters(0.0);
if(photonVisionSubsystem.hasGoalTargets()){
targetSeen = true;
hoodSubsystem.setHoodPosition(.208 + .00568 * d - (.00000945 * (d*d)));
shooterSubsystem.setSpeed(4.63*d + 2000);
drivetrainSubsystem.drive(new ChassisSpeeds(0, 0, rotationController.calculate(photonVisionSubsystem.getXDisplacementOfGoal())));
} else if (!targetSeen){
timer2.start();
timer3.start();
if(timer2.get() > .5){
drivetrainSubsystem.drive(new ChassisSpeeds(0, 0, 2));
} else {
drivetrainSubsystem.drive(new ChassisSpeeds(0, 0, -2));
}
}
if(timer3.get()>.1 && targetSeen){
targetSeen = false;
}
if(photonVisionSubsystem.hasGoalTargets()){
if (shooterSubsystem.isShooterToSpeedAndNotDisabled() && (Math.abs(photonVisionSubsystem.getXDisplacementOfGoal()) < 5)) {
indexerSubsystem.runIndexerInMed();
timer.start();
} else {
indexerSubsystem.indexBallsBetweenBreaks();
timer.stop();
}
}
Lastbol = indexerSubsystem.topBeamBreak.get();
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
hoodSubsystem.setHoodPosition(0.1);
indexerSubsystem.stopIndexer();
shots = 0;
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return (timer.get() > .5 && timer4.get() > .1) || timer5.get() > 6;
}
}
| 22.956989
| 223
| 0.702576
|
318371755618b94bbf9a22091f637d3343e87303
| 716
|
package com.cartoonishvillain.eeriehauntings.capabilities.playercapability;
public interface IPlayerCapability {
float getHauntChance();
void setHauntChance(float hauntChance);
void addHauntChance(float addedChance);
boolean getIsHaunted();
void setHaunted(boolean isHaunted);
int getGhostType();
void setGhostType(int Type);
int getProtectedDays();
void setProtectedDays(int days);
void setAnger(boolean isAngry);
boolean getAnger();
int getHauntActionTicks();
void setHauntActionTicks(int ticks);
boolean checkHauntActionTicks();
int getVisualEffectTime();
void setVisualEffectTime(int ticks);
int getEffectID();
void setEffectID(int ID);
}
| 31.130435
| 75
| 0.740223
|
6a55443a5f2b3c1c9ac3b0460336e50025e0df31
| 285
|
package com.leodelmiro.mercadolivre.purchaseprocess;
public enum PurchaseStatusPagseguro {
SUCCESS, FAIL;
public PurchaseStatus normalize() {
if (this.equals(SUCCESS)) {
return PurchaseStatus.SUCCESS;
}
return PurchaseStatus.FAIL;
}
}
| 21.923077
| 52
| 0.666667
|
2e9db9cf963d55902cc28adecc97340e21b50db0
| 1,206
|
package com.example.lab4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.lab4.Screen.Lesson2Activity;
import com.example.lab4.Screen.Lesson3Activity;
import com.example.lab4.Screen.lesson1;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void switchActivity(View view){
Intent intent = null;
switch (view.getId()){
case R.id.btOne :
intent = new Intent(this, lesson1.class);
break;
case R.id.btTwo :
intent = new Intent(this, Lesson2Activity.class);
break;
case R.id.btThree :
intent = new Intent(this, Lesson3Activity.class);
break;
default:
return;
}
startActivity(intent);
}
}
| 28.714286
| 65
| 0.635987
|
509bccbef51e7c9c848ab78a7e29609d54b280aa
| 5,400
|
package com.blackstone.goldenquran.adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.blackstone.goldenquran.R;
import com.blackstone.goldenquran.models.AljuzaModel;
import com.blackstone.goldenquran.models.AlsuraModel;
import com.blackstone.goldenquran.models.QueryMessage;
import com.blackstone.goldenquran.models.TableOfContents;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Abdullah on 5/6/2017.
*/
public class ActivityResultAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<Object> list;
List<Object> models;
List<Object> originalModels;
LayoutInflater layoutInflater;
Context context;
ArrayList<TableOfContents> modelsData;
public void query(QueryMessage queryMessage) {
list = new ArrayList<>();
for (Object s : models) {
if (!AljuzaModel.class.isInstance(s)) {
if (((AlsuraModel) s).suraName.contains(queryMessage.getMessage()))
list.add(s);
}
}
if (!queryMessage.getMessage().isEmpty()) {
originalModels = new ArrayList<>(list);
notifyDataSetChanged();
} else {
originalModels = new ArrayList<>(models);
notifyDataSetChanged();
}
}
public ActivityResultAdapter(Context context, List<Object> list, ArrayList<TableOfContents> modelsData) {
layoutInflater = LayoutInflater.from(context);
this.context = context;
this.modelsData = modelsData;
this.originalModels = list;
this.models = list;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1)
return new AlJuzaViewHolder1(layoutInflater.inflate(R.layout.juzoa_row_layout, parent, false));
else if (viewType == 0)
return new AlsurahViewHolder1(layoutInflater.inflate(R.layout.sura_row_layout, parent, false));
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 1) {
AlJuzaViewHolder1 viewHolder = (AlJuzaViewHolder1) holder;
final AljuzaModel aljuzaModel = (AljuzaModel) originalModels.get(position);
viewHolder.juzoa.setText(aljuzaModel.getName());
viewHolder.juzoRelative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
} else if (holder.getItemViewType() == 0) {
AlsurahViewHolder1 viewHolder = (AlsurahViewHolder1) holder;
final AlsuraModel alsuraModel = (AlsuraModel) originalModels.get(position);
viewHolder.ayat.setText(alsuraModel.numberOfAya);
viewHolder.name.setText(alsuraModel.suraName);
viewHolder.number.setText(alsuraModel.number);
viewHolder.contentPanel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent data = new Intent();
data.putExtra("suraName", alsuraModel.suraName + "");
data.putExtra("suraVersesCount", alsuraModel.numberOfAya);
data.putExtra("suraNumber", alsuraModel.number);
((AppCompatActivity) context).setResult(Activity.RESULT_OK, data);
((AppCompatActivity) context).finish();
}
});
if (context.getResources().getBoolean(R.bool.is_right_to_left))
viewHolder.arrow.setImageResource(R.drawable.right_arrow);
else
viewHolder.arrow.setImageResource(R.drawable.left_arrow);
}
}
@Override
public int getItemCount() {
return originalModels.size();
}
@Override
public int getItemViewType(int position) {
if (AljuzaModel.class.isInstance(originalModels.get(position)))
return 1;
else if (AlsuraModel.class.isInstance(originalModels.get(position)))
return 0;
return 2;
}
class AlsurahViewHolder1 extends RecyclerView.ViewHolder {
@BindView(R.id.imageLiftArrow)
ImageView arrow;
@BindView(R.id.suraName)
TextView name;
@BindView(R.id.numberOfSura)
TextView number;
@BindView(R.id.numberOfAyat)
TextView ayat;
@BindView(R.id.row)
RelativeLayout contentPanel;
AlsurahViewHolder1(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
class AlJuzaViewHolder1 extends RecyclerView.ViewHolder {
@BindView(R.id.juzoaNumber)
TextView juzoa;
@BindView(R.id.juzoRelative)
RelativeLayout juzoRelative;
AlJuzaViewHolder1(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
| 33.962264
| 109
| 0.652963
|
aafc3f63a2bf2480dd73db5cb6a309168a311724
| 6,191
|
/*
* Copyright 2019 HERMENEUT Consortium
*
* 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 eu.hermeneut.web.rest;
import com.codahale.metrics.annotation.Timed;
import eu.hermeneut.domain.SplittingValue;
import eu.hermeneut.service.SplittingValueService;
import eu.hermeneut.web.rest.errors.BadRequestAlertException;
import eu.hermeneut.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing SplittingValue.
*/
@RestController
@RequestMapping("/api")
public class SplittingValueResource {
private final Logger log = LoggerFactory.getLogger(SplittingValueResource.class);
private static final String ENTITY_NAME = "splittingValue";
private final SplittingValueService splittingValueService;
public SplittingValueResource(SplittingValueService splittingValueService) {
this.splittingValueService = splittingValueService;
}
/**
* POST /splitting-values : Create a new splittingValue.
*
* @param splittingValue the splittingValue to create
* @return the ResponseEntity with status 201 (Created) and with body the new splittingValue, or with status 400 (Bad Request) if the splittingValue has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/splitting-values")
@Timed
public ResponseEntity<SplittingValue> createSplittingValue(@RequestBody SplittingValue splittingValue) throws URISyntaxException {
log.debug("REST request to save SplittingValue : {}", splittingValue);
if (splittingValue.getId() != null) {
throw new BadRequestAlertException("A new splittingValue cannot already have an ID", ENTITY_NAME, "idexists");
}
SplittingValue result = splittingValueService.save(splittingValue);
return ResponseEntity.created(new URI("/api/splitting-values/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /splitting-values : Updates an existing splittingValue.
*
* @param splittingValue the splittingValue to update
* @return the ResponseEntity with status 200 (OK) and with body the updated splittingValue,
* or with status 400 (Bad Request) if the splittingValue is not valid,
* or with status 500 (Internal Server Error) if the splittingValue couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/splitting-values")
@Timed
public ResponseEntity<SplittingValue> updateSplittingValue(@RequestBody SplittingValue splittingValue) throws URISyntaxException {
log.debug("REST request to update SplittingValue : {}", splittingValue);
if (splittingValue.getId() == null) {
return createSplittingValue(splittingValue);
}
SplittingValue result = splittingValueService.save(splittingValue);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, splittingValue.getId().toString()))
.body(result);
}
/**
* GET /splitting-values : get all the splittingValues.
*
* @return the ResponseEntity with status 200 (OK) and the list of splittingValues in body
*/
@GetMapping("/splitting-values")
@Timed
public List<SplittingValue> getAllSplittingValues() {
log.debug("REST request to get all SplittingValues");
return splittingValueService.findAll();
}
/**
* GET /splitting-values/:id : get the "id" splittingValue.
*
* @param id the id of the splittingValue to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the splittingValue, or with status 404 (Not Found)
*/
@GetMapping("/splitting-values/{id}")
@Timed
public ResponseEntity<SplittingValue> getSplittingValue(@PathVariable Long id) {
log.debug("REST request to get SplittingValue : {}", id);
SplittingValue splittingValue = splittingValueService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(splittingValue));
}
/**
* DELETE /splitting-values/:id : delete the "id" splittingValue.
*
* @param id the id of the splittingValue to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/splitting-values/{id}")
@Timed
public ResponseEntity<Void> deleteSplittingValue(@PathVariable Long id) {
log.debug("REST request to delete SplittingValue : {}", id);
splittingValueService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/splitting-values?query=:query : search for the splittingValue corresponding
* to the query.
*
* @param query the query of the splittingValue search
* @return the result of the search
*/
@GetMapping("/_search/splitting-values")
@Timed
public List<SplittingValue> searchSplittingValues(@RequestParam String query) {
log.debug("REST request to search SplittingValues for query {}", query);
return splittingValueService.search(query);
}
}
| 40.201299
| 170
| 0.716201
|
96a1f4091345a77419513d90c876640c01975f86
| 435
|
package com.fgo.utils.mvp.view;
import com.fgo.utils.bean.BaseCommonBean;
import com.fgo.utils.bean.LoginBean;
import com.fgo.utils.bean.userBean;
import com.king.frame.mvp.base.BaseView;
/**
* @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
* @date 2017/7/5
*/
public interface PersonView extends BaseView {
void showRegeistData(BaseCommonBean body);
void showLoginData(BaseCommonBean<LoginBean> body);
}
| 22.894737
| 63
| 0.754023
|
cfd41d85ee0fbccd3fce597549e470613c2dad2f
| 1,396
|
package team.zmn.repository.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import team.zmn.repository.pojo.ProductMessage;
import team.zmn.repository.pojo.ProductMessageDto;
import team.zmn.repository.pojo.Result;
import team.zmn.repository.service.ProductService;
import team.zmn.repository.service.serviceimpl.ProductServiceImpl;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
*
* @author: ZhengCheng.Wen
* Date: 2020/7/3
* Time: 9:38
*/
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService = new ProductServiceImpl();
@ResponseBody
@RequestMapping("/selectAll")
public Result selectAll(){
Result result = productService.selectAll();
return result;
}
@ResponseBody
@RequestMapping("/del")
public Object del(ProductMessageDto dto){
Map<String ,Object> map = new HashMap<>();
int insert = productService.delete(dto);
System.out.println(insert);
if (insert == 1){
map.put("result","success!");
}else{
map.put("result","fail!");
}
return map;
}
}
| 27.92
| 69
| 0.70702
|
39ab57525b09d35fdad7a1083d23336b5200fcaa
| 3,633
|
package com.mutool.commonweb.base;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mutool.commonweb.common.IdEntity;
import com.mutool.commonweb.enums.ErrorCodeEnum;
import com.mutool.core.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.util.Date;
/**
* 描述:<br>
* 作者:les<br>
* 日期:2021/4/13 22:40<br>
*/
public class BaseController<Service extends IService<T>, T extends IdEntity> {
@Resource
protected HttpServletRequest request;
@Resource
protected HttpServletResponse response;
@Autowired
protected Service baseService;
public BaseController() {
}
private static final String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 将前台传递过来的日期格式的字符串,自动转化为Date类型
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtil.parse(text, parsePatterns));
}
});
// JSONObject 类型转换
binder.registerCustomEditor(JSONObject.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(JSONUtil.parseObj(text));
}
});
// JSONArray 类型转换
binder.registerCustomEditor(JSONArray.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(JSONUtil.parseObj(text));
}
});
}
@GetMapping({"/{id}"})
public T get(@PathVariable Long id) {
return this.baseService.getById(id);
}
@PostMapping("add")
public Boolean add(@RequestBody T model) {
return this.baseService.save(model);
}
@PostMapping("update")
public Boolean update(@RequestBody T model) {
if(null == model.getId()){
throw new BizException(ErrorCodeEnum.ID_REQUIRED);
}
return this.baseService.updateById(model);
}
@PostMapping({"/remove/{id}"})
public Boolean remove(@PathVariable("id") Long id) {
return this.baseService.removeById(id);
}
public Page getPage() {
long current = 1L;
long size = 10L;
String page = this.request.getParameter("page");
if (StringUtils.isNotBlank(page)) {
Long pageNum = Long.valueOf(page);
if (pageNum > 0L) {
current = pageNum;
}
}
String limitStr = this.request.getParameter("limit");
if (StringUtils.isNotBlank(page)) {
Long limit = Long.valueOf(limitStr);
if (limit > 0L) {
size = limit;
}
}
return new Page(current, size);
}
}
| 30.788136
| 83
| 0.63281
|
e3a6ea6018c76c462f51d7f31aa91950edf3b024
| 73
|
package com.speyejack.learning.gui;
public class LinkHeritage {
}
| 12.166667
| 36
| 0.726027
|
116e8d930f609992c5983842f982ecc5ab67c09c
| 2,021
|
package io.plumery.messaging.utils;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.plumery.core.Event;
import io.plumery.core.ID;
import io.plumery.core.exception.ApplicationException;
import io.plumery.core.exception.SystemException;
public class EventUtils {
public static Event exceptionToEvent(Exception ex) {
String message = ex.getMessage();
if (ex instanceof ApplicationException) {
ApplicationException e = (ApplicationException) ex;
String id = e.getAggregateRootId().toString();
return new ApplicationErrorEvent(message, id, e.getVersion());
} else if (ex instanceof SystemException) {
SystemException e = (SystemException) ex;
return new SystemErrorEvent(message, e.getErrorEventId(), ex.getClass().getName());
}
throw new IllegalArgumentException(ex.getClass().getSimpleName() + " is not supported.");
}
public static class ApplicationErrorEvent extends Event {
public final String message;
@JsonCreator
public ApplicationErrorEvent(
@JsonProperty("message") String message,
@JsonProperty("aggregateId") String aggregateId,
@JsonProperty("version") Integer version) {
this.message = message;
this.id = ID.fromObject(aggregateId);
this.version = version;
}
}
public static class SystemErrorEvent extends Event {
public final String message;
public final String exceptionType;
@JsonCreator
public SystemErrorEvent(
@JsonProperty("message") String message,
@JsonProperty("errorEventId") String errorEventId,
@JsonProperty("exceptionType") String exceptionType) {
this.message = message;
this.id = ID.fromObject(errorEventId);
this.exceptionType = exceptionType;
}
}
}
| 35.45614
| 97
| 0.653637
|
7579ec0653e044906338e128f0054b4e55df8c0c
| 27,527
|
package com.bitwig.extensions.controllers.novation.launchpad_pro;
import java.util.ArrayList;
import java.util.List;
import com.bitwig.extension.controller.api.Clip;
import com.bitwig.extension.controller.api.CursorDevice;
import com.bitwig.extension.controller.api.CursorRemoteControlsPage;
import com.bitwig.extension.controller.api.CursorTrack;
import com.bitwig.extension.controller.api.DrumPad;
import com.bitwig.extension.controller.api.DrumPadBank;
import com.bitwig.extension.controller.api.Arpeggiator;
import com.bitwig.extension.controller.api.PinnableCursorClip;
import com.bitwig.extension.controller.api.PlayingNoteArrayValue;
import com.bitwig.extension.controller.api.RemoteControl;
import com.bitwig.extension.controller.api.SettableIntegerValue;
import com.bitwig.extension.controller.api.NoteStep;
import com.bitwig.extension.controller.api.Track;
import com.bitwig.extensions.util.NoteInputUtils;
final class DrumSequencerMode extends AbstractSequencerMode
{
DrumSequencerMode(final LaunchpadProControllerExtension driver)
{
super(driver, "drum-sequencer");
final PinnableCursorClip cursorClip = driver.mCursorClip;
mShiftLayer = new LaunchpadLayer(driver, "drum-sequencer-shift");
mDrumPadsLayer = new LaunchpadLayer(driver, "drum-pads");
mMainActionsLayer = new LaunchpadLayer(driver, "drum-main-actions");
mSceneAndPerfsLayer = new LaunchpadLayer(driver, "drum-scenes-and-perfs");
mMixDataLayer = new LaunchpadLayer(driver, "drum-seq-mix-data");
mSoundDataLayer = new LaunchpadLayer(driver, "drum-seq-sound-data");
bindLightState(LedState.DRUM_SEQ_MODE, driver.mDeviceButton);
// Step sequencer
for (int y = 0; y < 4; ++y)
{
for (int x = 0; x < 8; ++x)
{
final int X = x;
final int Y = y;
final Button bt = driver.getPadButton(x, y + 4);
final int clipStepIndex = calculateClipStepIndex(x, 3 - y);
bindPressed(bt, v -> {
bt.onButtonPressed(driver.getHost());
onStepPressed(clipStepIndex, (int) (v * 127.0));
});
bindReleased(bt, () -> {
final boolean wasHeld = bt.getButtonState() == Button.State.HOLD;
bt.onButtonReleased();
onStepReleased(clipStepIndex, wasHeld);
});
bindLightState(() -> computeStepSeqLedState(X, 3 - Y), bt);
}
final Button sceneButton = driver.mSceneButtons[y + 4];
final int page = 3 - y;
final int Y = y;
bindPressed(sceneButton, () -> {
mPage = page;
cursorClip.scrollToStep(32 * page);
});
bindLightState(() -> computePatternOffsetLedState(3 - Y), sceneButton);
final Button dataChoiceBt = driver.mSceneButtons[y];
bindPressed(dataChoiceBt, () -> setDataMode(Y));
bindLightState(() -> computeDataChoiceLedState(Y), dataChoiceBt);
}
// Scene buttons in shift layer
for (int y = 0; y < 8; ++y)
{
final Button sceneButton = driver.mSceneButtons[y];
final int page = 8 - y;
final int Y = y;
mShiftLayer.bindPressed(sceneButton, () -> setClipLength(page * 4));
mShiftLayer.bindLightState(() -> computeClipLengthSelectionLedState(7 - Y), sceneButton);
}
final SettableIntegerValue drumPosition = driver.mDrumPadBank.scrollPosition();
mShiftLayer.bindPressed(driver.mUpButton, this::drumpPadsUp);
mShiftLayer.bindPressed(driver.mDownButton, this::drumpPadsDown);
mShiftLayer.bindLightState(() -> drumPosition.get() < 116 ? LedState.PITCH : LedState.PITCH_LOW, driver.mUpButton);
mShiftLayer.bindLightState(() -> drumPosition.get() > 0 ? LedState.PITCH : LedState.PITCH_LOW, driver.mDownButton);
// Drum Pads
for (int x = 0; x < 4; ++x)
{
for (int y = 0; y < 4; ++y)
{
final int X = x;
final int Y = y;
final Button bt = driver.getPadButton(x, y);
mDrumPadsLayer.bindPressed(bt, () -> onDrumPadPressed(X, Y));
mDrumPadsLayer.bindLightState(() -> computeDrumPadLedState(X, Y), bt);
mShiftLayer.bindPressed(bt, () -> {
if (mDataMode == DataMode.Main || mDataMode == DataMode.MainAlt)
onDrumPadPressed(X, Y);
});
final Button actionBt = driver.getPadButton(x + 4, y);
mSceneAndPerfsLayer.bindLightState(() -> computePerfAndScenesLedState(X, Y), actionBt);
if (y < 2)
mSceneAndPerfsLayer.bindPressed(actionBt, () -> onDrumScenePressed(X, Y));
else
{
mSceneAndPerfsLayer.bind(actionBt.mAfterTouch, v -> onDrumPerfPressure(X, Y, (int) (127. * v)));
mSceneAndPerfsLayer.bindReleased(actionBt, () -> onDrumPerfReleased(X, Y));
}
mMainActionsLayer.bindPressed(actionBt, v -> onDrumActionPressed(X, Y, (int) (v * 127)));
mMainActionsLayer.bindReleased(actionBt, () -> onDrumActionReleased(X, Y));
if (X == 0 && Y == 2)
mMainActionsLayer.bind(actionBt.mAfterTouch, v -> onAutoNoteRepeatPressure((int) (127. * v)));
}
}
// Step Data
for (int x = 0; x < 8; ++x)
{
for (int y = 0; y < 4; ++y)
{
final int X = x;
final int Y = y;
final Button bt = driver.getPadButton(x, y);
mMixDataLayer.bindPressed(bt, () -> onMixDataPressed(X, 3 - Y));
mMixDataLayer.bindLightState(() -> computeMixDataLedState(X, Y), bt);
mSoundDataLayer.bindPressed(bt, () -> onSoundDataPressed(X, 3 - Y));
mSoundDataLayer.bindLightState(() -> computeSoundDataLedState(X, Y), bt);
}
}
mMainActionsLayer.bindLightState(() -> new LedState(isDrumPadSelectOn() ? Color.TRACK : Color.TRACK_LOW), mDriver.getPadButton(4, 0));
mMainActionsLayer.bindLightState(() -> new LedState(isDrumPadMuteOn() || mDriver.isDeleteOn() ? Color.MUTE : Color.MUTE_LOW), mDriver.getPadButton(5, 0));
mMainActionsLayer.bindLightState(() -> new LedState(isDrumPadSoloOn() || mDriver.isDeleteOn() ? Color.SOLO : Color.SOLO_LOW), mDriver.getPadButton(6, 0));
mMainActionsLayer.bindLightState(LedState.OFF, mDriver.getPadButton(7, 0));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(4, 1) ? Color.BLUE : Color.BLUE_LOW), mDriver.getPadButton(4, 1));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(5, 1) ? Color.RED : Color.RED_LOW), mDriver.getPadButton(5, 1));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(6, 1) ? Color.GREEN : Color.GREEN_LOW), mDriver.getPadButton(6, 1));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(7, 1) ? Color.WHITE : Color.WHITE_LOW), mDriver.getPadButton(7, 1));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(4, 2) ? Color.PURPLE : Color.PURPLE_LOW), mDriver.getPadButton(4, 2));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(5, 2) ? Color.ORANGE : Color.ORANGE_LOW), mDriver.getPadButton(5, 2));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(6, 2) ? Color.ORANGE : Color.ORANGE_LOW), mDriver.getPadButton(6, 2));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(7, 2) ? Color.ORANGE : Color.ORANGE_LOW), mDriver.getPadButton(7, 2));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(4, 3) ? Color.YELLOW : Color.YELLOW_LOW), mDriver.getPadButton(4, 3));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(5, 3) ? Color.YELLOW : Color.YELLOW_LOW), mDriver.getPadButton(5, 3));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(6, 3) ? Color.YELLOW : Color.YELLOW_LOW), mDriver.getPadButton(6, 3));
mMainActionsLayer.bindLightState(() -> new LedState(isActionOn(7, 3) ? Color.YELLOW : Color.YELLOW_LOW), mDriver.getPadButton(7, 3));
}
@Override
protected void doActivate()
{
super.doActivate();
final DrumPadBank drumPads = mDriver.mDrumPadBank;
drumPads.exists().subscribe();
drumPads.scrollPosition().subscribe();
drumPads.hasMutedPads().subscribe();
drumPads.hasSoloedPads().subscribe();
drumPads.subscribe();
drumPads.setIndication(true);
for (int i = 0; i < 16; ++i)
{
final DrumPad drumPad = drumPads.getItemAt(i);
drumPad.subscribe();
drumPad.exists().subscribe();
drumPad.color().subscribe();
drumPad.mute().subscribe();
drumPad.isMutedBySolo().subscribe();
drumPad.solo().subscribe();
}
final CursorDevice cursorDevice = mDriver.mCursorDevice;
cursorDevice.hasDrumPads().subscribe();
cursorDevice.subscribe();
final CursorRemoteControlsPage drumScenesRemoteControls = mDriver.mDrumScenesRemoteControls;
final CursorRemoteControlsPage drumPerfsRemoteControls = mDriver.mDrumPerfsRemoteControls;
for (int i = 0; i < 8; ++i)
{
{
final RemoteControl parameter = drumScenesRemoteControls.getParameter(i);
parameter.exists().subscribe();
parameter.value().subscribe();
parameter.subscribe();
}
{
final RemoteControl parameter = drumPerfsRemoteControls.getParameter(i);
parameter.exists().subscribe();
parameter.value().subscribe();
parameter.subscribe();
}
}
updateDrumPadsBankPosition();
setDataMode(mDataMode);
}
@Override
protected void doDeactivate()
{
deactivateEveryLayers();
final DrumPadBank drumPads = mDriver.mDrumPadBank;
drumPads.exists().unsubscribe();
drumPads.scrollPosition().unsubscribe();
drumPads.hasMutedPads().unsubscribe();
drumPads.hasSoloedPads().unsubscribe();
drumPads.unsubscribe();
drumPads.setIndication(false);
for (int i = 0; i < 16; ++i)
{
final DrumPad drumPad = drumPads.getItemAt(i);
drumPad.exists().unsubscribe();
drumPad.color().unsubscribe();
drumPad.mute().unsubscribe();
drumPad.isMutedBySolo().unsubscribe();
drumPad.solo().unsubscribe();
drumPad.unsubscribe();
}
final CursorDevice cursorDevice = mDriver.mCursorDevice;
cursorDevice.hasDrumPads().unsubscribe();
cursorDevice.unsubscribe();
final CursorRemoteControlsPage drumScenesRemoteControls = mDriver.mDrumScenesRemoteControls;
final CursorRemoteControlsPage drumPerfsRemoteControls = mDriver.mDrumPerfsRemoteControls;
for (int i = 0; i < 8; ++i)
{
{
final RemoteControl parameter = drumScenesRemoteControls.getParameter(i);
parameter.exists().unsubscribe();
parameter.value().unsubscribe();
parameter.unsubscribe();
}
{
final RemoteControl parameter = drumPerfsRemoteControls.getParameter(i);
parameter.exists().unsubscribe();
parameter.value().unsubscribe();
parameter.unsubscribe();
}
}
super.doDeactivate();
}
private void deactivateEveryLayers()
{
mShiftLayer.deactivate();
mDrumPadsLayer.deactivate();
mMainActionsLayer.deactivate();
mSceneAndPerfsLayer.deactivate();
mSoundDataLayer.deactivate();
mMixDataLayer.deactivate();
}
@Override
protected void setDataMode(final DataMode dataMode)
{
super.setDataMode(dataMode);
deactivateEveryLayers();
switch (mDataMode)
{
case Main:
mDrumPadsLayer.activate();
mMainActionsLayer.activate();
break;
case MixData:
mMixDataLayer.activate();
break;
case SoundData:
mSoundDataLayer.activate();
break;
case MainAlt:
mDrumPadsLayer.activate();
mSceneAndPerfsLayer.activate();
break;
}
}
void drumpPadsUp()
{
final DrumPadBank drumPads = mDriver.mDrumPadBank;
final SettableIntegerValue position = drumPads.scrollPosition();
if (position.get() == 0)
position.set(4);
else
position.set(Math.min(116, position.get() + 16));
updateDrumPadsBankPosition();
}
void drumpPadsDown()
{
final DrumPadBank drumPads = mDriver.mDrumPadBank;
final SettableIntegerValue position = drumPads.scrollPosition();
position.set(Math.max(0, position.get() - 16));
updateDrumPadsBankPosition();
}
private void updateDrumPadsBankPosition()
{
mDriver.updateKeyTranslationTable();
}
@Override
void updateKeyTranslationTable(final Integer[] table)
{
if (mDriver.isShiftOn() || (mDataMode != DataMode.Main && mDataMode != DataMode.MainAlt))
return;
for (int x = 0; x < 4; ++x)
{
for (int y = 0; y < 4; ++y)
{
final int tableIndex = 11 + x + y * 10;
final int note = calculateDrumPadKey(x, y);
assert note >= 0;
assert note < 128;
table[tableIndex] = note;
}
}
}
private int calculateDrumPadKey(final int x, final int y)
{
final DrumPadBank drumPadBank = mDriver.mDrumPadBank;
if (drumPadBank.exists().get())
return x + 4 * y + drumPadBank.scrollPosition().get();
return x + 4 * y + 36;
}
private void onMixDataPressed(final int x, final int y)
{
final Clip clip = mDriver.mCursorClip;
final List<Button> padsInHoldState = getStepsInPressedOrHoldState();
for (final Button button : padsInHoldState)
{
final int clipStepIndex = calculateClipStepIndex(button.mX - 1, 8 - button.mY);
final NoteStep noteStep = clip.getStep(0, clipStepIndex, mCurrentPitch);
switch (y)
{
case 0:
noteStep.setVelocity(x / 7.0);
break;
case 1:
noteStep.setDuration(computeDuration(x));
break;
case 2:
noteStep.setPan((3 <= x && x <= 4) ? 0 : (x - 3.5) / 3.5);
break;
}
}
}
private void onSoundDataPressed(final int x, final int y)
{
final Clip clip = mDriver.mCursorClip;
final List<Button> padsInHoldState = getStepsInPressedOrHoldState();
for (final Button buttonState : padsInHoldState)
{
final int clipStepIndex = calculateClipStepIndex(buttonState.mX - 1, 8 - buttonState.mY);
final NoteStep noteStep = clip.getStep(0, clipStepIndex, mCurrentPitch);
switch (y)
{
case 0:
noteStep.setTranspose(computeTranspoose(x));
break;
case 1:
noteStep.setTimbre((3 <= x && x <= 4) ? 0 : (x - 3.5) / 3.5);
break;
case 2:
noteStep.setPressure(x / 7.0);
break;
}
}
}
private void onDrumActionPressed(final int x, final int y, final int velocity)
{
if (y == 0 && (x >= 0 && x <= 2))
{
if (mDriver.isDeleteOn() && x == 1 && y == 0)
mDriver.mDrumPadBank.clearMutedPads();
if (mDriver.isDeleteOn() && x == 2 && y == 0)
mDriver.mDrumPadBank.clearSoloedPads();
mDriver.mNoteInput.setKeyTranslationTable(NoteInputUtils.NO_NOTES);
}
else if (y == 1)
{
final Clip cursorClip = mDriver.mCursorClip;
final boolean cursorClipExists = cursorClip.exists().get();
final int sceneIndex = cursorClipExists ? cursorClip.clipLauncherSlot().sceneIndex().get() : 0;
final Track track = cursorClipExists ? cursorClip.getTrack() : mDriver.mCursorTrack;
if (x == 0)
track.createNewLauncherClip(sceneIndex, 8);
else if (x == 1)
track.recordNewLauncherClip(sceneIndex);
else if (x == 2 && cursorClipExists)
cursorClip.launch();
else if (x == 3)
track.stop();
}
else if (y == 2 || y == 3)
{
final double period;
if (y == 3 || x != 0)
period = calculateNoteRepeatPeriodForPad(x, y);
else
period = calculateAutoNoteRepeatPeriod(velocity);
// Configure the Arp as a note repeat
final Arpeggiator arpeggiator = mDriver.mArpeggiator;
arpeggiator.rate().set(period);
arpeggiator.usePressureToVelocity().set(true);
arpeggiator.shuffle().set(true);
arpeggiator.mode().set("all"); // that's the note repeat way
arpeggiator.octaves().set(0);
arpeggiator.isEnabled().set(true);
arpeggiator.humanize().set(0);
arpeggiator.isFreeRunning().set(false);
mNoteRepeatStack.add(new Coord(x, y));
}
}
private double calculateNoteRepeatPeriodForPad(final int x, final int y)
{
if (y == 3)
return 1.0 / 8.0 * (1 << x);
if (y == 2 && x > 0)
return 1.0 / 6.0 * (1 << (x - 1));
return 0.25;
}
private void onAutoNoteRepeatPressure(final int pressure)
{
final Arpeggiator arpeggiator = mDriver.mArpeggiator;
arpeggiator.rate().set(calculateAutoNoteRepeatPeriod(pressure));
}
private double calculateAutoNoteRepeatPeriod(final int pressure)
{
if (pressure < 32)
return 1.0;
if (pressure < 64)
return 0.5;
if (pressure < 96)
return 0.25;
return 0.125;
}
private void onDrumActionReleased(final int x, final int y)
{
if (y == 0 && (!isDrumPadSoloOn() && !isDrumPadMuteOn() && !isDrumPadSelectOn()))
mDriver.updateKeyTranslationTable();
else if (y == 2 || y == 3)
{
final Arpeggiator arpeggiator = mDriver.mArpeggiator;
mNoteRepeatStack.removeIf(coord -> coord.x == x && coord.y == y);
if (!mNoteRepeatStack.isEmpty())
{
final Coord coord = mNoteRepeatStack.get(mNoteRepeatStack.size() - 1);
if (coord.y != 2 || coord.x != 0)
{
final double periodForPad = calculateNoteRepeatPeriodForPad(coord.x, coord.y);
arpeggiator.rate().set(periodForPad);
}
}
arpeggiator.isEnabled().set(hasNoteRepeatPadPressed());
}
}
private boolean hasNoteRepeatPadPressed()
{
for (int x = 0; x < 4; ++x)
for (int y = 0; y < 2; ++y)
if (isActionOn(4 + x, y + 2))
return true;
return false;
}
private void onDrumPerfReleased(final int x, final int y)
{
final CursorRemoteControlsPage drumPerfsRemoteControls = mDriver.mDrumPerfsRemoteControls;
final RemoteControl parameter = drumPerfsRemoteControls.getParameter(x + 4 * (3 - y));
if (!mDriver.isShiftOn() && parameter.exists().get())
parameter.set(0);
}
private void onDrumPerfPressure(final int x, final int y, final int pressure)
{
final CursorRemoteControlsPage drumPerfsRemoteControls = mDriver.mDrumPerfsRemoteControls;
final RemoteControl parameter = drumPerfsRemoteControls.getParameter(x + 4 * (3 - y));
if (!mDriver.isShiftOn() && parameter.exists().get())
parameter.set(pressure / 127.0);
}
private void onDrumPerfPressed(final int x, final int y)
{
}
private void onDrumScenePressed(final int x, final int y)
{
final int paramIndex = x + 4 * (1 - y);
final CursorRemoteControlsPage scenesRemoteControls = mDriver.mDrumScenesRemoteControls;
final RemoteControl parameter = scenesRemoteControls.getParameter(paramIndex);
if (parameter.exists().get() && parameter.get() != 0)
{
parameter.set(0);
return;
}
if (!mDriver.isShiftOn())
{
for (int i = 0; i < 8; ++i)
{
if (i == paramIndex)
continue;
final RemoteControl otherParam = scenesRemoteControls.getParameter(i);
if (otherParam.exists().get())
otherParam.set(0);
}
}
if (parameter.exists().get())
parameter.set(1);
}
private void onStepPressed(final int absoluteStep, final int velocity)
{
final Clip cursorClip = mDriver.mCursorClip;
if (mDriver.isShiftOn())
setClipLength((absoluteStep + 1) / 4.0);
else if (mDriver.isDeleteOn())
cursorClip.clearStep(absoluteStep, mCurrentPitch);
else
{
final NoteStep noteStep = cursorClip.getStep(0, absoluteStep, mCurrentPitch);
if (noteStep.state() != NoteStep.State.NoteOn)
{
cursorClip.setStep(absoluteStep, mCurrentPitch, velocity, 1.0 / 4.0);
mStepsBeingAdded.add(absoluteStep);
}
}
}
private void onStepReleased(final int absoluteStep, final boolean wasHeld)
{
final Clip cursorClip = mDriver.mCursorClip;
if (mDriver.isShiftOn() || mDriver.isDeleteOn())
return;
final NoteStep noteStep = cursorClip.getStep(0, absoluteStep, mCurrentPitch);
if (noteStep.state() == NoteStep.State.NoteOn && !wasHeld && !mStepsBeingAdded.contains(absoluteStep))
cursorClip.clearStep(absoluteStep, mCurrentPitch);
mStepsBeingAdded.remove(absoluteStep);
}
private void onDrumPadPressed(final int x, final int y)
{
final int key = calculateDrumPadKey(x, y);
if (mDriver.isDeleteOn())
mDriver.mCursorClip.clearStepsAtY(0, key);
else if (isDrumPadMuteOn())
{
final DrumPadBank drumPadBank = mDriver.mDrumPadBank;
final DrumPad drumPad = drumPadBank.getItemAt(x + 4 * y);
drumPad.mute().toggle();
}
else if (isDrumPadSoloOn())
{
final DrumPadBank drumPadBank = mDriver.mDrumPadBank;
final DrumPad drumPad = drumPadBank.getItemAt(x + 4 * y);
drumPad.solo().toggle();
}
else if (isDrumPadSelectOn() || mDriver.isShiftOn())
{
final DrumPadBank drumPadBank = mDriver.mDrumPadBank;
final DrumPad drumPad = drumPadBank.getItemAt(x + 4 * y);
drumPad.selectInEditor();
mCurrentPitch = key;
}
else
mCurrentPitch = key;
}
private boolean isActionOn(final int x, final int y)
{
if (mDataMode != DataMode.Main)
return false;
final Button button = mDriver.getPadButton(x, y);
return button.mButton.isPressed().get();
}
private boolean isDrumPadSelectOn()
{
return isActionOn(4, 0);
}
private boolean isDrumPadSoloOn()
{
return isActionOn(6, 0);
}
private boolean isDrumPadMuteOn()
{
return isActionOn(5, 0);
}
@Override
protected NoteStep findStepInfo(final int clipStepIndex)
{
return mDriver.mCursorClip.getStep(0, clipStepIndex, mCurrentPitch);
}
private LedState computePerfAndScenesLedState(final int x, final int y)
{
final CursorRemoteControlsPage drumPerfsRemoteControls = mDriver.mDrumPerfsRemoteControls;
final CursorRemoteControlsPage drumScenesRemoteControls = mDriver.mDrumScenesRemoteControls;
if (y > 1)
{
final RemoteControl perfParam = drumPerfsRemoteControls.getParameter(x + (3 - y) * 4);
if (perfParam.exists().get())
return new LedState(Color.scale(Color.CYAN, (float) (0.95 * perfParam.get() + 0.05)));
}
else
{
final RemoteControl sceneParam = drumScenesRemoteControls.getParameter(x + (1 - y) * 4);
if (sceneParam.exists().get())
return new LedState(Color.scale(Color.YELLOW, (float) (0.9 * sceneParam.get() + 0.1)));
}
return LedState.OFF;
}
private LedState computeStepSeqLedState(final int x, final int y)
{
final Clip clip = mDriver.mCursorClip;
final int playingStep = clip.playingStep().get();
final NoteStep noteStep = clip.getStep(0, calculateClipStepIndex(x, y), mCurrentPitch);
if (playingStep == mPage * 32 + 8 * y + x)
return new LedState(noteStep.state() == NoteStep.State.NoteOn ? Color.STEP_PLAY : Color.STEP_PLAY_HEAD);
if (mDriver.getPadButton(x, 7- y).getButtonState() == Button.State.HOLD)
return new LedState(Color.STEP_HOLD);
switch (noteStep.state())
{
case NoteOn:
return new LedState(Color.STEP_ON);
case NoteSustain:
return new LedState(Color.STEP_SUSTAIN);
case Empty:
return new LedState(Color.STEP_OFF);
}
throw new IllegalStateException();
}
private LedState computeDrumPadLedState(final int x, final int y)
{
final Clip clip = mDriver.mCursorClip;
final PlayingNoteArrayValue playingNotes = mDriver.mCursorTrack.playingNotes();
final CursorDevice cursorDevice = mDriver.mCursorDevice;
final boolean hasDrumPads = cursorDevice.hasDrumPads().get();
final DrumPadBank drumPads = mDriver.mDrumPadBank;
final int pitch = calculateDrumPadKey(x, y);
final boolean isPlaying = playingNotes.isNotePlaying(pitch);
final DrumPad drumPad = drumPads.getItemAt(x + 4 * y);
final boolean drumPadExists = hasDrumPads & drumPad.exists().get();
final boolean drumPadIsSolo = drumPadExists & drumPad.solo().get();
final boolean drumPadIsMuted = drumPadExists & !drumPadIsSolo & (drumPad.mute().get() | drumPad.isMutedBySolo().get());
final Color color = new Color(drumPad.color());
if (isPlaying)
return new LedState(drumPadIsMuted ? Color.GREEN_LOW : Color.GREEN);
if (mCurrentPitch == pitch)
return new LedState(drumPadIsMuted ? Color.TRACK_LOW : Color.TRACK);
if (hasDrumPads)
{
if (drumPadExists)
return new LedState(drumPadIsSolo ? Color.YELLOW : drumPadIsMuted ? Color.scale(color, .1f) : color);
else
return new LedState(Color.WHITE_LOW);
}
return new LedState(clip.color());
}
@Override
protected String getDataModeDescription(final DataMode dataMode)
{
switch (dataMode)
{
case Main:
return "Drum Sequencer: Note Repeat, Solo, Mute";
case MainAlt:
return "Drum Sequencer: Perfs, Scenes";
case MixData:
return "Drum Sequencer: Velocity, Note Length, Pan";
case SoundData:
return "Drum Sequencer: Pich Offset, Timbre, Pressure";
default:
return "Error";
}
}
private void invalidateDrumPosition(final int newPosition)
{
mCurrentPitch = newPosition;
updateDrumPadsBankPosition();
}
private static class Coord
{
Coord(final int x_, final int y_)
{
x = x_;
y = y_;
}
final int x;
final int y;
}
private final List<Coord> mNoteRepeatStack = new ArrayList<>();
private int mCurrentPitch = 36;
private final LaunchpadLayer mShiftLayer;
private final LaunchpadLayer mDrumPadsLayer;
private final LaunchpadLayer mSceneAndPerfsLayer;
private final LaunchpadLayer mMainActionsLayer;
private final LaunchpadLayer mMixDataLayer;
private final LaunchpadLayer mSoundDataLayer;
}
| 35.291026
| 160
| 0.621208
|
96cd97a0500ee87e1c40af1ecc3374be03f61ee9
| 1,516
|
/**
*
*/
package me.learn.personal.month3;
/**
* Title 1254 :
*
* Date : Jan 1, 2021
*
* @author bramanarayan
*
*/
public class NumberOfClosedIslands {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
int[] row = new int[] { 1, -1, 0, 0 };
int[] col = new int[] { 0, 0, 1, -1 };
// a closed island is surrounded with 1's all together.\
// we will basically start with perimeter
public int closedIsland(int[][] a) {
int res = 0;
int m = a.length;
int n = a[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// initiate a flood fill for '0' th cell
if (a[i][j] == 0) {
// add only if this do not touch PERIMETER
if (dfs(a, i, j))
res++;
}
}
}
return res;
}
public boolean dfs(int[][] grid, int i, int j) {
// out of range
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)
// THIS IS THE KEY TO CATCH THE PERIMETER. ONE SHOULD NEVER HIT HERE FOR A CLOSED ISLAND.
return false;
// if its 1, all good
if (grid[i][j] == 1)
return true;
grid[i][j] = 1;
boolean res = true;
for (int k = 0; k < 4; k++) {
res = res & dfs(grid, i + row[k], j + col[k]);
}
return res;
}
// the other approach is :
// eliminate all the islands that touch the perimeter bounadry of matrix. Probably mark with -1 or something
// Now, again invoke the floodfill search for '0', keep track of count to get # of closed islands.
}
| 19.435897
| 109
| 0.565303
|
055276b243644b2b84ef033e737f0cadc1379a2b
| 9,105
|
package org.openecomp.sdc.be.components.impl.utils;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
import org.openecomp.sdc.be.components.validation.AnnotationValidator;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
import org.openecomp.sdc.common.util.ZipUtil;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class YamlTemplateParsingHandlerTest {
private final static String VFC_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup";
private final static String HEAT_GROUP_TYPE = "org.openecomp.groups.heat.HeatStack";
private final static String ROOT_GROUP_TYPE = "tosca.groups.Root";
private final static GroupTypeDefinition VfcInstanceGroupType = buildVfcInstanceGroupType();
private final static GroupTypeDefinition heatGroupType = buildHeatStackGroupType();
private final static GroupTypeDefinition rootGroupType = buildRootGroupType();
private final static String CAPABILITY_TYPE = "org.openecomp.capabilities.VLANAssignment";
private final static String CAPABILITY_NAME = "vlan_assignment";
public static final String csarsFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "csars" ;
private YamlTemplateParsingHandler handler;
private AnnotationBusinessLogic annotationBusinessLogic;
@Mock
private ComponentsUtils componentsUtils;
@Mock
private GroupTypeBusinessLogic groupTypeBusinessLogic;
@Mock
private AnnotationTypeOperations annotationTypeOperations;
@Mock
private AnnotationValidator annotationValidator;
@Mock
private TitanDao titanDao;
@Before
public void init(){
annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations, annotationValidator);
handler = new YamlTemplateParsingHandler(titanDao, groupTypeBusinessLogic, annotationBusinessLogic);
}
@Test
public void parseResourceInfoFromYAMLTest(){
Path path = Paths.get(csarsFilePath + File.separator + "with_groups.csar");
try {
Map<String, byte[]> csar = ZipUtil.readZip(Files.readAllBytes(path));
String fileName = "MainServiceTemplate.yaml";
Optional<String> keyOp = csar.keySet().stream().filter(k -> k.endsWith(fileName)).findAny();
byte[] mainTemplateService = csar.get(keyOp.get());
Properties props = new Properties();
String resourceYml = new String(mainTemplateService);
props.load(new StringReader(resourceYml.replace("\\","\\\\")));
Resource resource = new Resource();
stubGetGroupType();
ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(fileName, resourceYml, new HashMap<>(), new HashMap<>(), "");
validateParsedYaml(parsedYaml);
} catch (IOException e) {
e.printStackTrace();
}
}
private void validateParsedYaml(ParsedToscaYamlInfo parsedYaml) {
assertThat(parsedYaml).isNotNull();
assertThat(parsedYaml.getGroups()).isNotNull().containsKey("x_group");
assertThat(parsedYaml.getGroups().get("x_group")).isNotNull();
assertThat(parsedYaml.getGroups().get("x_group").getProperties()).isNotNull();
assertThat(parsedYaml.getGroups().get("x_group").getProperties()
.stream()
.map(PropertyDataDefinition::getName)
.collect(Collectors.toList()))
.containsAll(Lists.newArrayList("vfc_parent_port_role", "network_collection_function", "vfc_instance_group_function", "subinterface_role"));
assertThat(parsedYaml.getGroups().get("x_group").getCapabilities()
.get(CAPABILITY_TYPE)
.get(0).getProperties().get(0).getValue()).isEqualTo("success");
assertThat(parsedYaml.getGroups().get("x_group").getProperties()
.stream()
.map(PropertyDataDefinition::getName)
.collect(Collectors.toList()))
.containsAll(Lists.newArrayList("vfc_parent_port_role", "network_collection_function", "vfc_instance_group_function", "subinterface_role"));
assertThat(parsedYaml.getGroups().get("x_group").getCapabilities()).isNotNull();
assertThat(parsedYaml.getGroups().get("x_group").getMembers()).isNotNull();
}
private void stubGetGroupType() {
when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE))).thenReturn(VfcInstanceGroupType);
when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE))).thenReturn(heatGroupType);
when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(ROOT_GROUP_TYPE))).thenReturn(rootGroupType);
// when(annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(any(Map.class))).thenReturn(null);
}
private static GroupTypeDefinition buildRootGroupType() {
GroupTypeDefinition groupType = new GroupTypeDefinition();
groupType.setType(ROOT_GROUP_TYPE);
groupType.setDescription("The TOSCA Group Type all other TOSCA Group Types derive from");
return groupType;
}
private static GroupTypeDefinition buildHeatStackGroupType() {
GroupTypeDefinition groupType = new GroupTypeDefinition();
groupType.setType(HEAT_GROUP_TYPE);
groupType.setDerivedFrom("tosca.groups.Root");
groupType.setDescription("Grouped all heat resources which are in the same heat stack");
GroupProperty property1 = new GroupProperty();
property1.setName("heat_file");
property1.setType("string");
property1.setRequired(true);
property1.setDescription("Heat file which associate to this group/heat stack");
property1.setStatus("SUPPORTED");
GroupProperty property2 = new GroupProperty();
property2.setName("description");
property2.setType("string");
property2.setRequired(true);
property2.setDescription("group description");
property2.setStatus("SUPPORTED");
groupType.setProperties(Lists.newArrayList(property1, property2));
return groupType;
}
private static GroupTypeDefinition buildVfcInstanceGroupType() {
GroupTypeDefinition groupType = new GroupTypeDefinition();
groupType.setType(VFC_GROUP_TYPE);
groupType.setDerivedFrom("tosca.groups.Root");
groupType.setDescription("groups VFCs with same parent port role");
GroupProperty property1 = new GroupProperty();
property1.setName("vfc_instance_group_function");
property1.setType("string");
property1.setRequired(true);
property1.setDescription("function of this VFC group");
GroupProperty property2 = new GroupProperty();
property2.setName("vfc_parent_port_role");
property2.setType("string");
property2.setRequired(true);
property2.setDescription("common role of parent ports of VFCs in this group");
GroupProperty property3 = new GroupProperty();
property3.setName("network_collection_function");
property3.setType("string");
property3.setRequired(true);
property3.setDescription("network collection function assigned to this group");
GroupProperty property4 = new GroupProperty();
property4.setName("subinterface_role");
property4.setType("string");
property4.setRequired(true);
property4.setDescription("common role of subinterfaces of VFCs in this group, criteria the group is created");
groupType.setProperties(Lists.newArrayList(property1, property2, property3, property4));
CapabilityDefinition capability = new CapabilityDefinition();
capability.setType(CAPABILITY_TYPE);
capability.setName(CAPABILITY_NAME);
ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty();
capabilityProperty.setName("vfc_instance_group_reference");
capabilityProperty.setType("string");
capability.setProperties(Arrays.asList(capabilityProperty));
Map<String, CapabilityDefinition> capabilityMap = new HashMap<>();
capabilityMap.put(CAPABILITY_NAME, capability);
groupType.setCapabilities(capabilityMap);
return groupType;
}
}
| 46.692308
| 188
| 0.736409
|
846177ea2c41eefcc9102fc4fb978d5840987e3c
| 556
|
package com.jfeat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created on 2020/8/7.
*
* @author Wen Hao
*/
@SpringBootApplication
public class AmApplication {
protected final static Logger logger = LoggerFactory.getLogger(AmApplication.class);
public static void main(String[] args) {
SpringApplication.run(AmApplication.class, args);
logger.info("io application is success!");
}
}
| 25.272727
| 88
| 0.75
|
12438b8cd2e3e7764a0063a978e87ad19042a8a2
| 5,959
|
package com.github.mealsquad.listeners;
import com.github.mealsquad.guild.GuildMusicManager;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.managers.AudioManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class CommandListener extends ListenerAdapter {
private static final Logger log = LogManager.getFormatterLogger();
private final AudioPlayerManager playerManager;
private final Map<Long, GuildMusicManager> musicManagers;
public CommandListener() {
this.musicManagers = new HashMap<>();
this.playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager);
}
private synchronized GuildMusicManager getGuildAudioPlayer(Guild guild) {
long guildId = Long.parseLong(guild.getId());
log.info("Getting Audio Player for Guild with Id: %s", guildId);
GuildMusicManager musicManager = musicManagers.get(guildId);
if (musicManager == null) {
musicManager = new GuildMusicManager(playerManager);
musicManagers.put(guildId, musicManager);
}
guild.getAudioManager().setSendingHandler(musicManager.getSendHandler());
return musicManager;
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
String[] command = event.getMessage().getContentRaw().split(" ", 2);
Guild guild = event.getGuild();
if (guild != null) {
if (";play".equals(command[0]) && command.length == 2) {
loadAndPlay(event.getTextChannel(), command[1], event.getAuthor());
} else if (";skip".equals(command[0])) {
skipTrack(event.getTextChannel());
} else if (";stop".equals(command[0])) {
stopTrack(event.getTextChannel());
}
}
super.onMessageReceived(event);
}
private void loadAndPlay(final TextChannel channel, final String trackUrl, final User user) {
GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild());
playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
channel.sendMessage("Adding to queue " + track.getInfo().title).queue();
log.info("Adding Track: %s to queue, requested by %s", track.getInfo().title, user.getName());
play(channel.getGuild(), musicManager, track, user);
}
@Override
public void playlistLoaded(AudioPlaylist playlist) {
AudioTrack firstTrack = playlist.getSelectedTrack();
if (firstTrack == null) {
firstTrack = playlist.getTracks().get(0);
}
channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue();
play(channel.getGuild(), musicManager, firstTrack, user);
}
@Override
public void noMatches() {
channel.sendMessage("Nothing found by " + trackUrl).queue();
}
@Override
public void loadFailed(FriendlyException exception) {
channel.sendMessage("Could not play: " + exception.getMessage()).queue();
}
});
}
private void play(Guild guild, GuildMusicManager musicManager, AudioTrack track, User user) {
connectToUserOccupiedVoiceChannel(guild.getAudioManager(), user);
musicManager.scheduler.queue(track);
}
private void skipTrack(TextChannel channel) {
GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild());
musicManager.scheduler.nextTrack();
channel.sendMessage("Skipped to next track.").queue();
}
private void stopTrack(TextChannel channel) {
GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild());
musicManager.player.stopTrack();
channel.sendMessage("Stopping track").queue();
}
private static void connectToUserOccupiedVoiceChannel(AudioManager audioManager, User user) {
if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) {
for (VoiceChannel voiceChannel : audioManager.getGuild().getVoiceChannels()) {
if (voiceChannel.getMembers().stream().map(Member::getEffectiveName).collect(Collectors.toList()).contains(user.getName())) {
audioManager.openAudioConnection(voiceChannel);
log.info("Established audio connection with Voice Channel %s in Guild %s", voiceChannel.getName(), voiceChannel.getGuild().getName());
break;
} else {
log.warn("Requesting user %s not present in Voice Channel: %s", user.getName(), voiceChannel.getName());
}
}
}
}
}
| 41.671329
| 154
| 0.671254
|
8a6eb522bb7e4a633e58a3641fcf1cd63beaf734
| 1,297
|
package com.salwa;
import com.salwa.model.Game;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@ApplicationScoped
public class GameStoreManagementService implements GameManage{
private List<Game> gameList = new ArrayList<>();
public List<Game> getGameList() {
return gameList;
}
@Override
public void delete(@Observes @DeleteEvent Game witcher) {
gameList.remove(witcher);
}
@Override
public void add(@Observes @AddEvent Game witcher) {
gameList.add(witcher);
}
@Override
public List<Game> getGame() {
return gameList;
}
private Boolean checkAndUpdateGameIfExit(Game game) {
Optional<Game> gameOptional = this.gameList.stream().filter(g -> g.getName().equals(game.getName())).findFirst();
if (gameOptional.isPresent()) {
Game gameFounded = gameOptional.get();
int index = gameList.indexOf(gameFounded);
gameFounded.setQuantityStore(gameFounded.getQuantityStore() + game.getQuantityStore());
gameList.set(index, gameFounded);
return true;
}
return false;
}
}
| 24.942308
| 121
| 0.669237
|
5561865c3adf885da7ce16ea6a09f134b67fe3df
| 264
|
package mybatis.entity;
import lombok.Data;
import java.util.Date;
@Data
public class UserEntity {
private Long id;
private String name;
private Date createTime;
private String password;
private String phone;
private String nickName;
}
| 15.529412
| 28
| 0.719697
|
013c16491a414ac59c2c0e1dc56cfef66081d217
| 8,239
|
package hr.fer.vizualizacijaRNA;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class RnaMenuBar extends JMenuBar{
private final Display display;
private JMenuItem menuFASTA;
private JMenuItem menuSAM;
private JMenuItem menuAnnotation;
private JMenuItem menuFindRead;
private JMenuItem menuFindAnnotation;
private Read previousRead;
private Annotation previousAnnotation;
public RnaMenuBar(Display d){
display = d;
FileLoader.setDisplay(d);
JMenu file = new JMenu("File");
JMenu view = new JMenu("View");
menuFASTA = new JMenuItem("Load FASTA File");
openFASTA(menuFASTA);
menuSAM = new JMenuItem("Load SAM File");
menuSAM.setEnabled(false);
openSAM(menuSAM);
menuAnnotation = new JMenuItem("Load annotation file");
menuAnnotation.setEnabled(false);
openBED(menuAnnotation);
file.add(menuFASTA);
file.add(menuSAM);
file.add(menuAnnotation);
menuFindRead = new JMenuItem("Find read");
menuFindRead.setEnabled(false);
findRead(menuFindRead);
menuFindAnnotation = new JMenuItem("Find annotation");
menuFindAnnotation.setEnabled(false);
findAnnotation(menuFindAnnotation);
view.add(menuFindRead);
view.add(menuFindAnnotation);
this.add(file);
this.add(view);
}
private void openFASTA(final JMenuItem item){
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
FileFilter ff = new FileNameExtensionFilter("All FASTA files", "fasta", "fa", "fna", "ffn", "faa", "frn");
fileChooser.addChoosableFileFilter(ff);
fileChooser.setFileFilter(ff);
int result = fileChooser.showOpenDialog(item);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
FileLoader.loadFASTA(selectedFile);
}
}
});
}
private void openSAM(final JMenuItem item){
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
FileFilter ff = new FileNameExtensionFilter("All SAM files", "sam");
fileChooser.addChoosableFileFilter(ff);
fileChooser.setFileFilter(ff);
int result = fileChooser.showOpenDialog(item);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
FileLoader.loadSAM(selectedFile);
}
}
});
}
private void openBED(final JMenuItem item){
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
FileFilter ff = new FileNameExtensionFilter("All annotation files", "bed");
fileChooser.addChoosableFileFilter(ff);
fileChooser.setFileFilter(ff);
int result = fileChooser.showOpenDialog(item);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
FileLoader.loadBED(selectedFile);
}
}
});
}
//popup prozori i sama pretraga anotacija
private void findAnnotation(final JMenuItem item){
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String filter = JOptionPane.showInputDialog(null, "Enter annotation name:", "", JOptionPane.PLAIN_MESSAGE, null, null, "").toString();
if(filter == null)
return;
else if(filter.equals("")){
JOptionPane.showMessageDialog(null, "Didn't enter a name");
return;
}
final ArrayList<Annotation> filteredAnnotations = new ArrayList<>();
for(Annotation a : display.getAnnotations().getCurrentAnnotationList()){
if(a.getName().toLowerCase().contains(filter.toLowerCase())){
filteredAnnotations.add(a);
}
}
if(filteredAnnotations.isEmpty()){
JOptionPane.showMessageDialog(null, "No annotations found");
return;
}
int numberOfMatches = filteredAnnotations.size();
String message = "Found " + numberOfMatches + " matches.";
JButton next = new JButton("Find next");
Object[] dialogObjects = new Object[]{message, next};
next.addActionListener(new SearchButtonListener(numberOfMatches, dialogObjects) {
@Override
public void actionPerformed(ActionEvent arg0) {
if(getCurrentMatch() + 1 > getNumberOfMatches())
setCurrentMatch(1);
else
increment();
Annotation matchedAnnotation = filteredAnnotations.get(getCurrentMatch() - 1);
matchedAnnotation.setFindHighlighted(true);
previousAnnotation.setFindHighlighted(false);
display.getAnnotations().setvPos(matchedAnnotation.getvPos());
VisualizationControl.positionChanged(matchedAnnotation.getStart(), VisualizationControl.getReadvPos());
previousAnnotation = matchedAnnotation;
}
});
filteredAnnotations.get(0).setFindHighlighted(true);
previousAnnotation = filteredAnnotations.get(0);
display.getAnnotations().setvPos(filteredAnnotations.get(0).getvPos());
VisualizationControl.positionChanged(filteredAnnotations.get(0).getStart(), VisualizationControl.getReadvPos());
JOptionPane.showMessageDialog(null, dialogObjects);
previousAnnotation.setFindHighlighted(false);
display.getAnnotations().repaint();
}
});
}
//popup prozori i sama pretraga očitanja
private void findRead(final JMenuItem item){
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String filter = JOptionPane.showInputDialog(null, "Enter read name:", "", JOptionPane.PLAIN_MESSAGE, null, null, "").toString();
if(filter == null)
return;
else if(filter.equals("")){
JOptionPane.showMessageDialog(null, "Didn't enter a name");
return;
}
final ArrayList<Read> filteredReads = new ArrayList<>();
for(Read r : display.getReads().getCurrentReadList()){
if(r.getName().toLowerCase().contains(filter.toLowerCase())){
filteredReads.add(r);
}
}
if(filteredReads.isEmpty()){
JOptionPane.showMessageDialog(null, "No reads found");
return;
}
int numberOfMatches = filteredReads.size();
String message = "Found " + numberOfMatches + " matches.";
JButton next = new JButton("Find next");
Object[] dialogObjects = new Object[]{message, next};
next.addActionListener(new SearchButtonListener(numberOfMatches, dialogObjects) {
@Override
public void actionPerformed(ActionEvent arg0) {
if(getCurrentMatch() + 1 > getNumberOfMatches())
setCurrentMatch(1);
else
increment();
String message = "Found " + getNumberOfMatches() + " matches.";
setMessage(message);
Read matchedRead = filteredReads.get(getCurrentMatch() - 1);
matchedRead.setFindHighlighted(true);
VisualizationControl.positionChanged(matchedRead.getPosStart(), matchedRead.getvPos());
previousRead.setFindHighlighted(false);
previousRead = matchedRead;
}
});
filteredReads.get(0).setFindHighlighted(true);
VisualizationControl.positionChanged(filteredReads.get(0).getPosStart(), filteredReads.get(0).getvPos());
previousRead = filteredReads.get(0);
JOptionPane.showMessageDialog(null, dialogObjects);
previousRead.setFindHighlighted(false);
display.getReads().repaint();
}
});
}
public void fastaLoaded(boolean isLoaded){
menuSAM.setEnabled(isLoaded);
menuAnnotation.setEnabled(isLoaded);
}
public void readsLoaded(boolean isLoaded){
menuFindRead.setEnabled(isLoaded);
}
public void annotationsLoaded(boolean isLoaded){
menuFindAnnotation.setEnabled(isLoaded);
}
}
| 30.973684
| 137
| 0.724481
|
d7eb52d93d51a828099c5e3a038eb1e8d4b236ff
| 9,439
|
/*
* Copyright 2017 Sphereon B.V.
*
* 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.jclouds.xillio.engine.blobstore.functions;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.hash.HashCode;
import com.google.inject.Inject;
import org.jclouds.blobstore.domain.MutableBlobMetadata;
import org.jclouds.blobstore.domain.MutableStorageMetadata;
import org.jclouds.blobstore.domain.StorageType;
import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;
import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;
import org.jclouds.domain.Location;
import org.jclouds.io.MutableContentMetadata;
import org.jclouds.xillio.engine.model.ContainerDecorator;
import org.jclouds.xillio.engine.model.CreatedDecorator;
import org.jclouds.xillio.engine.model.DescriptionDecorator;
import org.jclouds.xillio.engine.model.Entity;
import org.jclouds.xillio.engine.model.FileDecorator;
import org.jclouds.xillio.engine.model.FileSystemDecorator;
import org.jclouds.xillio.engine.model.HashDecorator;
import org.jclouds.xillio.engine.model.MimeTypeDecorator;
import org.jclouds.xillio.engine.model.ModifiedDecorator;
import org.jclouds.xillio.engine.model.ParentDecorator;
import org.jclouds.xillio.engine.model.PropertiesDecorator;
import org.jclouds.xillio.engine.model.VersionDecorator;
import org.jclouds.xillio.engine.reference.XillioConstants;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.HASH_MD5;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.HASH_SHA1;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.HASH_SHA256;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.VERSION_TAG;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.CONTAINER_HAS_CHILDREN;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.DESCRIPTION_SHORT;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.FILE_SYSTEM_PATH;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.DecoratorName.MIME_TYPE_TYPE;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.Kind.CONTAINER;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.Kind.FILE_SYSTEM;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.Kind.FOLDER;
import static org.jclouds.xillio.engine.reference.XillioConstants.Domain.Kind.CONFIGURATION;
public class EntityToStorageMetadataImpl<T extends MutableStorageMetadata> implements Function<Entity, T> {
public static final String PATH_REGEX = "http.*\\/v2\\/entities\\/([^\\/]+)\\/?(.*)";
private Supplier<Location> defaultLocation;
public EntityToStorageMetadataImpl() {
}
@Inject
EntityToStorageMetadataImpl(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation;
}
public T apply(Entity fromEntity) {
T toMetadata = getTypedMetadata(fromEntity);
addDefaultMetadata(fromEntity, toMetadata);
addUserMetadata(fromEntity, toMetadata);
return toMetadata;
}
private String extractContainer(ParentDecorator parent) {
if (parent == null || parent.getId() == null) {
return null;
}
return parent.getId().replaceFirst(PATH_REGEX, "$1");
}
private String extractName(Entity fromEntity) {
if (fromEntity == null || fromEntity.getId() == null) {
return null;
}
boolean container = FILE_SYSTEM.getEntityValue().equals(fromEntity.getKind()) || CONTAINER.getEntityValue().equals(fromEntity.getKind());
return fromEntity.getId().replaceFirst(PATH_REGEX, container ? "$1" : "$2");
}
private T getTypedMetadata(Entity fromEntity) {
T toMetadata;
if (isKind(fromEntity, XillioConstants.Domain.Kind.FILE)) {
MutableBlobMetadata blobMetadata = new MutableBlobMetadataImpl();
blobMetadata.setPublicUri(URI.create(fromEntity.getId()));
ParentDecorator parent = fromEntity.getModified().getParent();
if (parent != null) {
blobMetadata.setContainer(extractContainer(parent));
}
addContentMetadata(fromEntity, blobMetadata);
toMetadata = (T) blobMetadata;
toMetadata.setType(StorageType.BLOB);
} else if (isKind(fromEntity, FOLDER)) {
toMetadata = (T) new MutableStorageMetadataImpl();
toMetadata.setType(StorageType.FOLDER);
} else if (isKind(fromEntity, CONFIGURATION) || isKind(fromEntity, CONTAINER) || isKind(fromEntity, FILE_SYSTEM)) {
toMetadata = (T) new MutableStorageMetadataImpl();
toMetadata.setType(StorageType.CONTAINER);
} else {
throw new RuntimeException(String.format("Unsupported metadata type found: %s for entity with id %s", fromEntity.getKind(), fromEntity.getId()));
}
return toMetadata;
}
private void addContentMetadata(Entity fromEntity, MutableBlobMetadata blobMetadata) {
MutableContentMetadata contentMetadata = blobMetadata.getContentMetadata();
MimeTypeDecorator mimeType = fromEntity.getModified().getMimeType();
FileDecorator file = fromEntity.getModified().getFile();
HashDecorator hash = fromEntity.getModified().getHash();
if (mimeType != null) {
contentMetadata.setContentType(mimeType.getType());
}
if (hash != null) {
contentMetadata.setContentMD5(HashCode.fromString(hash.getMd5()));
}
if (file != null) {
contentMetadata.setContentLength(file.getSize().longValue());
}
}
private void addDefaultMetadata(Entity fromEntity, T toMetadata) {
toMetadata.setLocation(defaultLocation == null ? null : defaultLocation.get());
toMetadata.setId(fromEntity.getId());
toMetadata.setUri(URI.create(fromEntity.getId()));
CreatedDecorator created = fromEntity.getModified().getCreated();
String name = extractName(fromEntity);
FileDecorator file = fromEntity.getModified().getFile();
ModifiedDecorator modified = fromEntity.getModified().getModified();
if (name != null) {
toMetadata.setName(name);
} else {
toMetadata.setName(fromEntity.getId());
}
if (created != null) {
toMetadata.setCreationDate(Date.from(created.getDate().toInstant()));
}
if (modified != null) {
toMetadata.setLastModified(Date.from(modified.getDate().toInstant()));
}
if (file != null) {
toMetadata.setSize(file.getSize().longValue());
}
}
private void addUserMetadata(Entity fromEntity, T toMetadata) {
HashDecorator hash = fromEntity.getModified().getHash();
VersionDecorator version = fromEntity.getModified().getVersion();
DescriptionDecorator description = fromEntity.getModified().getDescription();
PropertiesDecorator properties = fromEntity.getModified().getProperties();
ContainerDecorator container = fromEntity.getModified().getContainer();
FileSystemDecorator fileSystem = fromEntity.getModified().getFilesystem();
MimeTypeDecorator mimeType = fromEntity.getModified().getMimeType();
Map<String, String> userMetadata = new HashMap<>();
if (hash != null) {
userMetadata.put(HASH_MD5.getMetadataKey(), hash.getMd5());
userMetadata.put(HASH_SHA1.getMetadataKey(), hash.getSha1());
userMetadata.put(HASH_SHA256.getMetadataKey(), hash.getSha256());
}
if (version != null) {
userMetadata.put(VERSION_TAG.getMetadataKey(), version.getTag());
}
if (description != null) {
userMetadata.put(DESCRIPTION_SHORT.getMetadataKey(), description.getShort());
}
if (container != null) {
userMetadata.put(CONTAINER_HAS_CHILDREN.getMetadataKey(), Boolean.toString(container.getHasChildren()));
}
if (fileSystem != null) {
userMetadata.put(FILE_SYSTEM_PATH.getMetadataKey(), fileSystem.getPath());
}
if (mimeType != null) {
userMetadata.put(MIME_TYPE_TYPE.getMetadataKey(), mimeType.getType());
}
if (properties != null && !properties.isEmpty()) {
userMetadata.putAll(properties);
}
toMetadata.setUserMetadata(userMetadata);
}
private boolean isKind(Entity fromEntity, XillioConstants.Domain.Kind kind) {
return kind != null && kind.is(fromEntity.getKind());
}
}
| 44.947619
| 157
| 0.710457
|
b285fef0584ff2a786ed51773835082bd0aa74aa
| 26,713
|
/*
* Copyright 2015 floragunn UG (haftungsbeschränkt)
*
* 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.floragunn.searchguard.ssl;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.crypto.Cipher;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import com.floragunn.searchguard.ssl.util.SSLCertificateHelper;
import com.floragunn.searchguard.ssl.util.SSLConfigConstants;
public class SearchGuardKeyStore {
private static final String DEFAULT_STORE_TYPE = "JKS";
private static final String DEFAULT_STORE_PASSWORD = "changeit"; //#16
private void printJCEWarnings() {
try {
final int aesMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES");
if (aesMaxKeyLength < 256) {
log.info("AES-256 not supported, max key length for AES is " + aesMaxKeyLength+" bit."
+ ". That is not an issue, it just limits possible encryption strength. To enable AES 256 install 'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files'");
}
} catch (final NoSuchAlgorithmException e) {
log.error("AES encryption not supported (SG 1). " + e);
}
}
private final Settings settings;
private final ESLogger log = Loggers.getLogger(this.getClass());
public final SslProvider sslHTTPProvider;
public final SslProvider sslTransportServerProvider;
public final SslProvider sslTransportClientProvider;
private final boolean httpSSLEnabled;
private final boolean transportSSLEnabled;
private X509Certificate[] trustedHTTPCertificates;
private X509Certificate[] trustedTransportCertificates;
private X509Certificate[] httpKeystoreCert;
private PrivateKey httpKeystoreKey;
private X509Certificate[] transportKeystoreCert;
private PrivateKey transportKeystoreKey;
private ClientAuth httpClientAuthMode;
private List<String> enabledHttpCiphersJDKProvider;
private List<String> enabledHttpCiphersOpenSSLProvider;
private List<String> enabledTransportCiphersJDKProvider;
private List<String> enabledTransportCiphersOpenSSLProvider;
private SslContext httpSslContext;
private SslContext transportServerSslContext;
private SslContext transportClientSslContext;
@Inject
public SearchGuardKeyStore(final Settings settings) {
super();
this.settings = settings;
httpSSLEnabled = settings.getAsBoolean(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLED,
SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLED_DEFAULT);
transportSSLEnabled = settings.getAsBoolean(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED,
SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_DEFAULT);
final boolean useOpenSSLForHttpIfAvailable = settings.getAsBoolean(
SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, true);
final boolean useOpenSSLForTransportIfAvailable = settings.getAsBoolean(
SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, true);
if (httpSSLEnabled && useOpenSSLForHttpIfAvailable) {
sslHTTPProvider = SslContext.defaultServerProvider();
logOpenSSLInfos();
} else if (httpSSLEnabled) {
sslHTTPProvider = SslProvider.JDK;
} else {
sslHTTPProvider = null;
}
if (transportSSLEnabled && useOpenSSLForTransportIfAvailable) {
sslTransportClientProvider = SslContext.defaultClientProvider();
sslTransportServerProvider = SslContext.defaultServerProvider();
logOpenSSLInfos();
} else if (transportSSLEnabled) {
sslTransportClientProvider = sslTransportServerProvider = SslProvider.JDK;
} else {
sslTransportClientProvider = sslTransportServerProvider = null;
}
initEnabledSSLCiphers();
initSSLConfig();
printJCEWarnings();
log.info("sslTransportClientProvider:{} with ciphers {}", sslTransportClientProvider,
getEnabledSSLCiphers(sslTransportClientProvider, false));
log.info("sslTransportServerProvider:{} with ciphers {}", sslTransportServerProvider,
getEnabledSSLCiphers(sslTransportServerProvider, false));
log.info("sslHTTPProvider:{} with ciphers {}", sslHTTPProvider, getEnabledSSLCiphers(sslHTTPProvider, true));
log.info("sslTransport protocols {}", Arrays.asList(SSLConfigConstants.getSecureSSLProtocols(settings, false)));
log.info("sslHTTP protocols {}", Arrays.asList(SSLConfigConstants.getSecureSSLProtocols(settings, true)));
if(transportSSLEnabled && (getEnabledSSLCiphers(sslTransportClientProvider, false).isEmpty()
|| getEnabledSSLCiphers(sslTransportServerProvider, false).isEmpty())) {
throw new ElasticsearchSecurityException("no valid cipher suites for transport protocol");
}
if(httpSSLEnabled && getEnabledSSLCiphers(sslHTTPProvider, true).isEmpty()) {
throw new ElasticsearchSecurityException("no valid cipher suites for http");
}
if(transportSSLEnabled && SSLConfigConstants.getSecureSSLProtocols(settings, false).length == 0) {
throw new ElasticsearchSecurityException("no ssl protocols for transport protocol");
}
if(httpSSLEnabled && SSLConfigConstants.getSecureSSLProtocols(settings, true).length == 0) {
throw new ElasticsearchSecurityException("no ssl protocols for http");
}
}
private void initSSLConfig() {
final Environment env = new Environment(settings);
log.info("Config directory is {}/, from there the key- and truststore files are resolved relatively", env.configFile().toAbsolutePath());
if (transportSSLEnabled) {
final String keystoreFilePath = env.configFile()
.resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, "")).toAbsolutePath().toString();
final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE, DEFAULT_STORE_TYPE);
final String keystorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, null);
final String truststoreFilePath = env.configFile()
.resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, "")).toAbsolutePath()
.toString();
if(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, null) == null) {
throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH
+ " must be set if transport ssl is reqested.");
}
checkStorePath(keystoreFilePath);
if(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, null) == null) {
throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH
+ " must be set if transport ssl is reqested.");
}
checkStorePath(truststoreFilePath);
final String truststoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE);
final String truststorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
final String truststoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, null);
try {
final KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(new FileInputStream(new File(keystoreFilePath)), (keystorePassword == null || keystorePassword.length() == 0) ? null:keystorePassword.toCharArray());
transportKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias);
transportKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias, (keystorePassword==null || keystorePassword.length() == 0) ? null:keystorePassword.toCharArray());
if(transportKeystoreKey == null) {
throw new ElasticsearchException("No key found in "+keystoreFilePath+" with alias "+keystoreAlias);
}
if(transportKeystoreCert != null && transportKeystoreCert.length > 0) {
//TODO create sensitive log property
/*for (int i = 0; i < transportKeystoreCert.length; i++) {
X509Certificate x509Certificate = transportKeystoreCert[i];
if(x509Certificate != null) {
log.info("Transport keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
}
}*/
} else {
throw new ElasticsearchException("No certificates found in "+keystoreFilePath+" with alias "+keystoreAlias);
}
final KeyStore ts = KeyStore.getInstance(truststoreType);
ts.load(new FileInputStream(new File(truststoreFilePath)), (truststorePassword==null || truststorePassword.length() == 0) ? null:truststorePassword.toCharArray());
trustedTransportCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias);
if (trustedTransportCertificates == null) {
throw new ElasticsearchException("No truststore configured for server");
}
final SslContextBuilder sslServerContextBuilder = SslContextBuilder.forServer(transportKeystoreKey, transportKeystoreCert)
.ciphers(getEnabledSSLCiphers(this.sslTransportServerProvider, false))
.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED).clientAuth(ClientAuth.REQUIRE)
// https://github.com/netty/netty/issues/4722
.sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslTransportServerProvider)
.trustManager(trustedTransportCertificates);
transportServerSslContext = buildSSLContext(sslServerContextBuilder);
if (trustedTransportCertificates == null) {
throw new ElasticsearchException("No truststore configured for client");
}
final SslContextBuilder sslClientContextBuilder = SslContextBuilder.forClient().ciphers(getEnabledSSLCiphers(sslTransportClientProvider, false))
.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED).sessionCacheSize(0).sessionTimeout(0)
.sslProvider(sslTransportClientProvider).trustManager(trustedTransportCertificates)
.keyManager(transportKeystoreKey, transportKeystoreCert);
transportClientSslContext = buildSSLContext(sslClientContextBuilder);
} catch (final Exception e) {
throw new ElasticsearchSecurityException("Error while initializing transport SSL layer: "+e.toString(), e);
}
}
final boolean client = !"node".equals(this.settings.get(SearchGuardSSLPlugin.CLIENT_TYPE));
if (!client && httpSSLEnabled) {
final String keystoreFilePath = env.configFile()
.resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, "")).toAbsolutePath().toString();
final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_TYPE, DEFAULT_STORE_TYPE);
final String keystorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS, null);
httpClientAuthMode = ClientAuth.valueOf(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE, ClientAuth.OPTIONAL.toString()));
//TODO remove with next version
String _enforceHTTPClientAuth = settings.get("searchguard.ssl.http.enforce_clientauth");
if(_enforceHTTPClientAuth != null) {
log.error("{} is deprecated and replaced by {}", "searchguard.ssl.http.enforce_clientauth", SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE);
throw new RuntimeException("searchguard.ssl.http.enforce_clientauth is deprecated");
}
log.info("HTTPS client auth mode {}", httpClientAuthMode);
final String truststoreFilePath = env.configFile()
.resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, "")).toAbsolutePath().toString();
if(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, null) == null) {
throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH
+ " must be set if https is reqested.");
}
checkStorePath(keystoreFilePath);
if (httpClientAuthMode == ClientAuth.REQUIRE) {
if(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) == null) {
throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH
+ " must be set if http ssl and client auth is reqested.");
}
}
try {
final KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(new FileInputStream(new File(keystoreFilePath)), (keystorePassword == null || keystorePassword.length() == 0) ? null:keystorePassword.toCharArray());
httpKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias);
httpKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias, (keystorePassword==null || keystorePassword.length() == 0) ? null:keystorePassword.toCharArray());
if(httpKeystoreKey == null) {
throw new ElasticsearchException("No key found in "+keystoreFilePath+" with alias "+keystoreAlias);
}
if(httpKeystoreCert != null && httpKeystoreCert.length > 0) {
//TODO create sensitive log property
/*for (int i = 0; i < httpKeystoreCert.length; i++) {
X509Certificate x509Certificate = httpKeystoreCert[i];
if(x509Certificate != null) {
log.info("HTTP keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
}
}*/
} else {
throw new ElasticsearchException("No certificates found in "+keystoreFilePath+" with alias "+keystoreAlias);
}
if(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) != null) {
checkStorePath(truststoreFilePath);
final String truststoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE);
final String truststorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
final String truststoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_ALIAS, null);
final KeyStore ts = KeyStore.getInstance(truststoreType);
ts.load(new FileInputStream(new File(truststoreFilePath)), (truststorePassword == null || truststorePassword.length() == 0) ?null:truststorePassword.toCharArray());
trustedHTTPCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias);
}
final SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(httpKeystoreKey, httpKeystoreCert)
.ciphers(getEnabledSSLCiphers(this.sslHTTPProvider, true)).applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
.clientAuth(Objects.requireNonNull(httpClientAuthMode)) // https://github.com/netty/netty/issues/4722
.sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslHTTPProvider);
if (trustedHTTPCertificates != null && trustedHTTPCertificates.length > 0) {
sslContextBuilder.trustManager(trustedHTTPCertificates);
}
httpSslContext = buildSSLContext(sslContextBuilder);
} catch (final Exception e) {
throw new ElasticsearchSecurityException("Error while initializing HTTP SSL layer: "+e.toString(), e);
}
}
}
public SSLEngine createHTTPSSLEngine() throws SSLException {
final SSLEngine engine = httpSslContext.newEngine(PooledByteBufAllocator.DEFAULT);
engine.setEnabledProtocols(SSLConfigConstants.getSecureSSLProtocols(settings, true));
// engine.setNeedClientAuth(enforceHTTPClientAuth);
return engine;
}
public SSLEngine createServerTransportSSLEngine() throws SSLException {
final SSLEngine engine = transportServerSslContext.newEngine(PooledByteBufAllocator.DEFAULT);
engine.setEnabledProtocols(SSLConfigConstants.getSecureSSLProtocols(settings, false));
// engine.setNeedClientAuth(true);
return engine;
}
public SSLEngine createClientTransportSSLEngine(final String peerHost, final int peerPort) throws SSLException {
if (peerHost != null) {
final SSLEngine engine = transportClientSslContext.newEngine(PooledByteBufAllocator.DEFAULT, peerHost, peerPort);
final SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
engine.setSSLParameters(sslParams);
engine.setEnabledProtocols(SSLConfigConstants.getSecureSSLProtocols(settings, false));
return engine;
} else {
final SSLEngine engine = transportClientSslContext.newEngine(PooledByteBufAllocator.DEFAULT);
engine.setEnabledProtocols(SSLConfigConstants.getSecureSSLProtocols(settings, false));
return engine;
}
}
private void logOpenSSLInfos() {
if (OpenSsl.isAvailable()) {
log.info("Open SSL " + OpenSsl.versionString() + " available");
log.debug("Open SSL available ciphers " + OpenSsl.availableCipherSuites());
} else {
log.info("Open SSL not available (this is not an error, we simply fallback to built-in JDK SSL) because of " + OpenSsl.unavailabilityCause());
}
}
private List<String> getEnabledSSLCiphers(final SslProvider provider, boolean http) {
if (provider == null) {
return Collections.emptyList();
}
if(http) {
return provider == SslProvider.JDK ? enabledHttpCiphersJDKProvider : enabledHttpCiphersOpenSSLProvider;
} else {
return provider == SslProvider.JDK ? enabledTransportCiphersJDKProvider : enabledTransportCiphersOpenSSLProvider;
}
}
private void initEnabledSSLCiphers() {
List<String> secureSSLCiphers = SSLConfigConstants.getSecureSSLCiphers(settings, true);
if (OpenSsl.isAvailable()) {
final Set<String> openSSLSecureCiphers = new HashSet<>();
for (final String secure : secureSSLCiphers) {
if (OpenSsl.isCipherSuiteAvailable(secure)) {
openSSLSecureCiphers.add(secure);
}
}
enabledHttpCiphersOpenSSLProvider = Collections.unmodifiableList(new ArrayList<String>(openSSLSecureCiphers));
} else {
enabledHttpCiphersOpenSSLProvider = Collections.emptyList();
}
SSLEngine engine = null;
try {
final SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(null, null, null);
engine = serverContext.createSSLEngine();
final List<String> jdkSupportedCiphers = new ArrayList<>(Arrays.asList(engine.getSupportedCipherSuites()));
jdkSupportedCiphers.retainAll(secureSSLCiphers);
engine.setEnabledCipherSuites(jdkSupportedCiphers.toArray(new String[0]));
enabledHttpCiphersJDKProvider = Collections.unmodifiableList(Arrays.asList(engine.getEnabledCipherSuites()));
} catch (final Exception e) {
enabledHttpCiphersJDKProvider = Collections.emptyList();
} finally {
if(engine != null) {
try {
engine.closeInbound();
} catch (SSLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
engine.closeOutbound();
}
}
secureSSLCiphers = SSLConfigConstants.getSecureSSLCiphers(settings, false);
if (OpenSsl.isAvailable()) {
final Set<String> openSSLSecureCiphers = new HashSet<>();
for (final String secure : secureSSLCiphers) {
if (OpenSsl.isCipherSuiteAvailable(secure)) {
openSSLSecureCiphers.add(secure);
}
}
enabledTransportCiphersOpenSSLProvider = Collections.unmodifiableList(new ArrayList<String>(openSSLSecureCiphers));
} else {
enabledTransportCiphersOpenSSLProvider = Collections.emptyList();
}
try {
final SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(null, null, null);
engine = serverContext.createSSLEngine();
final List<String> jdkSupportedCiphers = new ArrayList<>(Arrays.asList(engine.getSupportedCipherSuites()));
jdkSupportedCiphers.retainAll(secureSSLCiphers);
engine.setEnabledCipherSuites(jdkSupportedCiphers.toArray(new String[0]));
enabledTransportCiphersJDKProvider = Collections.unmodifiableList(Arrays.asList(engine.getEnabledCipherSuites()));
} catch (final Exception e) {
enabledTransportCiphersJDKProvider = Collections.emptyList();
} finally {
if(engine != null) {
try {
engine.closeInbound();
} catch (SSLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
engine.closeOutbound();
}
}
}
private SslContext buildSSLContext(final SslContextBuilder sslContextBuilder) throws SSLException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
SslContext sslContext = null;
try {
sslContext = AccessController.doPrivileged(new PrivilegedExceptionAction<SslContext>() {
@Override
public SslContext run() throws Exception {
return sslContextBuilder.build();
}
});
} catch (final PrivilegedActionException e) {
throw (SSLException) e.getCause();
}
return sslContext;
}
private static void checkStorePath(String keystoreFilePath) {
if (Files.isDirectory(Paths.get(keystoreFilePath), LinkOption.NOFOLLOW_LINKS)) {
throw new ElasticsearchException("Is a directory: " + keystoreFilePath+" Expected file!");
}
if(!Files.isReadable(Paths.get(keystoreFilePath))) {
throw new ElasticsearchException("Unable to read " + keystoreFilePath + " ("+Paths.get(keystoreFilePath)+") Please make sure this files exists and is readable regarding to permissions");
}
}
}
| 49.744879
| 205
| 0.666342
|
83e4f96622ad43949f2b06397f604baa67ddcaac
| 340
|
package source.structural.defaultMethods;
public interface I5 {
@MyAnnotation
default void o2(boolean b, CC1 cc1, II1 ii1) {
System.out.println("o2-s");
}
@MyAnnotation
default void o2(boolean b, CC2 cc2, II1 ii1) {
System.out.println("o2-i");
}
@MyAnnotation
default void o3(boolean b) {
System.out.println("o3");
}
}
| 16.190476
| 47
| 0.685294
|
5a3c787bbcb271824243b151b4fa9c2ad7b9bba7
| 401
|
package com.cgy.weixin.model.exception;
import com.cgy.weixin.R;
import com.cgy.weixin.utils.UIUtils;
/**
* Created by cgy
* 2018/5/28 18:24
* 服务器异常
*/
public class ServerException extends Exception{
public ServerException(int errorCode) {
this(UIUtils.getString(R.string.error_code) + errorCode);
}
public ServerException(String message) {
super(message);
}
}
| 20.05
| 65
| 0.690773
|
63abbcd895873b75514112ed88b3c0d42e77378a
| 425
|
// Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package de.bytefish.sqlmapper.handlers;
import java.lang.reflect.Type;
import java.sql.ResultSet;
public interface IValueHandler<TTargetType> extends ValueHandler {
TTargetType handle(String columnName, final ResultSet resultSet);
Type getTargetType();
}
| 26.5625
| 101
| 0.783529
|
d3cfabb799a4b3b5845bc875f5454db1d6181e5b
| 2,261
|
/*
* RadioManager
* RadioManager
*
* OpenAPI spec version: 2.0
* Contact: support@pluxbox.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.pluxbox.radiomanager.api.models;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* BroadcastRelationsItemsParams
*/
public class BroadcastRelationsItemsParams {
@SerializedName("broadcast_id")
private Integer broadcastId = null;
public BroadcastRelationsItemsParams broadcastId(Integer broadcastId) {
this.broadcastId = broadcastId;
return this;
}
/**
* Get broadcastId
* @return broadcastId
**/
@ApiModelProperty(example = "1", value = "")
public Integer getBroadcastId() {
return broadcastId;
}
public void setBroadcastId(Integer broadcastId) {
this.broadcastId = broadcastId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BroadcastRelationsItemsParams broadcastRelationsItemsParams = (BroadcastRelationsItemsParams) o;
return Objects.equals(this.broadcastId, broadcastRelationsItemsParams.broadcastId);
}
@Override
public int hashCode() {
return Objects.hash(broadcastId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BroadcastRelationsItemsParams {\n");
sb.append(" broadcastId: ").append(toIndentedString(broadcastId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 24.053191
| 100
| 0.702344
|
82b16d129eb3f95584043e79dbd48827214718c0
| 3,364
|
package WayofTime.bloodmagic.alchemyArray;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.SPacketUpdateHealth;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import WayofTime.bloodmagic.core.RegistrarBloodMagicBlocks;
import WayofTime.bloodmagic.iface.IAlchemyArray;
public class AlchemyArrayEffectTeleport extends AlchemyArrayEffect {
public static final int MAX_SEARCH = 20;
public static final int TELEPORT_DELAY = 40;
public AlchemyArrayEffectTeleport(String key) {
super(key);
}
@Override
public boolean update(TileEntity tile, int ticksActive) {
return false;
}
@Override
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) {
EnumFacing direction = array.getRotation();
teleportEntityInDirection(world, pos, entity, direction);
}
public void teleportEntityInDirection(World world, BlockPos currentPos, Entity entity, EnumFacing direction) {
if (entity != null && entity.timeUntilPortal <= 0) {
for (int i = 1; i <= MAX_SEARCH; i++) {
BlockPos offsetPos = currentPos.offset(direction, i);
Block testBlock = world.getBlockState(offsetPos).getBlock();
if (testBlock == RegistrarBloodMagicBlocks.ALCHEMY_ARRAY) {
int x = offsetPos.getX();
int y = offsetPos.getY();
int z = offsetPos.getZ();
entity.getEntityWorld().playSound(x, y, z, SoundEvents.ENTITY_ENDERMEN_TELEPORT, SoundCategory.AMBIENT, 1.0F, 1.0F, false);
entity.timeUntilPortal = TELEPORT_DELAY;
if (!world.isRemote) {
if (entity instanceof EntityPlayer) {
EntityPlayerMP player = (EntityPlayerMP) entity;
player.setPositionAndUpdate(x + 0.5, y + 0.5, z + 0.5);
player.getEntityWorld().updateEntityWithOptionalForce(player, false);
player.connection.sendPacket(new SPacketUpdateHealth(player.getHealth(), player.getFoodStats().getFoodLevel(), player.getFoodStats().getSaturationLevel()));
} else {
WorldServer worldServer = (WorldServer) entity.getEntityWorld();
entity.setPosition(x + 0.5, y + 0.5, z + 0.5);
worldServer.resetUpdateEntityTick();
}
}
return;
}
}
}
}
@Override
public void writeToNBT(NBTTagCompound tag) {
}
@Override
public void readFromNBT(NBTTagCompound tag) {
}
@Override
public AlchemyArrayEffect getNewCopy() {
return new AlchemyArrayEffectTeleport(key);
}
}
| 38.227273
| 184
| 0.640012
|
06099b1223ca651045cb0d87c3c415c5eb6e3583
| 1,963
|
package org.jxls.templatebasedtests;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.jxls.JxlsTester;
import org.jxls.common.Context;
/**
* Testcase for issues 159 (insert image) and 178 (text underline issues)
* A modification of the original example by ZhengJin Fang
*/
public class IssueB159Test {
@Test
public void test() throws IOException {
// Prepare
Context context = new Context();
Map<String, Object> model = getModel();
for (String key : model.keySet()) {
context.putVar(key, model.get(key));
}
// Test
JxlsTester tester = JxlsTester.xlsx(getClass());
tester.processTemplate(context);
// Verify
// TODO I guess in the template file the image command in cell I9 must be extended with: lockRange=false
// TODO assertions: What have to be verified?
}
private Map<String, Object> getModel() throws IOException {
// issue 178 >>
Map<String, Object> model = new HashMap<>();
model.put("name", "name111111111");
model.put("remark", "remark remark remark remark remark remark\n remark remark remark remark remark remark\n remark remark remark remark remark remark remark remark remark remark ");
// <<
List<Integer> details = new ArrayList<>();
for (int i = 0; i < 10; i++) {
details.add(i);
}
model.put("details", details);
// issue 159 numbers 1 and 2 >>
byte[] stampByteArray;
try (InputStream stamp = IssueB159Test.class.getResourceAsStream("stamp.png")) {
stampByteArray = IOUtils.toByteArray(stamp);
}
model.put("stampImage", stampByteArray);
// <<
return model;
}
}
| 31.66129
| 190
| 0.62812
|
021c2d4322087a38cb0f4d04557c596ad0bd0cf0
| 738
|
package org.onetwo.common.exception;
public class SessionTimeoutException extends NotLoginException {
public static final String DEFAULT_MESSAGE = "[登录超时]";
/**
*
*/
private static final long serialVersionUID = 7280411050853219784L;
public SessionTimeoutException() {
super(DEFAULT_MESSAGE);
}
public SessionTimeoutException(String message, String code) {
super(DEFAULT_MESSAGE+message, code);
}
public SessionTimeoutException(String message) {
super(DEFAULT_MESSAGE+message);
}
public SessionTimeoutException(Throwable cause) {
super(DEFAULT_MESSAGE, cause);
}
public SessionTimeoutException(String message, Throwable cause) {
super(DEFAULT_MESSAGE+message, cause);
}
}
| 23.0625
| 68
| 0.739837
|
e02552fe3fff3afe2cdbb45f5c76698ab5c957b0
| 1,980
|
/*
* Copyright (C) 2015 Samsung System LSI
* 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.bluetooth.map;
import com.android.bluetooth.R;
import com.android.bluetooth.map.BluetoothMapAccountItem;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ExpandableListView;
public class BluetoothMapSettings extends Activity {
private static final String TAG = "BluetoothMapSettings";
private static final boolean D = BluetoothMapService.DEBUG;
private static final boolean V = BluetoothMapService.VERBOSE;
BluetoothMapAccountLoader mLoader = new BluetoothMapAccountLoader(this);
LinkedHashMap<BluetoothMapAccountItem,ArrayList<BluetoothMapAccountItem>> mGroups;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* set UI */
setContentView(R.layout.bluetooth_map_settings);
/* create structure for list of groups + items*/
mGroups = mLoader.parsePackages(true);
/* update expandable listview with correct items */
ExpandableListView listView =
(ExpandableListView) findViewById(R.id.bluetooth_map_settings_list_view);
BluetoothMapSettingsAdapter adapter = new BluetoothMapSettingsAdapter(this,
listView, mGroups, mLoader.getAccountsEnabledCount());
listView.setAdapter(adapter);
}
}
| 33.559322
| 86
| 0.75
|
0057a7ffa995bad5bdee152b4d3777ccc7b6b162
| 2,763
|
/*
* 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.kylin.cube.model.validation.rule;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.apache.kylin.cube.model.CubeDesc;
import org.apache.kylin.cube.model.RowKeyColDesc;
import org.apache.kylin.cube.model.validation.IValidatorRule;
import org.apache.kylin.cube.model.validation.ResultLevel;
import org.apache.kylin.cube.model.validation.ValidateContext;
/**
* Validate that mandatory column must NOT appear in aggregation group.
*
* @author jianliu
*
*/
public class MandatoryColumnRule implements IValidatorRule<CubeDesc> {
/*
* (non-Javadoc)
*
* @see
* org.apache.kylin.metadata.validation.IValidatorRule#validate(java.lang.Object
* , org.apache.kylin.metadata.validation.ValidateContext)
*/
@Override
public void validate(CubeDesc cube, ValidateContext context) {
Set<String> mands = new HashSet<String>();
RowKeyColDesc[] cols = cube.getRowkey().getRowKeyColumns();
if (cols == null || cols.length == 0) {
return;
}
for (int i = 0; i < cols.length; i++) {
RowKeyColDesc rowKeyColDesc = cols[i];
if (rowKeyColDesc.isMandatory()) {
mands.add(rowKeyColDesc.getColumn());
}
}
if (mands.isEmpty()) {
return;
}
String[][] groups = cube.getRowkey().getAggregationGroups();
for (int i = 0; i < groups.length; i++) {
String[] group = groups[i];
for (int j = 0; j < group.length; j++) {
String col = group[j];
if (mands.contains(col)) {
context.addResult(ResultLevel.ERROR, "mandatory column " + col + " must not be in aggregation group [" + ArrayUtils.toString(group) + "]");
}
}
}
}
}
| 35.883117
| 160
| 0.633731
|
f1272abce10b74dd5332704c4a70dc72ec0f9560
| 286
|
package com.runwise.commomlibrary.swipetoloadlayout;
/**
* Created by Aspsine on 2015/8/17.
*/
public interface SwipeTrigger {
void onPrepare();
void onMove(int y, boolean isComplete, boolean automatic);
void onRelease();
void onComplete();
void onReset();
}
| 16.823529
| 62
| 0.688811
|
4cc58243db27ab3776084dc65a2951c95db422b3
| 594
|
/**
* Copyright (C), 2015-2020, XXX有限公司
* FileName: ServiceHiHystrix
* Author: 27046
* Date: 2020/2/28 0:23
* Description: hi服务的熔断
* History:
* <p>
* 作者姓名 修改时间 版本号 描述
*/
package com.pricemonitor.servicefeign;
import org.springframework.stereotype.Component;
/**
* 〈一句话功能简述〉
* 〈hi服务的熔断〉
*
*@author 27046
*@create 2020/2/28
*@since 1.0.0
*/
@Component
public class ServiceHiHystrix implements ServiceHi{
@Override
public String sayHiFromServiceHi(String name) {
return "hello" + name +", this message send failed";
}
}
| 19.8
| 60
| 0.631313
|
552d4cd3323d5ddef261b2525d014375662597f6
| 1,936
|
/**
* Copyright 2005-2019 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.core.framework.persistence.ojb.conversion;
import org.apache.ojb.broker.accesslayer.conversions.FieldConversion;
import org.kuali.rice.core.api.util.type.KualiPercent;
import java.math.BigDecimal;
/**
* Creates a KualiPercent object from the data field. Field is stored as a percentage.
*
*
*/
public class OjbKualiPercentFieldConversion implements FieldConversion {
/**
* @see FieldConversion#javaToSql(Object)
*/
public Object javaToSql(Object source) {
Object converted = source;
if (source instanceof KualiPercent) {
converted = ((KualiPercent) source).bigDecimalValue();
}
return converted;
}
/**
* @see FieldConversion#sqlToJava(Object)
*/
public Object sqlToJava(Object source) {
// Check for null, and verify object type.
// Do conversion if our type is correct (BigDecimal).
if (source != null && source instanceof BigDecimal) {
BigDecimal converted = (BigDecimal) source;
// Once we have converted, we need to convert again to KualiPercent.
KualiPercent percentConverted = new KualiPercent((BigDecimal) converted);
return percentConverted;
}
else {
return null;
}
}
}
| 30.25
| 86
| 0.682851
|
5e453480f9edb51fc83ff04043ae0ef8bb1ca5b5
| 7,168
|
package org.apache.jsp.user;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import Kontroller.KiralaList;
import Kontroller.Kirala;
import java.util.List;
public final class newjsp_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
List<Kirala> kiraliste = new KiralaList().getirTumKiralaListe();
request.setAttribute("kiraliste", kiraliste);
out.write('\r');
out.write('\n');
int toplamkira = new KiralaList().getirTumKira();
request.setAttribute("toplamkira",toplamkira);
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\r\n");
out.write("\r\n");
out.write(" <!-- Bootstrap CSS -->\r\n");
out.write(" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\">\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" <style>\r\n");
out.write(" .inner{\r\n");
out.write(" margin: 15px 0;\r\n");
out.write(" }\r\n");
out.write(" </style>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" <title>JSP Page</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write(" \r\n");
out.write(" <div class=\"container-fluid\">\r\n");
out.write(" <nav class=\"navbar navbar-light\">\r\n");
out.write(" <a class=\"navbar-brand\">Arac Ekle</a>\r\n");
out.write(" <form class=\"form-inline\">\r\n");
out.write(" <li><a class=\"nav-link text-dark \" href=\"../AdminLogoutServlet\">ÇIKIŞ</a></li>\r\n");
out.write(" </form>\r\n");
out.write("</nav>\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"container-fluid\">\r\n");
out.write(" <nav class=\"navbar navbar-light\">\r\n");
out.write(" <a class=\"navbar-brand\">Kayıtlı Araç Listesi</a> \r\n");
out.write("</nav>\r\n");
out.write(" </div>\r\n");
out.write(" <table class=\"table table-sm table-hover table-bordered table-striped\" style=\"text-align:center\">\r\n");
out.write(" <thead class=\"thead-light\">\r\n");
out.write(" <tr>\r\n");
out.write(" \r\n");
out.write(" <th>Alış Tarihi</th>\r\n");
out.write(" <th>Veriş Tarihi</th>\r\n");
out.write(" <th>Ödeme</th>\r\n");
out.write(" <th></th>\r\n");
out.write(" <th></th>\r\n");
out.write(" <th></th>\r\n");
out.write(" </tr>\r\n");
out.write(" </thead>\r\n");
out.write(" <tbody>\r\n");
out.write(" <c:forEach items=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${kiraliste}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" var=\"kiraliste\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td class=\"align-middle\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${kiraliste.alis_tarihi}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</td>\r\n");
out.write(" <td class=\"align-middle\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${kiraliste.veris_tarihi}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</td>\r\n");
out.write(" <td class=\"align-middle\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${kiraliste.odeme}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</td>\r\n");
out.write(" \r\n");
out.write(" <td><a href=\"../KiralaDeleteServlet?id=<c:out value='");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${kiraliste.id}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("'/>\">Sil</a></td>\r\n");
out.write(" \r\n");
out.write(" </tr>\r\n");
out.write(" \r\n");
out.write(" </c:forEach>\r\n");
out.write(" </tbody>\r\n");
out.write(" </table>\r\n");
out.write("</div>\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 48.761905
| 189
| 0.542132
|
722b56763ec4ab7051faec66ef8403c5cd4bb386
| 20,554
|
/*
* WSearchEditorMigrationRow.java
* Created on 2013/06/28
*
* Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tubame.wsearch.models;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import tubame.common.util.CmnStringUtil;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.WorkbenchException;
import tubame.wsearch.Activator;
import tubame.wsearch.biz.comparer.AbstractComparer;
import tubame.wsearch.util.resource.ResourceUtil;
/**
* It is the Row information to be displayed in the search results view.<br/>
*/
public class WSearchEditorMigrationRow implements MigrationEditorRow {
/**
* The type that defines the hierarchy level.<br/>
*/
public enum LEVEL {
FIRST(0), SECOND(1), THIRD(2), FOURTH(3), FIFTH(4), SIXTH(5);
/**
* Constructor.<br/>
* Nothing in particular.<br/>
*
* @param level
* Hierarchical level
*/
LEVEL(int level) {
this.level = level;
}
/**
* Hierarchical level
*/
private int level;
/**
* Get the hierarchy level.<br/>
*
* @return Hierarchical level
*/
public int getLevel() {
return level;
}
}
/**
* The lowest level
*/
public final static LEVEL LOWEST_LEVEL = LEVEL.FIFTH;
/**
* (Represents the hierarchy) level
*/
private int level;
/**
* Result
*/
private String status;
/**
* Category
*/
private String category;
/**
* Package
*/
private String packageName;
/**
* Porting the original library
*/
private String srcLibrary;
/**
* Porting library
*/
private String destLibrary;
/**
* Class
*/
private String clazzName;
/**
* Hits
*/
private String hitNum;
/**
* Line number
*/
private String rowNumber;
/**
* Migrated files
*/
private String files;
/**
* Migrated files
*/
private String targetFullPath;
public String getTargetFullPath() {
return targetFullPath;
}
public void setTargetFullPath(String targetFullPath) {
this.targetFullPath = targetFullPath;
}
/**
* Result detail
*/
private String detail;
/**
* Remarks
*/
private String note;
/**
* Subelement
*/
private List<WSearchEditorMigrationRow> childList = new ArrayList<WSearchEditorMigrationRow>();
/**
* Parent hierarchy
*/
private WSearchEditorMigrationRow parent;
/**
* Error icon
*/
private static Image errorIcon;
/**
* Warning icon
*/
private static Image warnIcon;
static {
try {
URL pluginURL = Activator.getDefault().getBundle()
.getEntry(CmnStringUtil.SLASH);
errorIcon = ImageDescriptor.createFromURL(
new URL(pluginURL, ResourceUtil.ERROR_ICON)).createImage();
warnIcon = ImageDescriptor.createFromURL(
new URL(pluginURL, ResourceUtil.WARN_ICON)).createImage();
} catch (MalformedURLException e) {
Activator.log(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getLevel() {
return level;
}
/**
* Set up a hierarchy level.<br/>
*
* @param level
* Hierarchical level
*/
public void setLevel(int level) {
this.level = level;
}
/**
* Get child hierarchy level.<br/>
*
* @return Child hierarchy level
*/
public List<WSearchEditorMigrationRow> getChildList() {
return childList;
}
/**
* Set the child hierarchy level.<br/>
*
* @param childList
* Child hierarchy level
*/
public void setChildList(List<WSearchEditorMigrationRow> childList) {
this.childList = childList;
}
/**
* Add it to the child hierarchy level.<br/>
*
* @param item
* Additional data
*/
public void addChild(WSearchEditorMigrationRow item) {
childList.add(item);
}
/**
* {@inheritDoc}
*/
@Override
public WSearchEditorMigrationRow getParent() {
return parent;
}
/**
* Set the parent hierarchy.<br/>
*
* @param parent
* Parent hierarchy
*/
public void setParent(WSearchEditorMigrationRow parent) {
this.parent = parent;
}
/**
* Get the status.<br/>
*
* @return Status
*/
public String getStatus() {
return status;
}
/**
* Set the status.<br/>
*
* @param status
* Status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Get the category.<br/>
*
* @return Category
*/
public String getCategory() {
return category;
}
/**
* Get the details.<br/>
*
* @return Detail
*/
public String getDetail() {
return detail;
}
/**
* Set the details.<br/>
*
* @param detail
* Detail
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* Get remarks.<br/>
*
* @return Remarks
*/
public String getNote() {
return note;
}
/**
* Set the remarks.<br/>
*
* @param note
* Remarks
*/
public void setNote(String note) {
this.note = note;
}
/**
* Set the category.<br/>
*
* @param category
* Category
*/
public void setCategory(String category) {
this.category = category;
}
/**
* Get the package.<br/>
*
* @return Package name
*/
public String getPackage() {
return packageName;
}
/**
* Set the package.<br/>
*
* @param packageName
* Package name
*/
public void setPackage(String packageName) {
this.packageName = packageName;
}
/**
* Get the transplant original library.<br/>
*
* @return Porting the original library name
*/
public String getSrcLibrary() {
return srcLibrary;
}
/**
* Set the transplant original library.<br/>
*
* @param library
* Porting the original library name
*/
public void setSrcLibrary(String library) {
this.srcLibrary = library;
}
/**
* Get the porting library.<br/>
*
* @return Porting library name
*/
public String getDestLibrary() {
return destLibrary;
}
/**
* Set the porting library.<br/>
*
* @param library
* Porting library name
*/
public void setDestLibrary(String library) {
this.destLibrary = library;
}
/**
* Get clazzName.<br/>
*
* @return clazzName
*/
public String getClazz() {
return clazzName;
}
/**
* Set the clazzName.<br/>
*
* @param clazzName
* clazzName
*/
public void setClazz(String clazzName) {
this.clazzName = clazzName;
}
/**
* Get hitNum.<br/>
*
* @return hitNum
*/
public String getHitNum() {
return hitNum;
}
/**
* Set the hitNum.<br/>
*
* @param hitNum
* hitNum
*/
public void setHitNum(String hitNum) {
this.hitNum = hitNum;
}
/**
* Get rowNumber.<br/>
*
* @return rowNumber
*/
public String getRowNumber() {
return rowNumber;
}
/**
* Set the rowNumber.<br/>
*
* @param rowNumber
* rowNumber
*/
public void setRowNumber(String rowNumber) {
this.rowNumber = rowNumber;
}
/**
* Get the files.<br/>
*
* @return files
*/
public String getFiles() {
return files;
}
/**
* Set the files.<br/>
*
* @param files
* files
*/
public void setFiles(String files) {
this.files = files;
}
/**
* Get the text to be displayed by specifying the section number of the
* column.<br/>
*
* @param columnIndex
* No. of column
* @return Text to be displayed
*/
public String getColumnText(int columnIndex) {
return getColumnText(columnIndex, true);
}
/**
* Get the text to be displayed by specifying the element level and the
* numbers in column.<br/>
*
* @param columnIndex
* No. of column
* @param affectedByLevel
* Element level
* @return Text to be displayed
*/
public String getColumnText(int columnIndex, boolean affectedByLevel) {
String text = CmnStringUtil.EMPTY;
switch (WSearchEditorEnum.get(columnIndex)) {
case INDEX_STATUS:
if (!affectedByLevel || (LEVEL.FIRST.getLevel() == getLevel())) {
text = getStatus();
}
break;
case INDEX_CATEGORY:
if (!affectedByLevel || (LEVEL.SECOND.getLevel() == getLevel())) {
text = getCategory();
}
break;
case INDEX_PACKAGE:
if (!affectedByLevel || (LEVEL.THIRD.getLevel() == getLevel())) {
text = getPackage();
if (CmnStringUtil.isEmpty(text)) {
text = CmnStringUtil.HYPHEN;
}
}
break;
case INDEX_SRC_LIBRARY:
if (!affectedByLevel || (LEVEL.FOURTH.getLevel() == getLevel())) {
text = getSrcLibrary();
if (text.contains(",")) {
List<String> libraries = Arrays.asList(text.split(","));
Collections.sort(libraries, new LibraryComparetor());
StringBuilder string = new StringBuilder();
for (String value : libraries) {
string.append(value + ",");
}
text = string.toString();
text = text.substring(0, (text.length() - 1));
}
}
break;
case INDEX_DEST_LIBRARY:
if (!affectedByLevel || (LEVEL.FOURTH.getLevel() == getLevel())) {
text = getDestLibrary();
if (text.contains(",")) {
List<String> libraries = Arrays.asList(text.split(","));
Collections.sort(libraries, new LibraryComparetor());
StringBuilder string = new StringBuilder();
for (String value : libraries) {
string.append(value + ",");
}
text = string.toString();
text = text.substring(0, (text.length() - 1));
}
}
break;
case INDEX_CLAZZ:
if (!affectedByLevel || (LEVEL.FOURTH.getLevel() == getLevel())) {
text = getClazz();
}
break;
case INDEX_HIT_NUM:
if (LEVEL.FIRST.getLevel() == getLevel()) {
int count = 0;
for (WSearchEditorMigrationRow row : getChildList()) {
count += Integer.valueOf(row
.getColumnText(WSearchEditorEnum.INDEX_HIT_NUM
.getIndex()));
}
text = String.valueOf(count);
}
if (LEVEL.SECOND.getLevel() == getLevel()) {
int count = 0;
for (WSearchEditorMigrationRow row : getChildList()) {
String temp = row
.getColumnText(WSearchEditorEnum.INDEX_HIT_NUM
.getIndex());
if (!CmnStringUtil.isEmpty(temp)) {
count += Integer.valueOf(temp);
}
}
text = String.valueOf(count);
}
if (LEVEL.THIRD.getLevel() == getLevel()) {
int count = 0;
for (WSearchEditorMigrationRow row : getChildList()) {
String temp = row
.getColumnText(WSearchEditorEnum.INDEX_HIT_NUM
.getIndex());
if (!CmnStringUtil.isEmpty(temp)) {
count += Integer.valueOf(temp);
}
}
text = String.valueOf(count);
}
if (LEVEL.FOURTH.getLevel() == getLevel()) {
int count = getChildList().size();
text = String.valueOf(count);
}
break;
case INDEX_FILES:
if (!affectedByLevel || (LEVEL.FIFTH.getLevel() == getLevel())) {
text = getFiles();
}
break;
case INDEX_LINE:
if (!affectedByLevel || (LEVEL.FIFTH.getLevel() == getLevel())) {
text = getRowNumber();
if (CmnStringUtil.isEmpty(text)) {
text = CmnStringUtil.HYPHEN;
}
}
break;
case INDEX_DETAIL:
if (!affectedByLevel || (LEVEL.FIFTH.getLevel() == getLevel())) {
text = getDetail();
}
break;
case INDEX_NOTE:
if (!affectedByLevel || (LEVEL.FIFTH.getLevel() == getLevel())) {
text = getNote();
if (text.contains(",")) {
List<String> libraries = Arrays.asList(text.split(","));
Collections.sort(libraries, new LibraryComparetor());
StringBuilder string = new StringBuilder();
for (String value : libraries) {
string.append(value + ",");
}
text = string.toString();
text = text.substring(0, (text.length() - 1));
}
}
break;
}
return text;
}
/**
* {@inheritDoc}
*/
@Override
public Image getColumnImage(int columnIndex) {
switch (WSearchEditorEnum.get(columnIndex)) {
case INDEX_STATUS:
if (LEVEL.FIRST.getLevel() == getLevel()) {
if (AbstractComparer.STATUS.ERROR.getValue()
.equals(getStatus())) {
return errorIcon;
} else if (AbstractComparer.STATUS.WARN.getValue().equals(
getStatus())) {
return warnIcon;
}
}
break;
case INDEX_DETAIL:
if (LEVEL.FIFTH.getLevel() == getLevel()) {
if (AbstractComparer.STATUS.ERROR.getValue()
.equals(getStatus())) {
return errorIcon;
} else if (AbstractComparer.STATUS.WARN.getValue().equals(
getStatus())) {
return warnIcon;
}
}
break;
default:
break;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Font getFont() {
// no operation
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Color getBackground(int columnIndex) {
// no operation
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasChildren() {
if (getChildList() != null && getChildList().size() > 0) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public List<WSearchEditorMigrationRow> getChildren() {
return getChildList();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\"");
sb.append(getStatus());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getCategory());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getPackage());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getSrcLibrary());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getDestLibrary());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getClazz());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
// sb.append("\"");
// sb.append(getHitNum());
// sb.append("\"");
// sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getFiles());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getRowNumber());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getDetail());
sb.append("\"");
sb.append(CmnStringUtil.CSV_DELIMITER);
sb.append("\"");
sb.append(getNote());
sb.append("\"");
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public WSearchEditorMigrationRow getMoreParent() {
if (getLevel() == LEVEL.FIRST.getLevel()) {
return this;
}
if (getLevel() == LEVEL.SECOND.getLevel()) {
return getParent();
}
if (getLevel() == LEVEL.THIRD.getLevel()) {
return getParent().getParent();
}
if (getLevel() == LEVEL.FOURTH.getLevel()) {
return getParent().getParent().getParent();
}
return getParent().getParent().getParent().getParent();
}
/**
* {@inheritDoc}
*/
@Override
public void updateWriteData() {
// no operation
}
/**
* {@inheritDoc}
*/
@Override
public Color getForeground(int columnIndex) {
// no operation
return null;
}
/**
* Library comparison class.<br/>
* Class to be compared to be the order of in the library configuration<br/>
*/
private static class LibraryComparetor implements Comparator<String>,
Serializable {
/**
* Serialization key
*/
private static final long serialVersionUID = -7251919997296472324L;
/**
* {@inheritDoc}
*/
@Override
public int compare(String o1, String o2) {
int order1 = Integer.MAX_VALUE;
int order2 = Integer.MAX_VALUE;
try {
Map<String, LibraryRepository> map = Activator
.getLibraryRepositories();
if (map.containsKey(o1)) {
order1 = map.get(o1).getOrder();
}
if (map.containsKey(o2)) {
order2 = map.get(o2).getOrder();
}
} catch (WorkbenchException e) {
Activator.log(e);
}
return order1 - order2;
}
}
}
| 25.219632
| 99
| 0.502189
|
3cb8fcdd81f6dd48911b7b1fe0cfe1d267d5e085
| 1,070
|
package com.miotech.kun.workflow.operator.spark.models;
import java.util.List;
public class SparkApp {
private int id;
private String state;
private String appId;
private AppInfo appInfo;
private List<String> log;
private String kind;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public AppInfo getAppInfo() {
return appInfo;
}
public void setAppInfo(AppInfo appInfo) {
this.appInfo = appInfo;
}
public List<String> getLog() {
return log;
}
public void setLog(List<String> log) {
this.log = log;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
}
| 15.735294
| 55
| 0.573832
|
92f42116324f02691dc26a56dac4d36234bf7a51
| 951
|
package com.besome.sketch.editor.property;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sketchware.remod.R;
import a.a.a.wB;
public class PropertySubheader extends RelativeLayout {
private ImageView imgAdd;
private TextView tvName;
public PropertySubheader(Context context) {
super(context);
initialize(context);
}
private void initialize(Context context) {
wB.a(context, this, R.layout.property_subheader);
tvName = findViewById(R.id.tv_name);
imgAdd = findViewById(R.id.img_add);
}
public void setHeaderName(String str) {
tvName.setText(str);
}
@Override
public void setOnClickListener(View.OnClickListener onClickListener) {
imgAdd.setVisibility(VISIBLE);
imgAdd.setOnClickListener(onClickListener);
}
}
| 24.384615
| 74
| 0.713985
|
94be3fe7e00385b6e636aaa4be3abc21de7244e5
| 7,430
|
/*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.security.web.lockout;
import com.google.common.collect.Lists;
import org.jbb.lib.commons.vo.Email;
import org.jbb.lib.commons.vo.Username;
import org.jbb.members.api.base.DisplayedName;
import org.jbb.members.api.base.Member;
import org.jbb.members.api.base.MemberService;
import org.jbb.security.api.lockout.MemberLock;
import org.jbb.security.api.lockout.MemberLockoutService;
import org.jbb.security.web.BaseIT;
import org.jbb.security.web.MemberImpl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
public class AcpMemberLocksControllerIT extends BaseIT {
@Autowired
WebApplicationContext wac;
private MockMvc mockMvc;
@Autowired
private MemberLockoutService memberLockoutServiceMock;
@Autowired
private MemberService memberServiceMock;
@Autowired
private UserDetailsService userDetailsServiceMock;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity()).build();
Mockito.reset(memberLockoutServiceMock);
Mockito.reset(memberServiceMock);
UserDetails userDetails = mock(UserDetails.class);
Collection<? extends GrantedAuthority> administrator = Lists.newArrayList(new SimpleGrantedAuthority("ROLE_ADMINISTRATOR"));
Mockito.doReturn(administrator).when(userDetails).getAuthorities();
Mockito.doReturn(userDetails).when(userDetailsServiceMock).loadUserByUsername(any());
}
@Test
@WithMockUser(username = "admin", roles = {"ADMINISTRATOR"})
public void shouldUseMemberLocksView_whenGET() throws Exception {
// when
ResultActions result = mockMvc.perform(get("/acp/members/locks"));
// then
result.andExpect(status().isOk())
.andExpect(view().name("acp/members/locks"));
}
@Test
@WithMockUser(username = "admin", roles = {"ADMINISTRATOR"})
public void shouldSetFlag_whenPOST_ok() throws Exception {
// given
given(memberLockoutServiceMock.getLocksWithCriteria(any())).willReturn(examplePageOfLocks());
given(memberServiceMock.getMemberWithIdChecked(any())).willReturn(exampleMember());
// when
ResultActions result = mockMvc.perform(post("/acp/members/locks")
.with(csrf())
);
// then
result.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/acp/members/locks"))
.andExpect(flash().attributeExists("resultPage"));
verify(memberLockoutServiceMock, times(1)).getLocksWithCriteria(any());
}
@Test
@WithMockUser(username = "admin", roles = {"ADMINISTRATOR"})
public void shouldSetFlag_whenPOST_withExistingDisplayedName() throws Exception {
// given
given(memberLockoutServiceMock.getLocksWithCriteria(any())).willReturn(examplePageOfLocks());
given(memberServiceMock.getMemberWithIdChecked(any())).willReturn(exampleMember());
given(memberServiceMock.getMemberWithDisplayedName(eq(DisplayedName.of("john")))).willReturn(Optional.of(exampleMember()));
// when
ResultActions result = mockMvc.perform(post("/acp/members/locks")
.param("displayedName", "john")
.with(csrf())
);
// then
result.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/acp/members/locks"))
.andExpect(flash().attributeExists("resultPage"));
verify(memberLockoutServiceMock, times(1)).getLocksWithCriteria(any());
}
@Test
@WithMockUser(username = "admin", roles = {"ADMINISTRATOR"})
public void shouldNotSetFlag_whenPOST_withNotExistingDisplayedName() throws Exception {
// given
given(memberLockoutServiceMock.getLocksWithCriteria(any())).willReturn(examplePageOfLocks());
given(memberServiceMock.getMemberWithIdChecked(any())).willReturn(exampleMember());
given(memberServiceMock.getMemberWithDisplayedName(eq(DisplayedName.of("john")))).willReturn(Optional.empty());
// when
ResultActions result = mockMvc.perform(post("/acp/members/locks")
.param("displayedName", "john")
.with(csrf())
);
// then
result.andExpect(status().isOk())
.andExpect(view().name("acp/members/locks"))
.andExpect(model().hasErrors());
verifyNoMoreInteractions(memberLockoutServiceMock);
}
private Page<MemberLock> examplePageOfLocks() {
return new PageImpl<>(Lists.newArrayList(MemberLock.builder()
.memberId(123L)
.active(true)
.createDateTime(LocalDateTime.now())
.expirationDateTime(LocalDateTime.now().plusHours(1L))
.build()), PageRequest.of(0, 1), 1);
}
private Member exampleMember() {
return MemberImpl.builder()
.id(123L)
.username(Username.of("john"))
.displayedName(DisplayedName.of("John"))
.email(Email.of("john@john.com"))
.build();
}
}
| 40.162162
| 132
| 0.716689
|
0189e3f34def4e50c5b2f5eccf518e91762a43c6
| 680
|
package com.sly.demo.thinkinjava.chapter10.parcel5;
import com.sly.demo.thinkinjava.chapter10.parcel4.Destination;
/**
* 一个定义在方法中的类
*
* @author sly
* @time 2019年5月28日
*/
public class Parcel5 {
public Destination destination(String dest) {
class PDestination implements Destination {
private String label;
private PDestination(String dest) {
label = dest;
}
@Override
public String readLabel() {
return label;
}
}
return new PDestination(dest);
}
public static void main(String[] args) {
Parcel5 parcel5 = new Parcel5();
Destination destination = parcel5.destination("土星");
System.out.println(destination.readLabel());
}
}
| 18.888889
| 62
| 0.702941
|
7375b61e509b184c19de69f0bb2f635389ea5c3b
| 2,333
|
/*
* 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.jena.graph.compose;
import java.util.Set ;
import org.apache.jena.graph.Graph ;
import org.apache.jena.graph.Triple ;
import org.apache.jena.util.CollectionFactory ;
import org.apache.jena.util.iterator.ExtendedIterator ;
/**
A class representing the dynamic union of two graphs. Addition only affects the left
operand, deletion affects both.
@see MultiUnion
*/
public class Union extends Dyadic implements Graph
{
public Union( Graph L, Graph R )
{ super( L, R ); }
/**
To add a triple to the union, add it to the left operand; this is asymmetric.
*/
@Override public void performAdd( Triple t )
{ L.add( t ); }
/**
To remove a triple, remove it from <i>both</i> operands.
*/
@Override public void performDelete( Triple t )
{
L.delete( t );
R.delete( t );
}
@Override public boolean graphBaseContains( Triple t )
{ return L.contains( t ) || R.contains( t ); }
/**
To find in the union, find in the components, concatenate the results, and omit
duplicates. That last is a performance penalty, but I see no way to remove it
unless we know the graphs do not overlap.
*/
@Override protected ExtendedIterator<Triple> _graphBaseFind( final Triple t )
{
Set<Triple> seen = CollectionFactory.createHashedSet();
return recording( L.find( t ), seen ).andThen( rejecting( R.find( t ), seen ) );
// return L.find( t ) .andThen( rejecting( R.find( t ), L ) );
}
}
| 33.811594
| 89
| 0.687098
|
2656220af53c0160f9694eaf0338af3a1932e1db
| 19,231
|
package de.kreth.clubhelperbackend.config;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.kreth.dbmanager.ColumnDefinition;
import de.kreth.dbmanager.DataType;
import de.kreth.dbmanager.Database;
import de.kreth.dbmanager.DatabaseType;
import de.kreth.dbmanager.TableDefinition;
import de.kreth.dbmanager.UniqueConstraint;
public class DatabaseConfiguration {
private static final String PERSON_ID_FK_NAME = "person_id";
private static final int LATEST_VERSION = 10;
private final Logger logger;
private final DatabaseType dbType;
private List<TableDefinition> allTables;
private TableDefinition person;
private TableDefinition contact;
private TableDefinition relative;
private TableDefinition adress;
private TableDefinition attendance;
private TableDefinition version;
private TableDefinition deletedEntries;
private TableDefinition group;
private TableDefinition persongroup;
private TableDefinition startpass;
private TableDefinition startrecht;
private final List<MyStatement> statements;
private int fromVersion;
public DatabaseConfiguration(int fromVersion) {
this(fromVersion, DatabaseType.MYSQL);
}
public DatabaseConfiguration(int fromVersion, DatabaseType dbType) {
this.fromVersion = fromVersion;
this.dbType = dbType;
statements = new ArrayList<>();
logger = LoggerFactory.getLogger(getClass());
switch (fromVersion) {
case 0 :
createAll();
createWith(person, contact, relative, adress, attendance,
version, deletedEntries, group, persongroup, startpass,
startrecht);
createAttendenceUniqueConstraint();
createForeignkeysForMainTables();
addForeignKey(startrecht, "startpass_id", startpass, "id");
addForeignKey(startpass, "person_id", person, "id");
break;
case 1 :
createAll();
createWith(deletedEntries, group, persongroup);
addDeletedColumn(person, contact, relative, adress, attendance,
version, startpass);
addAuthColumns(person);
statements.add(new DirectStatement(
"INSERT INTO `groupDef`(`name`,`changed`,`created`)VALUES('ADMIN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)"));
addUniquePersonGroup();
addDeleteColumnStm(person, new ColumnDefinition(DataType.TEXT,
"type", "NOT NULL"));
createAttendenceUniqueConstraint();
break;
case 2 :
createAll();
createWith(startpass);
addDeletedColumn(person, contact, relative, adress, attendance,
version, deletedEntries, group, persongroup);
addAuthColumns(person);
statements.add(new DirectStatement(
"INSERT INTO `groupDef`(`name`,`changed`,`created`)VALUES('ADMIN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)"));
addUniqueGroupName();
addUniquePersonGroup();
addDeleteColumnStm(person, new ColumnDefinition(DataType.TEXT,
"type", "NOT NULL"));
createAttendenceUniqueConstraint();
break;
case 3 :
createAll();
createWith(startpass);
addAuthColumns(person);
statements.add(new DirectStatement(
"INSERT INTO `groupDef`(`name`,`changed`,`created`)VALUES('ADMIN',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)"));
addUniqueGroupName();
addUniquePersonGroup();
addDeleteColumnStm(person, new ColumnDefinition(DataType.TEXT,
"type", "NOT NULL"));
createAttendenceUniqueConstraint();
break;
case 4 :
createWith(startpass);
addUniqueGroupName();
addUniquePersonGroup();
addDeleteColumnStm(person, new ColumnDefinition(DataType.TEXT,
"type", "NOT NULL"));
createAttendenceUniqueConstraint();
break;
case 5 :
createAll();
createWith(startpass);
addDeleteColumnStm(person, new ColumnDefinition(DataType.TEXT,
"type", "NOT NULL"));
createAttendenceUniqueConstraint();
break;
case 6 :
createAll();
createWith(startpass);
createAttendenceUniqueConstraint();
changeIdNamesInAllTables();
break;
case 7 :
createAll();
createWith(startpass);
changeIdNamesInAllTables();
break;
case 8 :
createAll();
createWith(startpass, startrecht);
addForeignKey(startrecht, "startpass_id", startpass, "id");
addForeignKey(startpass, "person_id", person, "id");
createForeignkeysForMainTables();
break;
case 9 :
createAll();
createForeignkeysForMainTables();
break;
}
if (fromVersion != LATEST_VERSION && logger.isInfoEnabled()) {
logger.info("Prepared Datebase update from Version " + fromVersion
+ " to Version " + LATEST_VERSION);
}
}
private void createForeignkeysForMainTables() {
addForeignKey(contact, "person_id", person, "id");
addForeignKey(relative, "person1", person, "id");
addForeignKey(relative, "person2", person, "id");
addForeignKey(persongroup, "person_id", person, "id");
addForeignKey(persongroup, "group_id", group, "id");
addForeignKey(attendance, "person_id", person, "id");
addForeignKey(adress, "person_id", person, "id");
}
private void addForeignKey(TableDefinition foreignTable,
String foreignColumn, TableDefinition targetTable,
String targetColumn) {
throwExecptionIfColumnNotContained(foreignTable, foreignColumn);
throwExecptionIfColumnNotContained(targetTable, targetColumn);
StringBuilder sql = new StringBuilder("ALTER TABLE ")
.append(foreignTable.getTableName())
.append(" ADD FOREIGN KEY (").append(foreignColumn)
.append(") REFERENCES ").append(targetTable.getTableName())
.append("(").append(targetColumn).append(")");
add(sql.toString());
}
private void throwExecptionIfColumnNotContained(
TableDefinition foreignTable, String foreignColumn) {
for (Iterator<ColumnDefinition> iterator = foreignTable.getColumns()
.iterator(); iterator.hasNext();) {
ColumnDefinition def = iterator.next();
if (def.getColumnName().equals(foreignColumn)) {
return;
}
}
throw new IllegalArgumentException(foreignTable
+ " does not contain column with name " + foreignColumn);
}
public List<TableDefinition> getAllTables() {
return Collections.unmodifiableList(allTables);
}
public TableDefinition getPerson() {
return person;
}
public TableDefinition getContact() {
return contact;
}
public TableDefinition getRelative() {
return relative;
}
public TableDefinition getAdress() {
return adress;
}
public TableDefinition getAttendance() {
return attendance;
}
public TableDefinition getVersion() {
return version;
}
public TableDefinition getDeletedEntries() {
return deletedEntries;
}
public TableDefinition getGroup() {
return group;
}
public TableDefinition getPersongroup() {
return persongroup;
}
public TableDefinition getStartpass() {
return startpass;
}
public TableDefinition getStartrecht() {
return startrecht;
}
private void changeIdNamesInAllTables() {
String format = "ALTER TABLE %s CHANGE _id id INTEGER NOT NULL AUTO_INCREMENT";
for (TableDefinition def : allTables) {
String sql = String.format(format, def.getTableName());
statements.add(new DirectStatement(sql));
}
}
private void createAttendenceUniqueConstraint() {
ColumnDefinition[] columns = new ColumnDefinition[2];
attendance.getColumns().forEach(col -> {
if (PERSON_ID_FK_NAME.equals(col.getColumnName())) {
columns[0] = col;
} else if ("on_date".equals(col.getColumnName())) {
columns[1] = col;
}
});
statements.add(
new AddConstraint(attendance, new UniqueConstraint(columns)));
}
private void addDeleteColumnStm(TableDefinition table,
ColumnDefinition columnDefinition) {
statements.add(new DropColumnStatement(table, columnDefinition));
}
private void addDeleteColumn(List<ColumnDefinition> columns) {
columns.add(new ColumnDefinition(DataType.DATETIME, "deleted",
" DEFAULT null"));
}
private void addUniqueGroupName() {
statements.add(new DirectStatement(
"delete n1 from groupDef n1, groupDef n2 WHERE n1._id >n2._id AND n1.name = n2.name"));
statements.add(new DirectStatement("ALTER TABLE `groupDef` \n"
+ "ADD UNIQUE INDEX `groupname_UNIQUE` (`name` ASC);"));
}
private void addUniquePersonGroup() {
statements.add(new DirectStatement(
"delete n1 from persongroup n1, persongroup n2 WHERE n1._id >n2._id AND n1.person_id = n2.person_id AND n1.group_id = n2.group_id;"));
add("ALTER TABLE `persongroup` \n"
+ "ADD UNIQUE INDEX `unique_person_group` (`person_id` ASC, `group_id` ASC);");
}
private void add(String sql) {
statements.add(new DirectStatement(sql));
}
private void addAuthColumns(TableDefinition... defs) {
for (TableDefinition t : defs) {
statements.add(new AddColumnStatement(t, new ColumnDefinition(
DataType.TEXT, "username", "DEFAULT NULL")));
statements.add(new AddColumnStatement(t, new ColumnDefinition(
DataType.TEXT, "password", "DEFAULT NULL")));
}
}
private void addDeletedColumn(TableDefinition... defs) {
for (TableDefinition t : defs) {
statements.add(new AddColumnStatement(t, new ColumnDefinition(
DataType.DATETIME, "deleted", " DEFAULT null")));
}
}
private void createWith(TableDefinition... defs) {
for (TableDefinition d : defs) {
statements.add(new CreateTableStatement(d));
}
}
private void createAll() {
List<ColumnDefinition> columns = createPersonColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
person = new TableDefinition("person", dbType, columns);
columns = createContactColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
contact = new TableDefinition("contact", dbType, columns);
columns = createRelativeColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
relative = new TableDefinition("relative", dbType, columns);
columns = createAdressColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
adress = new TableDefinition("adress", dbType, columns);
columns = createAttendanceColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
attendance = new TableDefinition("ATTENDANCE".toLowerCase(), dbType,
columns);
ColumnDefinition colVersion = new ColumnDefinition(DataType.INTEGER,
"version", "NOT NULL");
columns = new ArrayList<ColumnDefinition>();
columns.add(colVersion);
version = new TableDefinition("version", dbType, columns);
columns = createDeletedEntriesColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
deletedEntries = new TableDefinition("deleted_entries", dbType,
columns);
columns = createGroupColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
group = new TableDefinition("groupDef", dbType, columns);
columns = createPersonGroupColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
persongroup = new TableDefinition("persongroup", dbType, columns);
columns = createStartpassColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
startpass = new TableDefinition("startpaesse", dbType, columns);
columns = createStartrechtColumns();
addCreateChangeColumn(columns);
addDeleteColumn(columns);
startrecht = new TableDefinition("startpass_startrechte", dbType,
columns);
allTables = Arrays.asList(person, contact, relative, adress, attendance,
version, deletedEntries, group, persongroup, startpass,
startrecht);
}
private List<ColumnDefinition> createStartrechtColumns() {
ColumnDefinition colStartpassId = new ColumnDefinition(DataType.INTEGER,
"startpass_id", "NOT NULL");
ColumnDefinition colStartRechtVerein = new ColumnDefinition(
DataType.VARCHAR100, "verein_name", "NOT NULL");
ColumnDefinition colStartRechtFachgebiet = new ColumnDefinition(
DataType.VARCHAR25, "fachgebiet", "NOT NULL");
ColumnDefinition colGueltigVon = new ColumnDefinition(DataType.DATETIME,
"startrecht_beginn", "NOT NULL");
ColumnDefinition colGueltigBis = new ColumnDefinition(DataType.DATETIME,
"startrecht_ende", "NOT NULL");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colStartpassId);
columns.add(colStartRechtVerein);
columns.add(colStartRechtFachgebiet);
columns.add(colGueltigVon);
columns.add(colGueltigBis);
return columns;
}
private List<ColumnDefinition> createStartpassColumns() {
ColumnDefinition colPersonId = new ColumnDefinition(DataType.INTEGER,
PERSON_ID_FK_NAME, "NOT NULL");
ColumnDefinition colStartpassNr = new ColumnDefinition(
DataType.VARCHAR25, "startpass_nr", "NOT NULL UNIQUE");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colPersonId);
columns.add(colStartpassNr);
return columns;
}
private List<ColumnDefinition> createGroupColumns() {
ColumnDefinition colTableName = new ColumnDefinition(
DataType.VARCHAR255, "name", "NOT NULL UNIQUE");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colTableName);
return columns;
}
private List<ColumnDefinition> createPersonGroupColumns() {
ColumnDefinition colPersonId = new ColumnDefinition(DataType.INTEGER,
PERSON_ID_FK_NAME, "NOT NULL");
ColumnDefinition colGroupId = new ColumnDefinition(DataType.INTEGER,
"group_id", "NOT NULL");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colPersonId);
columns.add(colGroupId);
return columns;
}
private List<ColumnDefinition> createDeletedEntriesColumns() {
ColumnDefinition colTableName = new ColumnDefinition(DataType.VARCHAR25,
"tablename", "NOT NULL");
ColumnDefinition colEntryId = new ColumnDefinition(DataType.INTEGER,
"entryId", "NOT NULL");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colTableName);
columns.add(colEntryId);
return columns;
}
private List<ColumnDefinition> createAttendanceColumns() {
ColumnDefinition colOnDate = new ColumnDefinition(DataType.DATETIME,
"on_date");
ColumnDefinition colPersonId = new ColumnDefinition(DataType.INTEGER,
PERSON_ID_FK_NAME, "NOT NULL");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colOnDate);
columns.add(colPersonId);
return columns;
}
private List<ColumnDefinition> createAdressColumns() {
ColumnDefinition colAdress1 = new ColumnDefinition(DataType.TEXT,
"adress1");
ColumnDefinition colAdress2 = new ColumnDefinition(DataType.TEXT,
"adress2");
ColumnDefinition colPlz = new ColumnDefinition(DataType.TEXT, "plz");
ColumnDefinition colCity = new ColumnDefinition(DataType.TEXT, "city");
ColumnDefinition colPersonId = new ColumnDefinition(DataType.INTEGER,
PERSON_ID_FK_NAME, "NOT NULL");
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(colAdress1);
columns.add(colAdress2);
columns.add(colPlz);
columns.add(colCity);
columns.add(colPersonId);
return columns;
}
private List<ColumnDefinition> createRelativeColumns() {
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(
new ColumnDefinition(DataType.INTEGER, "person1", "NOT NULL"));
columns.add(
new ColumnDefinition(DataType.INTEGER, "person2", "NOT NULL"));
columns.add(new ColumnDefinition(DataType.TEXT, "TO_PERSON2_RELATION"));
columns.add(new ColumnDefinition(DataType.TEXT, "TO_PERSON1_RELATION"));
return columns;
}
private List<ColumnDefinition> createContactColumns() {
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(new ColumnDefinition(DataType.TEXT, "type", "NOT NULL"));
columns.add(new ColumnDefinition(DataType.TEXT, "value"));
columns.add(new ColumnDefinition(DataType.INTEGER, PERSON_ID_FK_NAME,
"NOT NULL"));
return columns;
}
private List<ColumnDefinition> createPersonColumns() {
List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
columns.add(new ColumnDefinition(DataType.TEXT, "prename", "NOT NULL"));
columns.add(new ColumnDefinition(DataType.TEXT, "surname"));
columns.add(new ColumnDefinition(DataType.DATETIME, "birth"));
columns.add(new ColumnDefinition(DataType.TEXT, "username",
"DEFAULT NULL"));
columns.add(new ColumnDefinition(DataType.TEXT, "password",
"DEFAULT NULL"));
return columns;
}
private void addCreateChangeColumn(List<ColumnDefinition> columns) {
columns.add(new ColumnDefinition(DataType.DATETIME, "changed"));
columns.add(new ColumnDefinition(DataType.DATETIME, "created"));
}
public void executeOn(Database db) throws SQLException {
for (MyStatement stm : statements) {
String sql = stm.getSql();
if (logger.isDebugEnabled()) {
logger.debug(sql);
}
try {
db.execSQL(sql);
} catch (SQLException ex) {
throw new SQLException("Error on: " + sql, ex);
}
}
String sql;
if (fromVersion == 0) {
sql = "INSERT INTO version(version) VALUES (" + LATEST_VERSION
+ ")";
} else {
sql = "UPDATE version SET version=" + LATEST_VERSION;
}
if (fromVersion != LATEST_VERSION) {
if (logger.isDebugEnabled()) {
logger.debug(sql);
}
db.execSQL(sql);
if (logger.isInfoEnabled()) {
logger.info("Updated database to version " + LATEST_VERSION);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Database was up to date.");
}
}
}
private class DropColumnStatement extends AddColumnStatement {
public DropColumnStatement(TableDefinition def, ColumnDefinition col) {
super(def, col);
}
@Override
public String getSql() {
return de.kreth.dbmanager.DbManager.createSqlDropColumns(def, col);
}
}
private class AddColumnStatement extends CreateTableStatement {
protected ColumnDefinition col;
public AddColumnStatement(TableDefinition def, ColumnDefinition col) {
super(def);
this.col = col;
}
@Override
public String getSql() {
return de.kreth.dbmanager.DbManager.createSqlAddColumns(def, col);
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + col + " to " + def;
}
}
private class AddConstraint extends CreateTableStatement {
private UniqueConstraint constraint;
public AddConstraint(TableDefinition def, UniqueConstraint constraint) {
super(def);
this.constraint = constraint;
}
@Override
public String getSql() {
return de.kreth.dbmanager.DbManager.createUniqueConstraint(def,
constraint);
}
}
private class CreateTableStatement implements MyStatement {
protected TableDefinition def;
public CreateTableStatement(TableDefinition def) {
this.def = def;
}
@Override
public String getSql() {
return de.kreth.dbmanager.DbManager.createSqlStatement(def);
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + def;
}
}
private class DirectStatement implements MyStatement {
private String sql;
public DirectStatement(String sql) {
super();
this.sql = sql;
}
@Override
public String getSql() {
return sql;
}
@Override
public String toString() {
return sql;
}
}
private interface MyStatement {
String getSql();
}
}
| 28.918797
| 138
| 0.735115
|
917d988bd2cb9d40c90bada6fb3eb0edbaeddf0e
| 294
|
package org.hswebframework.payment.account.dao;
import org.hswebframework.payment.account.dao.entity.AccountTransLogEntity;
import org.hswebframework.web.dao.CrudDao;
/**
* @author Lind
* @since 1.0
*/
public interface AccountTransLogDao extends CrudDao<AccountTransLogEntity, String> {
}
| 24.5
| 84
| 0.79932
|
039e8f43bfa42211b7b31ad62fcdc2ea257de79a
| 2,650
|
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.ImportedWindowsAutopilotDeviceIdentityUploadStatus;
import com.microsoft.graph.models.ImportedWindowsAutopilotDeviceIdentity;
import com.microsoft.graph.models.Entity;
import com.microsoft.graph.requests.ImportedWindowsAutopilotDeviceIdentityCollectionPage;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Imported Windows Autopilot Device Identity Upload.
*/
public class ImportedWindowsAutopilotDeviceIdentityUpload extends Entity implements IJsonBackedObject {
/**
* The Created Date Time Utc.
* DateTime when the entity is created.
*/
@SerializedName(value = "createdDateTimeUtc", alternate = {"CreatedDateTimeUtc"})
@Expose
@Nullable
public java.time.OffsetDateTime createdDateTimeUtc;
/**
* The Status.
* Upload status.
*/
@SerializedName(value = "status", alternate = {"Status"})
@Expose
@Nullable
public ImportedWindowsAutopilotDeviceIdentityUploadStatus status;
/**
* The Device Identities.
* Collection of all Autopilot devices as a part of this upload.
*/
@SerializedName(value = "deviceIdentities", alternate = {"DeviceIdentities"})
@Expose
@Nullable
public ImportedWindowsAutopilotDeviceIdentityCollectionPage deviceIdentities;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
if (json.has("deviceIdentities")) {
deviceIdentities = serializer.deserializeObject(json.get("deviceIdentities"), ImportedWindowsAutopilotDeviceIdentityCollectionPage.class);
}
}
}
| 35.810811
| 152
| 0.710566
|
b2125e803609b3f3a4937080f548bea21a6d724f
| 3,334
|
package cybervelia.autocloner;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cybervelia.sdk.controller.BLEService;
import cybervelia.sdk.types.ConnectionTypesCommon;
import cybervelia.sdk.types.ConnectionTypesCommon.AddressType;
import cybervelia.server.CryptoHelper;
class BLEDevice {
private ArrayList<DeviceDatum> data;
private AddressType address_type;
private String address = "";
private int datacounter = 0;
private String adv_data = null;
private String scan_data = null;
private String devname = null;
private JSONArray discovery_services = null;
private boolean bond_happened = false;
BLEDevice(AddressType address_type, String address){
this.address = address;
this.address_type = address_type;
data = new ArrayList<DeviceDatum>();
}
public void setOnlyAdvData(String data) {
this.adv_data = data;
}
public void setOnlyScanData(String data) {
this.scan_data = data;
}
public boolean hasAdvData() {
return this.adv_data == null ? false : true;
}
public void bond() {
this.bond_happened = true;
}
public boolean hasScanData() {
return this.scan_data == null ? false : true;
}
public void setDeviceName(String devname) {
this.devname = devname;
}
public void setDiscoveryData(List<BLEService> services) throws JSONException {
this.discovery_services = jsonSerializeDiscoveryData(services);
}
public void putData(String characteristic, byte[] value, int datalen, DeviceDatum.operation operation) {
String strvalue = "";
if (datalen > 0)
strvalue = CryptoHelper.bytesToHex(value, datalen);
DeviceDatum datum = new DeviceDatum(characteristic, strvalue, datacounter++, operation);
data.add(datum);
}
public void setAdvertisementData(String adv_data, String scan_data) {
this.adv_data = adv_data;
this.scan_data = scan_data;
}
private JSONArray jsonSerializeData() throws JSONException {
JSONArray json_data = new JSONArray();
for(DeviceDatum datum : data) {
json_data.put(datum.jsonSerialize());
}
return json_data;
}
private JSONArray jsonSerializeDiscoveryData(List<BLEService> services) throws JSONException {
JSONArray json_services = new JSONArray();
if (services == null) {
System.err.println("Discovery services cannot be retrieved");
return null;
}
for(BLEService service : services) {
JSONObject json_service = new JSONObject();
json_service.put("service", service.getUUID().toString());
json_service.put("handle", String.valueOf(service.getHandle()));
json_service.put("characteristics", service.serializeCharacteristics());
json_services.put(json_service);
}
return json_services;
}
public JSONObject jsonSerialize() throws JSONException {
JSONObject device = new JSONObject();
if (discovery_services == null) return null;
device.put("address", address);
device.put("address_type", ConnectionTypesCommon.getStringFromAddressType(address_type));
device.put("data", jsonSerializeData());
if (hasAdvData())
device.put("advpacket", adv_data);
if (hasScanData())
device.put("scanpacket", scan_data);
if (devname != null)
device.put("name", devname);
device.put("discovery", discovery_services);
device.put("bond", bond_happened);
return device;
}
}
| 29.245614
| 105
| 0.745951
|
c814a101935148ef8eaa314c6e47f9455e13f6f2
| 178
|
package com.example.camel.demo;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String generate() {
return "Hello Camel!";
}
}
| 16.181818
| 48
| 0.735955
|
a7315af32d609d4915b52a853e5825c7202b059b
| 1,985
|
package com.mjj.viewflipper;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.text);
final ViewFlipper flipper = (ViewFlipper) findViewById(R.id.flipper);
flipper.addView(getImageView(R.mipmap.abcde_a));
flipper.addView(getImageView(R.mipmap.abcde_b));
flipper.addView(getImageView(R.mipmap.abcde_d));
flipper.setInAnimation(this, R.anim.push_up_in);
flipper.setOutAnimation(this, R.anim.push_up_out);
flipper.setFlipInterval(3000);
flipper.getInAnimation().setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
textView.setText((flipper.getDisplayedChild()+1)+"/"+flipper.getChildCount());
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
textView.setText((flipper.getDisplayedChild()+1)+"/"+flipper.getChildCount());
flipper.startFlipping();
}
public TextView getTextView(String text){
TextView textView = new TextView(this);
textView.setText(text);
textView.setTextSize(50f);
textView.setGravity(Gravity.CENTER);
return textView;
}
public ImageView getImageView(int res){
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(res);
return imageView;
}
}
| 30.538462
| 94
| 0.671537
|
f476130d7ff8a75f3fbbca1d8cfb26ee404724b4
| 5,905
|
/*
* 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.aliyuncs.retailcloud.model.v20180313;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.retailcloud.transform.v20180313.ListClusterResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class ListClusterResponse extends AcsResponse {
private String requestId;
private Integer code;
private String errorMsg;
private Integer pageNumber;
private Integer pageSize;
private Long totalCount;
private List<ClusterInfo> data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Integer getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Long getTotalCount() {
return this.totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public List<ClusterInfo> getData() {
return this.data;
}
public void setData(List<ClusterInfo> data) {
this.data = data;
}
public static class ClusterInfo {
private String vpcId;
private String status;
private String podCIDR;
private String businessCode;
private String instanceId;
private String createStatus;
private String clusterTitle;
private String regionId;
private String envType;
private String password;
private String workLoadMem;
private String serviceCIDR;
private String regionName;
private String workLoadCpu;
private String keyPair;
private String netPlug;
private Long id;
private List<String> ecsIds;
private List<String> vswitchIds;
public String getVpcId() {
return this.vpcId;
}
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPodCIDR() {
return this.podCIDR;
}
public void setPodCIDR(String podCIDR) {
this.podCIDR = podCIDR;
}
public String getBusinessCode() {
return this.businessCode;
}
public void setBusinessCode(String businessCode) {
this.businessCode = businessCode;
}
public String getInstanceId() {
return this.instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getCreateStatus() {
return this.createStatus;
}
public void setCreateStatus(String createStatus) {
this.createStatus = createStatus;
}
public String getClusterTitle() {
return this.clusterTitle;
}
public void setClusterTitle(String clusterTitle) {
this.clusterTitle = clusterTitle;
}
public String getRegionId() {
return this.regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getEnvType() {
return this.envType;
}
public void setEnvType(String envType) {
this.envType = envType;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getWorkLoadMem() {
return this.workLoadMem;
}
public void setWorkLoadMem(String workLoadMem) {
this.workLoadMem = workLoadMem;
}
public String getServiceCIDR() {
return this.serviceCIDR;
}
public void setServiceCIDR(String serviceCIDR) {
this.serviceCIDR = serviceCIDR;
}
public String getRegionName() {
return this.regionName;
}
public void setRegionName(String regionName) {
this.regionName = regionName;
}
public String getWorkLoadCpu() {
return this.workLoadCpu;
}
public void setWorkLoadCpu(String workLoadCpu) {
this.workLoadCpu = workLoadCpu;
}
public String getKeyPair() {
return this.keyPair;
}
public void setKeyPair(String keyPair) {
this.keyPair = keyPair;
}
public String getNetPlug() {
return this.netPlug;
}
public void setNetPlug(String netPlug) {
this.netPlug = netPlug;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public List<String> getEcsIds() {
return this.ecsIds;
}
public void setEcsIds(List<String> ecsIds) {
this.ecsIds = ecsIds;
}
public List<String> getVswitchIds() {
return this.vswitchIds;
}
public void setVswitchIds(List<String> vswitchIds) {
this.vswitchIds = vswitchIds;
}
}
@Override
public ListClusterResponse getInstance(UnmarshallerContext context) {
return ListClusterResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
| 19.61794
| 84
| 0.685182
|
311124e697e963895f2bcd8578aa29db41a077e8
| 737
|
/**
*
*/
package com.tedros.location.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.tedros.ejb.base.entity.TEntity;
import com.tedros.location.domain.DomainSchema;
import com.tedros.location.domain.DomainTables;
/**
* @author Davis Gordon
*
*/
@Entity
@Table(name = DomainTables.streetType, schema = DomainSchema.schema)
public class StreetType extends TEntity {
private static final long serialVersionUID = 1L;
@Column(length=30, nullable=false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name!=null ? name : "";
}
}
| 17.97561
| 68
| 0.7327
|
4cab7eb57b2f88336a72931c6290083459a7d663
| 5,459
|
package com.palindrome.message.palindromemessageservice.controller;
import com.palindrome.message.palindromemessageservice.error.MessageNotFoundException;
import com.palindrome.message.palindromemessageservice.model.Message;
import com.palindrome.message.palindromemessageservice.service.MessageService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.util.NestedServletException;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@WebMvcTest(value = MessageController.class)
@AutoConfigureMockMvc(addFilters=false)
public class MessageControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MessageService messageService;
@Test
public void testCreateMessage() throws Exception {
Message mockMessage = new Message("this is a message");
Mockito.when(
messageService.createMessage(Mockito.anyString())).thenReturn(mockMessage.getId());
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(
"/messages/create").accept(
MediaType.APPLICATION_JSON).content("this is a message").contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
@Test
public void testRetrieveMessage_success() throws Exception {
Message mockMessage = new Message("this is a message");
Mockito.when(
messageService.retrieveMessage(Mockito.anyLong())).thenReturn(mockMessage);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/messages/"+mockMessage.getId()).accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = "{id:"+mockMessage.getId()+"}";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
@Test(expected = NestedServletException.class)
public void testRetrieveMessage_failure() throws Exception {
Message mockMessage = new Message("this is a message");
Mockito.when(
messageService.retrieveMessage(Mockito.anyLong())).thenThrow(new MessageNotFoundException());
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/messages/"+mockMessage.getId()).accept(
MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.NOT_FOUND.value(), result.getResponse().getStatus());
}
@Test
public void testUpdateMessage() throws Exception {
Message mockMessage = new Message("text");
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(
"/messages/update/"+mockMessage.getId()).accept(
MediaType.APPLICATION_JSON).content("updated text").contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
@Test
public void testDeleteMessage() throws Exception {
Message mockMessage = new Message("this is a message");
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(
"/messages/delete/"+mockMessage.getId()).accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(result.getResponse().getStatus(), HttpStatus.OK.value());
}
@Test
public void testRetrieveAllMessages() throws Exception {
Message mockMessage1 = new Message("messageText1");
Message mockMessage2 = new Message("messageText2");
List<Message> mockMessages = new ArrayList<>();
mockMessages.add(mockMessage1);
mockMessages.add(mockMessage2);
Mockito.when(
messageService.retrieveAllMessages()).thenReturn(mockMessages);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/messages/all").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = "[{\"id\":0,\"text\":\"messageText1\",\"palindrome\":false},{\"id\":0,\"text\":\"messageText2\",\"palindrome\":false}]";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
}
| 43.325397
| 146
| 0.715516
|
320856c562065794fce81ad1a584e663f717f47f
| 449
|
package mb.pie.lang.test.imports.subModule.importPartialModulePathForeignPie;
import mb.pie.api.ExecException;
import mb.pie.api.None;
import org.junit.jupiter.api.Test;
import static mb.pie.lang.test.util.SimpleChecker.assertTaskOutputEquals;
class ImportPartialModulePathForeignPieTest {
@Test void test() throws ExecException {
assertTaskOutputEquals(DaggerimportPartialModulePathForeignPieComponent.class, None.instance);
}
}
| 32.071429
| 102
| 0.815145
|
83d7a99161e04cdf0e4c47ad9e84b55fa93f988a
| 4,174
|
package com.dankideacentral.dic.util;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Class: LocationFinder.java
* Purpose: Utility to help search for the device's
* current location.
*
* @author Chris Ermel
* @version 1.0
* @since 2016-10-23
*/
public abstract class LocationFinder implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String LOG_TAG = "LOCATION_FINDER";
public static final int LOCATION_SERVICES_OFF = 0;
private GoogleApiClient googleApiClient;
private Context context;
public LocationFinder(Context context) {
this.context = context;
// Instantiate GoogleAPIClient with given context
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Upon initializing, attempt to connect to client right away
googleApiClient.connect();
}
/**
* Connection callback for {@link GoogleApiClient}.
*
* @param bundle
* Data provided to {@link GoogleApiClient} by Google Play services.
*/
@Override
public void onConnected(@Nullable Bundle bundle) {
// On successful connection, log at info level
Log.i(LOG_TAG, "GoogleApiClient successfully connected.");
// Begin requesting location updates
startLocationUpdates();
}
/**
* Connection suspension callback for {@link GoogleApiClient}.
*
* @param cause
* The suspension causation code given to the callback method.
*/
@Override
public void onConnectionSuspended(int cause) {
// On connection suspension, log at info level
Log.i(LOG_TAG, "GoogleApiClient suspended with code: " + cause + ".");
}
/**
* Connection error callback for {@link GoogleApiClient}.
*
* @param result
* A {@link ConnectionResult} object used to
* determine what type of error occurred.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
// Error handling can be implemented here
// For now, log the connection failure at debug level
Log.d(LOG_TAG, "GoogleApiClient connection failed.");
}
/**
* Disconnects the {@link LocationFinder}'s
* {@link GoogleApiClient}.
*/
public void disconnect() {
googleApiClient.disconnect();
}
/**
* Stops the {@link GoogleApiClient}'s listening for location updates.
*/
public void stopLocationUpdates() {
// Stop location updates from occurring
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
}
/**
* Starts a request for location updates from the {@link GoogleApiClient}.
*/
private void startLocationUpdates() {
Log.v(getClass().getName(), "startingLocationUpdates");
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, LocationRequest.create(), this);
} catch (SecurityException e) {
// SecurityException thrown if location permissions are disabled
Log.d(LOG_TAG, "Location permissions deactivated when attempting to recover location.");
// Toast small message to user
Toast.makeText(context, "Location services turned off.", Toast.LENGTH_LONG).show();
onError(LocationFinder.LOCATION_SERVICES_OFF);
}
}
protected abstract void onError (int type);
}
| 33.934959
| 100
| 0.669382
|
b84eda7b3ca2c43b1d7bf83037b2a9ba376d6179
| 2,120
|
package com.imchuan.service.cms.impl;
import com.imchuan.api.pojo.Select2;
import com.imchuan.api.service.impl.BaseServiceImpl;
import com.imchuan.conversion.cms.CmsTagsToDtoConverter;
import com.imchuan.conversion.cms.CmsTagsToModelConverter;
import com.imchuan.conversion.cms.CmsTagsToSelect2Converter;
import com.imchuan.domian.cms.CmsTagsDomain;
import com.imchuan.dto.cms.CmsTagsDto;
import com.imchuan.entity.cms.CmsTags;
import com.imchuan.service.cms.CmsTagsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
/**
* 标签
*
* @author liuqq
* @email muchuanj@163.com
* @date 2015-12-03 15:36
*/
@Transactional
@Service("cmsTagsService")
public class CmsTagsServiceImpl extends BaseServiceImpl<CmsTags, CmsTagsDto, String> implements CmsTagsService {
@Resource
private CmsTagsToDtoConverter cmsTagsToDtoConverter;
@Resource
private CmsTagsToModelConverter cmsTagsToModelConverter;
@Resource
private CmsTagsToSelect2Converter cmsTagsToSelect2Converter;
@Override
@PostConstruct
public void initConverter() {
super.setConverter(cmsTagsToModelConverter, cmsTagsToDtoConverter);
}
/**
* 获取所有标签
*
* @return
*/
@Override
public List<Select2> getSelect2Data() {
final List<CmsTags> cmsTagses = super.getBaseDao().findAll(CmsTags.class);
return cmsTagsToSelect2Converter.convertAll(cmsTagses);
}
/**
* 保存
*
* @param tagNames
*/
@Override
public void saveTags(final List<String> tagNames) {
for (final String tagName : tagNames) {
final CmsTagsDto cmsTagsDto = super.findOneByProperty(CmsTagsDomain.NAME, tagName);
if (Objects.nonNull(cmsTagsDto)) {
continue;
}
final CmsTags cmsTags = getBaseDao().create(CmsTags.class);
cmsTags.setName(tagName);
getBaseDao().save(cmsTags);
}
}
}
| 29.041096
| 112
| 0.716981
|
68ffd9d994e24ecc8e99a8372b7fee591573b757
| 274
|
package yoshikihigo.cpanalyzer;
public class FileUtility {
public static LANGUAGE getLANGUAGE(final String name) {
for (final LANGUAGE language : LANGUAGE.values()) {
if (language.isTarget(name)) {
return language;
}
}
return null;
}
}
| 19.571429
| 57
| 0.656934
|
653ea634721b1d1959d2e1346fd4e6d971cb7f7b
| 1,015
|
package com.wut.resources.users;
import com.wut.datasources.CrudSource;
import com.wut.model.Data;
import com.wut.model.map.MappedData;
import com.wut.model.map.MessageData;
import com.wut.pipeline.Authenticator;
import com.wut.pipeline.WutRequest;
public class PingOperation extends UserOperation {
public PingOperation(CrudSource source) {
super(source);
}
@Override
public String getName() {
return "ping";
}
@Override
public Data perform(WutRequest ri) {
String application = ri.getApplication();
String customer = ri.getCustomer();
String username = ri.getUserId();
try {
String id = Authenticator.getUserId(customer, username);
MappedData data = (MappedData) source.read(customer, application, id);
if (data.equals(MessageData.NO_DATA_FOUND)) {
data.put("message", customer + ":" + username);
return data;
}
return MessageData.successOrFailure(data.get("username").toString().equals(username));
} catch (Exception e) {
return MessageData.error(e);
}
}
}
| 26.025641
| 89
| 0.731034
|
3d3928ee646cdb50723a6056eea078cdf876722e
| 10,525
|
/*
* [The "BSD license"]
* Copyright (c) 2002-2011, Rodney O'Donnell, Lloyd Allison, Kevin Korb
* Copyright (c) 2002-2011, Monash University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.*
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// Simple Search for CaMML
//
// File: GreedyLookaheadSearch.java
// Author: rodo@dgs.monash.edu.au
package camml.core.search;
import cdms.core.*;
/**
* GreedyLookaheadSearch as the name suggests is a very basic search algorithm to find the TOM with
* the lowest mml cost. This cost is simply the sum of costs of each node. Each node being a
* single CPT.
* No attemts is made to take into consideration the number of orderings in the network, or any
* other factors which a more complete searhc would address. <br>
* This search is intended to be a prototype and nothing more.
*/
public class GreedyLookaheadSearch
extends BNetSearch
{
/** Maximum number of steps to look ahead */
protected final int maxLookahead;
/** Current Epoch */
protected int epoch = 0;
/** Maximum number of epochs */
protected final int max = 1000;
/** flag if search is complete or not. */
protected boolean searchDone = false;
/**
* Reset the search. <p>
* NOTE:TOM is not reset here (but possibly should be?)
*/
public void reset()
{
// randomise the initial order of nodes so it is not bias towards an a->b->c type ordering.
tom.randomOrder(rand);
epoch = 0;
searchDone = false;
}
/** mutate the TOM. a & b are nodes, operation = (toggleArc,swapOrder)*/
void mutate( int operation, int a, int b)
{
if (operation == 0)
toggleArc(a,b);
else if (operation == 1)
swapOrder(a,b);
}
/** If arc is present remove it, if are is not present create it */
void toggleArc( int a, int b)
{
if ( tom.isArc(a,b) ) {
tom.removeArc(a,b);
}
else {
tom.addArc(a,b);
}
}
/** Swap the order of a abd b in the network */
void swapOrder( int a, int b )
{
tom.swapOrder( a, b, true );
}
/**
* Given a single mutation, look ahead k operations and return the best cost seen. <br>
* If k = 0 then no lookahead is performed. <br>
* To speed things up, all operations are given an ordering.
**/
double lookahead( int currentOperation, int currentA, int currentB, int k )
{
// Perform the initial mutation on the network and use this cost as bestCost
mutate( currentOperation, currentA, currentB );
// double bestCost = costNetwork() + structureCost;
double bestCost = costNetwork( mmlModelLearner, false );
if (k != 0) {
// Do a single iteration of a greedy search.
for ( int a = 0; a < tom.getNumNodes(); a++ ) {
for (int b = a+1; b < tom.getNumNodes(); b++ ) {
// operation = toggleArc(a,b) or swapOrder(a,b)
for (int operation = 0; operation < 2; operation ++ ) {
// always try to toggle an arc's existance, but only it's direction if it
// exists in the network.
if ( operation == 0 || tom.isArc(a,b) ) {
double cost = lookahead(operation,a,b,k-1);
// If this is the best operation found so far remember it.
if ( cost < bestCost ) {
bestCost = cost;
}
}
}
}
}
}
// reverse the initial mutation. This puts the TOM into it's original orientation.
mutate( currentOperation, currentA, currentB );
return bestCost;
}
/**
* In a single epoch we try all single mutations and take the one which lookahead()
* tells us has the best prospects.
*/
public double doEpoch()
{
int bestA = -1;
int bestB = -1;
int bestOperation = -1;
double baseNetworkCost = costNetwork( mmlModelLearner, false );
double bestCost = baseNetworkCost;
double cost;
boolean networkUpdated = false;
// do not mutate on first epoch. This gives the initial model zero arcs.
if (epoch != 0) {
for (int a = 0; a < tom.getNumNodes(); a++)
for (int b = a+1; b < tom.getNumNodes(); b++)
for (int op = 0; op < 2; op++) {
if ( op == 0 || tom.isArc(a,b) ) {
cost = lookahead(op,a,b,maxLookahead);
// if 2 costs are equal, resolve the tiebreak by checking which
// cost is best with a reduced lookahead. Without this cycles
// occur in the search space
if ( cost == bestCost ) {
// System.out.println(" -- Equal Best Model -- ");
int tempLookahead = maxLookahead - 1;
while (tempLookahead >=0 ) {
// Work out if the current or previous best has the best cost
// with a reduced lookahead.
double cost1 = lookahead( op,a,b,tempLookahead );
double cost2 = lookahead( bestOperation,bestA,
bestB,tempLookahead );
if ( cost1 < cost2 ) {
bestCost = cost;
bestA = a;
bestB = b;
bestOperation = op;
networkUpdated = true;
System.out.println(" --- New Best Model --- " + bestCost );
break;
}
else if ( cost1 > cost2 ) {
// System.out.print(" -- Worse Best Model -- ");
break;
}
else if ( cost1 == cost2 ) {
tempLookahead --;
// System.out.println("Looking ahead with k = "+tempLookahead);
}
}
}
else if ( cost > bestCost ) {
// System.out.print(" -- Worse Best Model -- ");
}
else if (cost < bestCost) {
bestCost = cost;
bestA = a;
bestB = b;
bestOperation = op;
networkUpdated = true;
System.out.println(" --- New Best Model --- " + bestCost );
}
}
}
}
// else if epoch == 0
else {
// bestCost = costNetwork() + structureCost;
bestCost = costNetwork( mmlModelLearner, false );
bestA = 0;
bestB = 0;
bestOperation = 0;
}
if ( networkUpdated || epoch == 0 ) {
System.out.println("New best TOM found : epoch = " + epoch);
// re-mutate the network to the best found so far.
mutate( bestOperation,bestA,bestB );
System.out.print(tom);
System.out.println("Network Cost = " + costNetwork( mmlModelLearner,false) + "\n");
}
else {
searchDone = true;
}
epoch++;
return bestCost;
}
public boolean isFinished()
{
return (epoch == max || searchDone == true);
}
public double getPercentage()
{
return (epoch / (double)max);
}
/** Create a new TOM with no arcs present. */
public GreedyLookaheadSearch( java.util.Random rand, Value.Vector data, int maxLookahead )
{
super( rand, data, SearchPackage.mlCPTLearner, SearchPackage.mmlCPTLearner );
this.maxLookahead = maxLookahead;
}
}
| 39.126394
| 123
| 0.480855
|
fece2e667233522619957d04afa65b70562a5eee
| 452
|
package com.chobocho.mahjong.button;
public interface ImageButton {
public void setId(int id);
public int getId();
public int getResourceId();
public void setResourceId(int id);
public void setPosition(int x1, int y1, int x2, int y2);
public boolean isInRange(int x, int y);
public void enable(boolean enable);
public boolean isEnabled();
public void show();
public void hide();
public boolean isShown();
}
| 28.25
| 60
| 0.688053
|
df6d9f4d1ed8488cb84efacbf5e7831345753381
| 602
|
package us.dot.its.jpo.ode.plugin.j2735;
import java.util.ArrayList;
import java.util.List;
import us.dot.its.jpo.ode.plugin.asn1.Asn1Object;
public class J2735RestrictionUserTypeList extends Asn1Object {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<J2735RestrictionUserType> restrictionUserType = new ArrayList<>();
public List<J2735RestrictionUserType> getRestrictionUserType() {
return restrictionUserType;
}
public void setRestrictionUserType(List<J2735RestrictionUserType> restrictionUserType) {
this.restrictionUserType = restrictionUserType;
}
}
| 24.08
| 89
| 0.792359
|
c1f6fb725a9026a919ec9ac061a5637bad33e0b7
| 1,591
|
/**
* Copyright 2019 Anthony Trinh
*
* 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 ch.qos.logback.core.pattern.parser;
public class CompositeNode extends SimpleKeywordNode {
Node childNode;
CompositeNode(String keyword) {
super(Node.COMPOSITE_KEYWORD, keyword);
}
public Node getChildNode() {
return childNode;
}
public void setChildNode(Node childNode) {
this.childNode = childNode;
}
public boolean equals(Object o) {
if(!super.equals(o)) {
return false;
}
if (!(o instanceof CompositeNode)) {
return false;
}
CompositeNode r = (CompositeNode) o;
return (childNode != null) ? childNode.equals(r.childNode)
: (r.childNode == null);
}
@Override
public int hashCode() {
return super.hashCode();
}
public String toString() {
StringBuilder buf = new StringBuilder();
if(childNode != null) {
buf.append("CompositeNode("+childNode+")");
} else {
buf.append("CompositeNode(no child)");
}
buf.append(printNext());
return buf.toString();
}
}
| 25.66129
| 75
| 0.675676
|
ba362b6b925f182b33db491e48684abd2dfa7f1d
| 645
|
package DeckSummary.statistics;
public class StatOutput {
public String name;
public int conservativeEstimate;
public int optimisticEstimate;
public StatOutput(String name, int conservativeEstimate, int optimisticEstimate) {
this.name = name;
this.conservativeEstimate = conservativeEstimate;
this.optimisticEstimate = optimisticEstimate;
}
public String getValueString() {
if (conservativeEstimate == optimisticEstimate) {
return Integer.toString(conservativeEstimate);
} else {
return conservativeEstimate + "-" + optimisticEstimate;
}
}
}
| 29.318182
| 86
| 0.685271
|
5fba63b444ffd7f3af6b2f001b067888f5aff0fd
| 6,241
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016. Diorite (by Bartłomiej Mazur (aka GotoFinal))
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.diorite.material.items;
import java.util.Map;
import org.diorite.material.BasicToolData;
import org.diorite.utils.collections.maps.CaseInsensitiveMap;
import org.diorite.utils.lazy.LazyValue;
import org.diorite.utils.math.DioriteMathUtils;
import it.unimi.dsi.fastutil.shorts.Short2ObjectMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap;
/**
* Class representing 'Shears' item material in minecraft. <br>
* ID of material: 359 <br>
* String ID of material: minecraft:shears <br>
* Max item stack size: 1
*/
@SuppressWarnings({"JavaDoc", "ClassHasNoToStringMethod"})
public class ShearsMat extends BasicToolMat
{
/**
* Sub-ids used by diorite/minecraft by default
*/
public static final int USED_DATA_VALUES = 1;
public static final ShearsMat SHEARS = new ShearsMat();
private static final Map<String, ShearsMat> byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
private static final Short2ObjectMap<ShearsMat> byID = new Short2ObjectOpenHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
protected final LazyValue<ShearsMat> next = new LazyValue<>(() -> (this.haveValidDurability()) ? getByDurability(this.getDurability() + 1) : null);
protected final LazyValue<ShearsMat> prev = new LazyValue<>(() -> (this.haveValidDurability()) ? getByDurability(this.getDurability() - 1) : null);
@SuppressWarnings("MagicNumber")
public ShearsMat()
{
super("SHEARS", 359, "minecraft:shears", "NEW", (short) 0x00, new BasicToolData(237));
}
public ShearsMat(final int durability)
{
super(SHEARS.name(), SHEARS.getId(), SHEARS.getMinecraftId(), Integer.toString(durability), (short) durability, new BasicToolData(SHEARS.getToolData()));
}
public ShearsMat(final String enumName, final int id, final String minecraftId, final String typeName, final short type, final BasicToolData toolData)
{
super(enumName, id, minecraftId, typeName, type, toolData);
}
public ShearsMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final short type, final BasicToolData toolData)
{
super(enumName, id, minecraftId, maxStack, typeName, type, toolData);
}
@Override
public ShearsMat getType(final String type)
{
return getByEnumName(type);
}
@Override
public ShearsMat getType(final int type)
{
return getByID(type);
}
@Override
public ShearsMat increaseDurability()
{
return this.next.get();
}
@Override
public ShearsMat decreaseDurability()
{
return this.prev.get();
}
@Override
public ShearsMat setDurability(final int durability)
{
return this.getType(durability);
}
@Override
public ShearsMat[] types()
{
return shearsTypes();
}
/**
* Returns one of Shears sub-type based on sub-id.
*
* @param id sub-type id
*
* @return sub-type of Shears.
*/
public static ShearsMat getByID(final int id)
{
ShearsMat mat = byID.get((short) id);
if (mat == null)
{
mat = new ShearsMat(id);
if ((id > 0) && (id < SHEARS.getBaseDurability()))
{
ShearsMat.register(mat);
}
}
return mat;
}
/**
* Returns one of Shears sub-type based on durability.
*
* @param id durability of type.
*
* @return sub-type of Shears.
*/
public static ShearsMat getByDurability(final int id)
{
return getByID(id);
}
/**
* Returns one of Shears-type based on name (selected by diorite team).
* If item contains only one type, sub-name of it will be this same as name of material.<br>
* Returns null if name can't be parsed to int and it isn't "NEW" one.
*
* @param name name of sub-type
*
* @return sub-type of Shears.
*/
public static ShearsMat getByEnumName(final String name)
{
final ShearsMat mat = byName.get(name);
if (mat == null)
{
final Integer idType = DioriteMathUtils.asInt(name);
if (idType == null)
{
return null;
}
return getByID(idType);
}
return mat;
}
/**
* Register new sub-type, may replace existing sub-types.
* Should be used only if you know what are you doing, it will not create fully usable material.
*
* @param element sub-type to register
*/
public static void register(final ShearsMat element)
{
allItems.incrementAndGet();
byID.put((short) element.getType(), element);
byName.put(element.getTypeName(), element);
}
/**
* @return array that contains all sub-types of this item.
*/
public static ShearsMat[] shearsTypes()
{
return new ShearsMat[]{SHEARS};
}
static
{
ShearsMat.register(SHEARS);
}
}
| 31.205
| 174
| 0.657907
|
ee0eedda97e6fbceca905a4b8c9d06f2bfbe3fa5
| 5,223
|
/*
* 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.netbeans.modules.css.model.impl;
import org.netbeans.modules.css.lib.api.Node;
import org.netbeans.modules.css.model.api.Declarations;
import org.netbeans.modules.css.model.api.Element;
import org.netbeans.modules.css.model.api.Model;
import org.netbeans.modules.css.model.api.PlainElement;
import org.netbeans.modules.css.model.api.Rule;
import org.netbeans.modules.css.model.api.SelectorsGroup;
import org.netbeans.modules.web.common.api.LexerUtils;
/**
*
* @author marekfukala
*/
public class RuleI extends ModelElement implements Rule {
private SelectorsGroup selectorsGroup;
private Declarations declarations;
private final ModelElementListener elementListener = new ModelElementListener.Adapter() {
@Override
public void elementAdded(SelectorsGroup value) {
selectorsGroup = value;
}
@Override
public void elementAdded(Declarations value) {
declarations = value;
}
};
public RuleI(Model model) {
super(model);
//default elements
addTextElement("\n"); //not acc. to the grammar!
addEmptyElement(SelectorsGroup.class);
addTextElement(" {\n");
addEmptyElement(Declarations.class);
addTextElement("\n}\n");
}
public RuleI(Model model, Node node) {
super(model, node);
initChildrenElements();
}
@Override
protected String getCustomElementID() {
SelectorsGroup sGroup = getSelectorsGroup();
if(sGroup != null) {
return new StringBuilder()
.append(getModelClass().getSimpleName())
.append('-')
.append(model.getElementSource(sGroup).toString().hashCode())
.toString();
}
return null;
}
@Override
public boolean isValid() {
if(!super.isValid()) {
return false; //parsing error
} else {
//no parsing error in the node's scope, but some sub-nodes are missing
return getSelectorsGroup() != null && getDeclarations() != null;
}
}
@Override
public SelectorsGroup getSelectorsGroup() {
return selectorsGroup;
}
@Override
public void setSelectorsGroup(SelectorsGroup selectorsGroup) {
setElement(selectorsGroup);
}
@Override
public Declarations getDeclarations() {
return declarations;
}
@Override
public void setDeclarations(Declarations declarations) {
if(!isArtificialElement()) {
if(getDeclarations() == null) {
//XXX this code is really not nice and should be possibly be
//generified somehow
int rightCBIndex = -1;
int leftCBIndex = -1;
//the element has been created from a source code,
//but there was no content between the { } curly braces
//so there's no Declarations node inside
for(int i = 0; i < getElementsCount(); i++) {
Element e = getElementAt(i);
if(e instanceof PlainElement) {
PlainElement pe = (PlainElement)e;
if(LexerUtils.equals("{", pe.getContent(), true, true)) {
rightCBIndex = i;
}
if(LexerUtils.equals("}", pe.getContent(), true, true)) {
leftCBIndex = i;
}
}
}
if(rightCBIndex == (leftCBIndex - 1)) {
//nothing between the curly braces
} else {
//remove the plain elements from the { } content
for(int i = rightCBIndex + 1; i < leftCBIndex - 1; i++) {
removeElement(i);
}
}
//insert the declarations between the left curly brace
insertElement(leftCBIndex, declarations);
return ;
}
}
setElement(declarations);
}
@Override
protected ModelElementListener getElementListener() {
return elementListener;
}
@Override
protected Class getModelClass() {
return Rule.class;
}
}
| 33.056962
| 93
| 0.584147
|
dc21118b0e5463a714250d4b87229c27b70fdc8e
| 13,444
|
package io.smallrye.reactive.messaging.ft;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.faulttolerance.Asynchronous;
import org.eclipse.microprofile.faulttolerance.Retry;
import org.eclipse.microprofile.reactive.messaging.Incoming;
import org.eclipse.microprofile.reactive.messaging.Message;
import org.eclipse.microprofile.reactive.messaging.Outgoing;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.smallrye.faulttolerance.FaultToleranceExtension;
import io.smallrye.metrics.MetricRegistries;
import io.smallrye.mutiny.Multi;
import io.smallrye.reactive.messaging.WeldTestBaseWithoutTails;
public class RetryTest extends WeldTestBaseWithoutTails {
@BeforeEach
public void initFaultTolerance() {
addExtensionClass(FaultToleranceExtension.class);
addBeanClass(MetricRegistries.class);
}
@Test
public void testRetryOnPayloadProcessor() {
addBeanClass(MessageGenerator.class, FailingProcessorOfPayload.class);
initialize();
FailingProcessorOfPayload processor = get(FailingProcessorOfPayload.class);
await().until(() -> processor.list().size() == 10);
assertThat(processor.list()).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnPayloadProcessorCS() {
addBeanClass(MessageGenerator.class, FailingProcessorOfPayloadCS.class);
initialize();
FailingProcessorOfPayloadCS processor = get(FailingProcessorOfPayloadCS.class);
await().until(() -> processor.list().size() == 10);
assertThat(processor.list()).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnMessageProcessor() {
addBeanClass(MessageGenerator.class, FailingProcessorOfMessage.class);
initialize();
FailingProcessorOfMessage processor = get(FailingProcessorOfMessage.class);
await().until(() -> processor.list().size() == 10);
assertThat(processor.list()).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnMessageProcessorCS() {
addBeanClass(MessageGenerator.class, FailingProcessorOfMessageCS.class);
initialize();
FailingProcessorOfMessageCS processor = get(FailingProcessorOfMessageCS.class);
await().until(() -> processor.list().size() == 10);
assertThat(processor.list()).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnPayloadSubscriber() {
addBeanClass(MessageGenerator.class, FailingSubscriberOfPayload.class);
initialize();
FailingSubscriberOfPayload subscriber = get(FailingSubscriberOfPayload.class);
await().until(() -> subscriber.list().size() == 10);
assertThat(subscriber.list()).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnPayloadSubscriberCS() {
addBeanClass(MessageGenerator.class, FailingSubscriberOfPayloadCS.class);
initialize();
FailingSubscriberOfPayloadCS subscriber = get(FailingSubscriberOfPayloadCS.class);
await().until(() -> subscriber.list().size() == 10);
assertThat(subscriber.list()).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnMessageSubscriber() {
addBeanClass(MessageGenerator.class, FailingSubscriberOfMessage.class);
initialize();
FailingSubscriberOfMessage subscriber = get(FailingSubscriberOfMessage.class);
await().until(() -> subscriber.list().size() == 10);
assertThat(subscriber.list()).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testRetryOnMessageSubscriberCS() {
addBeanClass(MessageGenerator.class, FailingSubscriberOfMessageCS.class);
initialize();
FailingSubscriberOfMessageCS subscriber = get(FailingSubscriberOfMessageCS.class);
await().until(() -> subscriber.list().size() == 10);
assertThat(subscriber.list()).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 10);
assertThat(generator.acks()).isEqualTo(10);
assertThat(generator.nacks()).isEqualTo(0);
}
@Test
public void testImpossibleRecovery() {
addBeanClass(MessageGenerator.class, FailingForeverProcessorOfPayload.class);
initialize();
FailingForeverProcessorOfPayload processor = get(FailingForeverProcessorOfPayload.class);
await().untilAsserted(() -> assertThat(processor.list()).containsExactly(1, 2, 3, 5, 6, 7, 8, 9, 10));
MessageGenerator generator = get(MessageGenerator.class);
await().until(() -> generator.acks() == 9);
assertThat(generator.acks()).isEqualTo(9);
assertThat(generator.nacks()).isEqualTo(1);
}
@ApplicationScoped
public static class MessageGenerator {
int acks;
int nacks;
public int acks() {
return acks;
}
public int nacks() {
return nacks;
}
@Outgoing("numbers")
public Multi<Message<Integer>> numbers() {
return Multi.createFrom().range(0, 10)
.onItem().transform(i -> Message.of(i, () -> {
acks++;
return CompletableFuture.completedFuture(null);
}, t -> {
nacks++;
return CompletableFuture.completedFuture(null);
}));
}
}
@ApplicationScoped
public static class FailingProcessorOfPayload {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Outgoing("retry-sink")
@Retry // 3 is the default
public int process(int i) {
if (attempt < 3 && i == 3) {
attempt++;
throw new ArithmeticException("boom");
}
return i + 1;
}
@Incoming("retry-sink")
public void consume(int l) {
list.add(l);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingProcessorOfMessage {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Outgoing("retry-sink")
@Retry // 3 is the default
public Message<Integer> process(Message<Integer> i) {
if (attempt < 3 && i.getPayload() == 3) {
attempt++;
throw new ArithmeticException("boom");
}
return i.withPayload(i.getPayload() + 1);
}
@Incoming("retry-sink")
public void consume(int l) {
list.add(l);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingSubscriberOfPayload {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Retry // 3 is the default
public void consume(int i) {
if (attempt < 3 && i == 3) {
attempt++;
throw new ArithmeticException("boom");
}
list.add(i);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingSubscriberOfMessage {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Retry // 3 is the default
public CompletionStage<Void> consume(Message<Integer> i) {
if (attempt < 3 && i.getPayload() == 3) {
attempt++;
throw new ArithmeticException("boom");
}
list.add(i.getPayload());
return i.ack();
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingForeverProcessorOfPayload {
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Outgoing("retry-sink")
@Retry // 3 is the default
public int process(int i) {
if (i == 3) {
throw new ArithmeticException("boom");
}
return i + 1;
}
@Incoming("retry-sink")
public void consume(int l) {
list.add(l);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingProcessorOfPayloadCS {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Outgoing("retry-sink")
@Retry // 3 is the default
@Asynchronous
public CompletionStage<Integer> process(int i) {
return CompletableFuture.supplyAsync(() -> {
if (attempt < 3 && i == 3) {
attempt++;
throw new ArithmeticException("boom");
}
return i + 1;
});
}
@Incoming("retry-sink")
public void consume(int l) {
list.add(l);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingProcessorOfMessageCS {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Outgoing("retry-sink")
@Retry // 3 is the default
@Asynchronous
public CompletionStage<Message<Integer>> process(Message<Integer> i) {
return CompletableFuture.supplyAsync(() -> {
if (attempt < 3 && i.getPayload() == 3) {
attempt++;
throw new ArithmeticException("boom");
}
return i.withPayload(i.getPayload() + 1);
});
}
@Incoming("retry-sink")
public void consume(int l) {
list.add(l);
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingSubscriberOfPayloadCS {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Retry // 3 is the default
@Asynchronous
public CompletionStage<Void> consume(int i) {
return CompletableFuture.runAsync(() -> {
if (attempt < 3 && i == 3) {
attempt++;
throw new ArithmeticException("boom");
}
list.add(i);
});
}
public List<Integer> list() {
return list;
}
}
@ApplicationScoped
public static class FailingSubscriberOfMessageCS {
int attempt = 0;
List<Integer> list = new ArrayList<>();
@Incoming("numbers")
@Retry // 3 is the default
@Asynchronous
public CompletionStage<Void> consume(Message<Integer> i) {
return CompletableFuture.runAsync(() -> {
if (attempt < 3 && i.getPayload() == 3) {
attempt++;
throw new ArithmeticException("boom");
}
list.add(i.getPayload());
}).thenCompose(x -> i.ack());
}
public List<Integer> list() {
return list;
}
}
}
| 32.870416
| 110
| 0.58368
|
ecdafd61c28aae0ee96b648fb764a2412d3d3b78
| 3,929
|
package bac.peers;
import bac.settings.Settings;
import bac.peers.Peers;
import bac.helper.Helper;
import bac.api.APIServlet;
import bac.Bac;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Collection;
import org.json.simple.JSONObject;
public class Peer {
public int PeerID;
public int PeerState;
public int ConnectionTimestamp;
public String PeerAnnouncedAddress;
Peer(String PeerAnnouncedAddress) {
this.PeerAnnouncedAddress = PeerAnnouncedAddress;
}
public static Peer AddPeer(String announcedAddress) {
synchronized (Peers.peers) {
if ( announcedAddress.equals(Peers.MyAnnouncedAddress) ) {
return null;
}
Peer peer = Peers.peers.get(Helper.GetAnnouncementHost(announcedAddress));
if (peer == null) {
peer = new Peer(announcedAddress);
peer.PeerID = ++Peers.PeersCounter;
peer.PeerState = Peers.PEER_STATE_DISCONNECTED;
peer.ConnectionTimestamp = 0;
Peers.peers.put(Helper.GetAnnouncementHost(announcedAddress),peer);
}
return peer;
}
}
void RemovePeer() {
synchronized (Peers.peers) {
for (Map.Entry<String, Peer> PeerEntry : Peers.peers.entrySet()) {
if (PeerEntry.getValue() == this) {
Peers.peers.remove(PeerEntry.getKey());
break;
}
}
}
}
public static Peer GetRandomPeer( int PeerStateFilter ) {
synchronized (Peers.peers) {
Collection<Peer> PeersList = ((HashMap<String, Peer>)Peers.peers.clone()).values();
Iterator<Peer> FilteredPeers = PeersList.iterator();
while (FilteredPeers.hasNext()) {
Peer peer = FilteredPeers.next();
if ( peer.PeerState != PeerStateFilter ) {
FilteredPeers.remove();
}
}
if (PeersList.size() > 0) {
return (Peer)Helper.getRandomObject(PeersList);
} else return null;
}
}
public JSONObject SendJsonQueryToPeer(JSONObject request) {
APIServlet listenner = new APIServlet();
JSONObject response = listenner.SendJsonQuery(request);
if (response != null) {
// Helper.logMessage("Peer response: "+response.toString());
JSONObject Data = (JSONObject) response.get("Data");
if (Data != null) {
return Data;
}
}
PeerDisconnect();
return null;
}
void PeerConnect() {
try {
JSONObject request = new JSONObject();
request.put("requestType", "GetInfo");
request.put("serverURL", "http://"+PeerAnnouncedAddress+"/api");
request.put("AnnouncedAddress",Peers.MyAnnouncedAddress);
JSONObject response = SendJsonQueryToPeer(request);
if (response != null) {
String ConnectedAnnouncedAddress = (String) response.get("AnnouncedAddress");
if ( ConnectedAnnouncedAddress.length() > 0 ) {
PeerState = Peers.PEER_STATE_UNSETTLED;
ConnectionTimestamp = Helper.getEpochTimestamp();
Helper.logMessage("Peer connected.(UNSETTLED)"+ConnectedAnnouncedAddress);
} else {
Helper.logMessage("Bad or missing AnnouncedAddress."+response.toString());
}
} else {
// Helper.logMessage("Peer connection fail. "+request.toString());
}
} catch (Exception e) {
Helper.logMessage("Peer connection error.");
}
}
void PeerDisconnect() {
if ( PeerState == Peers.PEER_STATE_DISCONNECTED ) {
Helper.logMessage("Peer ("+PeerAnnouncedAddress+") offline.");
PeerState = Peers.PEER_STATE_OFFLINE;
} else {
Helper.logMessage("Peer ("+PeerAnnouncedAddress+") disconnected.");
PeerState = Peers.PEER_STATE_DISCONNECTED;
}
ConnectionTimestamp = 0;
}
}
| 30.457364
| 95
| 0.618478
|
f6e5c5767cb7d06d8531933e292782c2ab000f16
| 4,180
|
package com.lanking.uxb.service.session.api.impl;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.lanking.cloud.sdk.bean.Attrable;
import com.lanking.cloud.sdk.util.ArrayUtils;
import com.lanking.cloud.sdk.util.StringUtils;
/**
* @author <a href="mailto:sikai.wang@elanking.com">sikai.wang</a>
* @version V1.0.0,2014年11月19日
*
*/
public class AttrSession implements Attrable, Serializable, Cloneable {
private static final long serialVersionUID = 7118988252822405961L;
private JSONObject attr;
public AttrSession(JSONObject attr) {
this.attr = attr;
}
public AttrSession(Map<String, Object> map) {
this.attr = new JSONObject(map);
}
public AttrSession() {
attr = new JSONObject();
}
public JSONObject getAttr() {
return attr;
}
public void setAttr(JSONObject attr) {
this.attr = attr;
}
public void updateAttr(JSONObject attr) {
if (attr != null) {
if (this.attr == null) {
this.attr = attr;
} else {
for (String key : attr.keySet()) {
this.attr.put(key, attr.get(key));
}
}
}
}
@Override
public boolean hasAttr(String key) {
return attr.containsKey(key);
}
@Override
public String getAttr(String key) {
return attr.getString(key);
}
@Override
public String getAttr(String key, String defaultValue) {
String v = getAttr(key);
if (v == null) {
v = defaultValue;
}
return v;
}
@Override
public boolean getBoolAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? false : TypeUtils.castToBoolean(value);
}
@Override
public byte getByteAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0 : TypeUtils.castToByte(value);
}
@Override
public short getShortAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0 : TypeUtils.castToShort(value);
}
@Override
public int getIntAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0 : TypeUtils.castToInt(value);
}
@Override
public long getLongAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0L : TypeUtils.castToLong(value);
}
@Override
public float getFloatAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0F : TypeUtils.castToFloat(value);
}
@Override
public double getDoubleAttr(String key) {
String value = getAttr(key);
return StringUtils.isEmpty(value) ? 0D : TypeUtils.castToDouble(value);
}
@Override
public <T> T getObject(String key, Class<T> clazz) {
return attr.getObject(key, clazz);
}
@Override
public Collection<String> keys() {
return attr.keySet();
}
@Override
public Map<String, String> getAttrs(String... keys) {
return getAttrs(ArrayUtils.asList(keys));
}
@Override
public Map<String, String> getAttrs(Collection<String> keys) {
if (keys == null) {
keys = keys();
}
Map<String, String> map = new HashMap<String, String>(keys.size());
for (String key : keys) {
String value = getAttr(key);
if (value != null) {
map.put(key, value);
}
}
return Collections.unmodifiableMap(map);
}
@Override
public void setAttr(String key, Object value) {
attr.put(key, value);
}
@Override
public void setAttrs(Map<String, ?> map) {
for (Map.Entry<String, ?> entry : map.entrySet()) {
setAttr(entry.getKey(), entry.getValue());
}
}
@Override
public void removeAttr(String key) {
attr.remove(key);
}
@Override
public void removeAttrs(String... keys) {
removeAttrs(ArrayUtils.asList(keys));
}
@Override
public void removeAttrs(Collection<String> keys) {
for (String key : keys) {
attr.remove(key);
}
}
@Override
public void clearAttrs() {
removeAttrs(keys());
}
@Override
public AttrSession clone() {
AttrSession obj = null;
try {
obj = (AttrSession) super.clone();
JSONObject json = new JSONObject(getAttr());
obj.setAttr(json);
} catch (CloneNotSupportedException ignored) {
}
return obj;
}
}
| 21.435897
| 77
| 0.694498
|
5743d4c4ee528267722b9703b291d31bbe5e3062
| 10,619
|
package org.yzh.web.model.entity;
import java.time.LocalDateTime;
public class DeviceStatusDO {
private String deviceId;
private Boolean online;
private Integer agencyId;
private String plateNo;
private LocalDateTime deviceTime;
private String mobileNo;
private Integer vehicleId;
private Integer warnBit;
private Integer statusBit;
private Integer longitude;
private Integer latitude;
private Integer altitude;
private Integer speed;
private Integer direction;
private String address;
private LocalDateTime updatedAt;
private LocalDateTime createdAt;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public Boolean getOnline() {
return online;
}
public void setOnline(Boolean online) {
this.online = online;
}
public Integer getAgencyId() {
return agencyId;
}
public void setAgencyId(Integer agencyId) {
this.agencyId = agencyId;
}
public String getPlateNo() {
return plateNo;
}
public void setPlateNo(String plateNo) {
this.plateNo = plateNo;
}
public LocalDateTime getDeviceTime() {
return deviceTime;
}
public void setDeviceTime(LocalDateTime deviceTime) {
this.deviceTime = deviceTime;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public Integer getVehicleId() {
return vehicleId;
}
public void setVehicleId(Integer vehicleId) {
this.vehicleId = vehicleId;
}
public Integer getWarnBit() {
return warnBit;
}
public void setWarnBit(Integer warnBit) {
this.warnBit = warnBit;
}
public Integer getStatusBit() {
return statusBit;
}
public void setStatusBit(Integer statusBit) {
this.statusBit = statusBit;
}
public Integer getLongitude() {
return longitude;
}
public void setLongitude(Integer longitude) {
this.longitude = longitude;
}
public Integer getLatitude() {
return latitude;
}
public void setLatitude(Integer latitude) {
this.latitude = latitude;
}
public Integer getAltitude() {
return altitude;
}
public void setAltitude(Integer altitude) {
this.altitude = altitude;
}
public Integer getSpeed() {
return speed;
}
public void setSpeed(Integer speed) {
this.speed = speed;
}
public Integer getDirection() {
return direction;
}
public void setDirection(Integer direction) {
this.direction = direction;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public DeviceStatusDO deviceId(String deviceId) {
this.deviceId = deviceId;
return this;
}
public DeviceStatusDO online(Boolean online) {
this.online = online;
return this;
}
public DeviceStatusDO agencyId(Integer agencyId) {
this.agencyId = agencyId;
return this;
}
public DeviceStatusDO plateNo(String plateNo) {
this.plateNo = plateNo;
return this;
}
public DeviceStatusDO deviceTime(LocalDateTime deviceTime) {
this.deviceTime = deviceTime;
return this;
}
public DeviceStatusDO mobileNo(String mobileNo) {
this.mobileNo = mobileNo;
return this;
}
public DeviceStatusDO vehicleId(Integer vehicleId) {
this.vehicleId = vehicleId;
return this;
}
public DeviceStatusDO warnBit(Integer warnBit) {
this.warnBit = warnBit;
return this;
}
public DeviceStatusDO statusBit(Integer statusBit) {
this.statusBit = statusBit;
return this;
}
public DeviceStatusDO longitude(Integer longitude) {
this.longitude = longitude;
return this;
}
public DeviceStatusDO latitude(Integer latitude) {
this.latitude = latitude;
return this;
}
public DeviceStatusDO altitude(Integer altitude) {
this.altitude = altitude;
return this;
}
public DeviceStatusDO speed(Integer speed) {
this.speed = speed;
return this;
}
public DeviceStatusDO direction(Integer direction) {
this.direction = direction;
return this;
}
public DeviceStatusDO address(String address) {
this.address = address;
return this;
}
public DeviceStatusDO updatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public DeviceStatusDO createdAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
DeviceStatusDO other = (DeviceStatusDO) that;
return (this.getDeviceId() == null ? other.getDeviceId() == null : this.getDeviceId().equals(other.getDeviceId()))
&& (this.getOnline() == null ? other.getOnline() == null : this.getOnline().equals(other.getOnline()))
&& (this.getAgencyId() == null ? other.getAgencyId() == null : this.getAgencyId().equals(other.getAgencyId()))
&& (this.getPlateNo() == null ? other.getPlateNo() == null : this.getPlateNo().equals(other.getPlateNo()))
&& (this.getDeviceTime() == null ? other.getDeviceTime() == null : this.getDeviceTime().equals(other.getDeviceTime()))
&& (this.getMobileNo() == null ? other.getMobileNo() == null : this.getMobileNo().equals(other.getMobileNo()))
&& (this.getVehicleId() == null ? other.getVehicleId() == null : this.getVehicleId().equals(other.getVehicleId()))
&& (this.getWarnBit() == null ? other.getWarnBit() == null : this.getWarnBit().equals(other.getWarnBit()))
&& (this.getStatusBit() == null ? other.getStatusBit() == null : this.getStatusBit().equals(other.getStatusBit()))
&& (this.getLongitude() == null ? other.getLongitude() == null : this.getLongitude().equals(other.getLongitude()))
&& (this.getLatitude() == null ? other.getLatitude() == null : this.getLatitude().equals(other.getLatitude()))
&& (this.getAltitude() == null ? other.getAltitude() == null : this.getAltitude().equals(other.getAltitude()))
&& (this.getSpeed() == null ? other.getSpeed() == null : this.getSpeed().equals(other.getSpeed()))
&& (this.getDirection() == null ? other.getDirection() == null : this.getDirection().equals(other.getDirection()))
&& (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))
&& (this.getUpdatedAt() == null ? other.getUpdatedAt() == null : this.getUpdatedAt().equals(other.getUpdatedAt()))
&& (this.getCreatedAt() == null ? other.getCreatedAt() == null : this.getCreatedAt().equals(other.getCreatedAt()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getDeviceId() == null) ? 0 : getDeviceId().hashCode());
result = prime * result + ((getOnline() == null) ? 0 : getOnline().hashCode());
result = prime * result + ((getAgencyId() == null) ? 0 : getAgencyId().hashCode());
result = prime * result + ((getPlateNo() == null) ? 0 : getPlateNo().hashCode());
result = prime * result + ((getDeviceTime() == null) ? 0 : getDeviceTime().hashCode());
result = prime * result + ((getMobileNo() == null) ? 0 : getMobileNo().hashCode());
result = prime * result + ((getVehicleId() == null) ? 0 : getVehicleId().hashCode());
result = prime * result + ((getWarnBit() == null) ? 0 : getWarnBit().hashCode());
result = prime * result + ((getStatusBit() == null) ? 0 : getStatusBit().hashCode());
result = prime * result + ((getLongitude() == null) ? 0 : getLongitude().hashCode());
result = prime * result + ((getLatitude() == null) ? 0 : getLatitude().hashCode());
result = prime * result + ((getAltitude() == null) ? 0 : getAltitude().hashCode());
result = prime * result + ((getSpeed() == null) ? 0 : getSpeed().hashCode());
result = prime * result + ((getDirection() == null) ? 0 : getDirection().hashCode());
result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());
result = prime * result + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode());
result = prime * result + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", deviceId=").append(deviceId);
sb.append(", online=").append(online);
sb.append(", agencyId=").append(agencyId);
sb.append(", plateNo=").append(plateNo);
sb.append(", deviceTime=").append(deviceTime);
sb.append(", mobileNo=").append(mobileNo);
sb.append(", vehicleId=").append(vehicleId);
sb.append(", warnBit=").append(warnBit);
sb.append(", statusBit=").append(statusBit);
sb.append(", longitude=").append(longitude);
sb.append(", latitude=").append(latitude);
sb.append(", altitude=").append(altitude);
sb.append(", speed=").append(speed);
sb.append(", direction=").append(direction);
sb.append(", address=").append(address);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", createdAt=").append(createdAt);
sb.append("]");
return sb.toString();
}
}
| 32.474006
| 134
| 0.602317
|
912fc8bde4d469a9b1103c3f5716a67f80122456
| 1,444
|
package com.millennialmedia.intellibot.psi.util;
import org.jetbrains.annotations.NotNull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternBuilder {
private static final Pattern PATTERN = Pattern.compile("(.*?)(\\$\\{.*?\\})(.*)");
private static final String ANY = ".*?";
private static final String DOT = ".";
@NotNull
static private String parseFunction(@NotNull String keyword) {
Matcher matcher = PATTERN.matcher(keyword);
String result = "";
if (matcher.matches()) {
String start = matcher.group(1);
String end = parseFunction(matcher.group(3));
if (start.length() > 0) {
result = Pattern.quote(start);
}
result += ANY;
if (end.length() > 0) {
result += end;
}
} else {
result = !keyword.isEmpty() ? Pattern.quote(keyword) : keyword;
}
return result;
}
@NotNull
static private String parseNamespace(@NotNull String namespace) {
String result = "";
if (!namespace.isEmpty()) {
result = "(" + Pattern.quote(namespace + DOT) + ")?";
}
return result;
}
@NotNull
static public String parseNamespaceKeyword(@NotNull String namespace, @NotNull String keyword) {
return parseNamespace(namespace) + parseFunction(keyword);
}
}
| 29.469388
| 100
| 0.578947
|
bf43dd7a842c677dced45006ef69f72ddd6f196b
| 1,372
|
package com.wxmp.racingcms.mapper;
import com.wxmp.racingapi.vo.dto.SysUserRelDTO;
import com.wxmp.racingcms.domain.RUser;
import com.wxmp.racingcms.vo.view.RUserMatchView;
import com.wxmp.racingcms.vo.view.RUserView;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RUserMapper {
/**
* 插入记录
* @param record
* @return
*/
int insert(RUser record);
/**
* 查询全部记录
* @return
*/
List<RUser> selectAll();
/**
* 分页查询
* @param filter
* @return
*/
List<RUser> listForPage(@Param("filter") RUser filter);
/**
* 分页查询
* @param filter
* @return
*/
List<RUserView> viewListForPage(@Param("filter") RUser filter);
/**
* 更新记录
* @param user
* @return
*/
int update(RUser user);
/**
* 冻结用户,不进行物理删除
* @param uuid
* @return
*/
int deleteUser(@Param("uuid")String uuid);
/**
* 主键查询
* @param uuid
* @return
*/
RUser getById(@Param("uuid") String uuid);
/**
* 分页查询
* @param filter
* @return
*/
List<RUserMatchView> listUserMatchLogs(@Param("filter") RUser filter);
/**
* 查询用户的关联关系
* @param sysUserUuids
* @return
*/
List<SysUserRelDTO> selectRelUsers(@Param("sysUserUuids")List<String> sysUserUuids);
}
| 18.540541
| 88
| 0.577259
|
e691abf1330a4118c01b296b59e7260ed3aea400
| 1,693
|
//给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
//
// 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
//
//
//
// 示例:
//
// 输入:"23"
//输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
//
//
// 说明:
//尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
// Related Topics 深度优先搜索 递归 字符串 回溯算法
// 👍 1065 👎 0
package me.bob.leetcode.editor.cn;
import java.util.ArrayList;
import java.util.List;
/**
* 17 电话号码的字母组合
* 2021-01-11 15:28:26
* 思路:回溯
*/
public class LetterCombinationsOfAPhoneNumber {
public static void main(String[] args) {
Solution solution = new LetterCombinationsOfAPhoneNumber().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return res;
}
String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
helper(digits, mapping, 0, res, "");
return res;
}
void helper(String digits, String[] mapping, int depth, List<String> res, String curr) {
if (depth == digits.length()) {
res.add(curr);
return;
}
// 获取digits下标,拿到对应字符串
int index = Character.getNumericValue(digits.charAt(depth));
String s = mapping[index];
for (int i = 0; i < s.length(); i++) {
helper(digits, mapping, depth + 1, res, curr + s.charAt(i));
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 26.453125
| 112
| 0.552274
|
2b9607029873d01d8e15d273502dabd8d2c74abb
| 8,936
|
package org.yawlfoundation.yawl.ui.view;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextAreaVariant;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MultiFileMemoryBuffer;
import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.yawlfoundation.yawl.engine.YSpecificationID;
import org.yawlfoundation.yawl.engine.interfce.SpecificationData;
import org.yawlfoundation.yawl.schema.YSchemaVersion;
import org.yawlfoundation.yawl.ui.service.EngineClient;
import org.yawlfoundation.yawl.ui.service.UploadResult;
import org.yawlfoundation.yawl.util.JDOMUtil;
import org.yawlfoundation.yawl.util.StringUtil;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @author Michael Adams
* @date 11/12/20
*/
public class UploadDialog extends Dialog {
private final EngineClient _client;
private final List<SpecificationData> _loadedSpecs;
private final TextArea _msgArea = new TextArea("Messages");
public UploadDialog(EngineClient client, List<SpecificationData> loadedSpecs,
ComponentEventListener<ClickEvent<Button>> listener) {
super();
_client = client;
_loadedSpecs = loadedSpecs;
setCloseOnOutsideClick(false);
setWidth("700px");
setHeight("515px");
add(getContent(listener));
}
private VerticalLayout getContent(ComponentEventListener<ClickEvent<Button>> listener) {
VerticalLayout layout = new VerticalLayout();
layout.add(new H3("Upload Specifications"));
layout.add(createUpload());
layout.add(createMsgArea());
layout.add(createButton(listener));
layout.setSizeFull();
return layout;
}
private Upload createUpload() {
MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
Upload upload = new Upload(buffer);
upload.setAcceptedFileTypes(".yawl", ".xml");
upload.setHeight("60%");
upload.setWidthFull();
upload.addSucceededListener(event -> {
String fileName = event.getFileName();
uploadSpecification(fileName, buffer.getInputStream(fileName));
});
return upload;
}
private TextArea createMsgArea() {
_msgArea.setReadOnly(true);
_msgArea.setHeight("30%");
_msgArea.addThemeVariants(TextAreaVariant.LUMO_SMALL);
_msgArea.setWidthFull();
return _msgArea;
}
private HorizontalLayout createButton(ComponentEventListener<ClickEvent<Button>> listener) {
HorizontalLayout layout = new HorizontalLayout();
Button b = new Button("Close", event -> {
close();
});
b.addClickListener(listener);
layout.add(b);
return layout;
}
private void uploadSpecification(String fileName, InputStream stream) {
try {
String fileContent = validateUpload(IOUtils.toString(stream,
StandardCharsets.UTF_8));
UploadResult result = _client.uploadSpecification(fileContent);
processResult(result, fileName);
}
catch (IOException ioe) {
appendMessage(formatMessage("ERROR", stripPath(fileName), unwrap(ioe.getMessage())));
}
}
private String validateUpload(String content) throws IOException {
int BOF = content.indexOf("<?xml");
int EOF = content.indexOf("</specificationSet>");
if (BOF != -1 && EOF != -1) {
String trimmedContent = content.substring(BOF, EOF + 19);
hasUniqueDescriptors(trimmedContent); // throws IOException
return trimmedContent;
}
return content;
}
private void hasUniqueDescriptors(String specxml) throws IOException {
if (StringUtil.isNullOrEmpty(specxml)) {
throw new IOException("Invalid specification file: null or empty contents.");
}
YSpecificationID specID = getDescriptors(specxml);
if (! specID.isValid()) {
throw new IOException("Invalid specification: missing identifier or incorrect version.");
}
for (SpecificationData spec : _loadedSpecs) {
if (spec.getID().equals(specID)) {
if (specID.getUri().equals(spec.getSpecURI())) {
throw new IOException("This specification is already loaded.");
}
else {
throw new IOException("A specification with the same id and " +
"version (but different name) is already loaded.");
}
}
else if (specID.isPreviousVersionOf(spec.getID())) {
if (specID.getUri().equals(spec.getSpecURI())) {
throw new IOException("A later version of this specification is " +
"already loaded.");
}
else {
throw new IOException("A later version of a specification with the " +
"same id (but different name) is already loaded.");
}
}
else if (specID.getUri().equals(spec.getSpecURI()) &&
(! specID.hasMatchingIdentifier(spec.getID()))) {
throw new IOException("A specification with the same name, but a different " +
"id, is already loaded. Please change the name and try again.");
}
}
}
private YSpecificationID getDescriptors(String specxml) throws IOException {
Document doc = JDOMUtil.stringToDocument(specxml);
if (doc != null) {
Element root = doc.getRootElement();
Namespace ns = root.getNamespace();
YSchemaVersion schemaVersion = YSchemaVersion.fromString(
root.getAttributeValue("version"));
Element specification = root.getChild("specification", ns);
if (specification != null) {
String uri = specification.getAttributeValue("uri");
String version = "0.1";
String uid = null;
if (! (schemaVersion == null || schemaVersion.isBetaVersion())) {
Element metadata = specification.getChild("metaData", ns);
version = metadata.getChildText("version", ns);
uid = metadata.getChildText("identifier", ns);
}
return new YSpecificationID(uid, version, uri);
}
else throw new IOException("Malformed specification: 'specification' node not found.");
}
else throw new IOException("Malformed specification: unable to parse.");
}
// removes the path part from an absolute filename
private String stripPath(String fileName) {
return stripPath(stripPath(fileName, '/'), '\\');
}
private String stripPath(String fileName, char slash) {
int index = fileName.lastIndexOf(slash);
if (index >= 0) fileName = fileName.substring(index + 1);
return fileName ;
}
private void processResult(UploadResult result, String fileName) {
fileName = stripPath(fileName);
for (String error : result.getErrors()) {
appendMessage(formatMessage("ERROR", fileName, error));
}
for (String warning : result.getWarnings()) {
appendMessage(formatMessage("WARNING", fileName, warning));
}
// add specids to loaded specs for consequent uniqueness checks
if (result.hasSpecIDs()) {
for (YSpecificationID specID : result.getSpecIDs()) {
_loadedSpecs.add(new SpecificationData(specID, null,
null, null, null));
}
appendMessage("SUCCESS (" + fileName + ").\n\n");
}
}
private String formatMessage(String label, String fileName, String msg) {
return String.format("%s (%s): %s.\n\n", label, fileName, msg);
}
private void appendMessage(String msg) {
String existing = _msgArea.getValue();
_msgArea.setValue(msg + existing);
}
private String unwrap(String s) {
if (s == null) return s;
while (s.trim().startsWith("<")) {
s = StringUtil.unwrap(s);
}
return s;
}
}
| 36.473469
| 101
| 0.621531
|
2baf4ae03caea04b12432dfb84265ac4c533e275
| 3,513
|
package com.vladmihalcea.book.hpjp.hibernate.concurrency;
import com.vladmihalcea.book.hpjp.util.AbstractTest;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.*;
/**
* CascadeLockTest - Test to check CascadeType.LOCK
*
* @author Vlad Mihalcea
*/
public class CascadeLockManyToOneTest extends AbstractTest {
@Override
protected Class<?>[] entities() {
return new Class<?>[]{
Post.class,
PostComment.class
};
}
@Before
public void init() {
super.init();
doInJPA(entityManager -> {
Post post = new Post();
post.setTitle("Hibernate Master Class");
entityManager.persist(post);
PostComment comment = new PostComment("Good post!");
comment.setId(1L);
comment.setPost(post);
entityManager.persist(comment);
});
}
@Test
public void testCascadeLockOnDetachedEntityUninitializedWithScope() {
LOGGER.info("Test lock cascade for detached entity with scope");
//Load the Post entity, which will become detached
PostComment comment = doInJPA(entityManager -> (PostComment) entityManager.find(PostComment.class, 1L));
doInJPA(entityManager -> {
LOGGER.info("Reattach and lock entity with associations not initialized");
entityManager.unwrap(Session.class)
.buildLockRequest(
new LockOptions(LockMode.PESSIMISTIC_WRITE))
.setScope(true)
.lock(comment);
LOGGER.info("Check entities are reattached");
});
}
@Entity(name = "Post")
@Table(name = "post")
public static class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String body;
@Version
private int version;
public Post() {}
public Post(Long id) {
this.id = id;
}
public Post(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public static class PostComment {
@Id
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@Cascade(CascadeType.LOCK)
private Post post;
private String review;
@Version
private int version;
public PostComment() {}
public PostComment(String review) {
this.review = review;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}
}
| 23.111842
| 112
| 0.558212
|
34e10c75cfbf668ca632d782ea49de1cf0d992c5
| 6,610
|
/*
* 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.04.07 at 01:56:59 PM PDT
//
package org.esipfed.eskg.structures;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Latitude_Resolution" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Longitude_Resolution" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Horizontal_Resolution_Range" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Vertical_Resolution" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Vertical_Resolution_Range" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Temporal_Resolution" minOccurs="0"/>
* <element ref="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}Temporal_Resolution_Range" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "latitudeResolution", "longitudeResolution", "horizontalResolutionRange", "verticalResolution", "verticalResolutionRange", "temporalResolution",
"temporalResolutionRange" })
@XmlRootElement(name = "Data_Resolution")
public class DataResolution {
@XmlElement(name = "Latitude_Resolution")
protected String latitudeResolution;
@XmlElement(name = "Longitude_Resolution")
protected String longitudeResolution;
@XmlElement(name = "Horizontal_Resolution_Range")
protected String horizontalResolutionRange;
@XmlElement(name = "Vertical_Resolution")
protected String verticalResolution;
@XmlElement(name = "Vertical_Resolution_Range")
protected String verticalResolutionRange;
@XmlElement(name = "Temporal_Resolution")
protected String temporalResolution;
@XmlElement(name = "Temporal_Resolution_Range")
protected String temporalResolutionRange;
/**
* Gets the value of the latitudeResolution property.
*
* @return possible object is {@link String }
*
*/
public String getLatitudeResolution() {
return latitudeResolution;
}
/**
* Sets the value of the latitudeResolution property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLatitudeResolution(String value) {
this.latitudeResolution = value;
}
/**
* Gets the value of the longitudeResolution property.
*
* @return possible object is {@link String }
*
*/
public String getLongitudeResolution() {
return longitudeResolution;
}
/**
* Sets the value of the longitudeResolution property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLongitudeResolution(String value) {
this.longitudeResolution = value;
}
/**
* Gets the value of the horizontalResolutionRange property.
*
* @return possible object is {@link String }
*
*/
public String getHorizontalResolutionRange() {
return horizontalResolutionRange;
}
/**
* Sets the value of the horizontalResolutionRange property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setHorizontalResolutionRange(String value) {
this.horizontalResolutionRange = value;
}
/**
* Gets the value of the verticalResolution property.
*
* @return possible object is {@link String }
*
*/
public String getVerticalResolution() {
return verticalResolution;
}
/**
* Sets the value of the verticalResolution property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setVerticalResolution(String value) {
this.verticalResolution = value;
}
/**
* Gets the value of the verticalResolutionRange property.
*
* @return possible object is {@link String }
*
*/
public String getVerticalResolutionRange() {
return verticalResolutionRange;
}
/**
* Sets the value of the verticalResolutionRange property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setVerticalResolutionRange(String value) {
this.verticalResolutionRange = value;
}
/**
* Gets the value of the temporalResolution property.
*
* @return possible object is {@link String }
*
*/
public String getTemporalResolution() {
return temporalResolution;
}
/**
* Sets the value of the temporalResolution property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTemporalResolution(String value) {
this.temporalResolution = value;
}
/**
* Gets the value of the temporalResolutionRange property.
*
* @return possible object is {@link String }
*
*/
public String getTemporalResolutionRange() {
return temporalResolutionRange;
}
/**
* Sets the value of the temporalResolutionRange property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTemporalResolutionRange(String value) {
this.temporalResolutionRange = value;
}
}
| 29.247788
| 178
| 0.684266
|
264daf25fcc3521a1020d1f906e1fd800f36324d
| 4,149
|
/*
* USE - UML based specification environment
* Copyright (C) 1999-2010 Mark Richters, University of Bremen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// $Id: MAttributeAssignmentStatement.java 3330 2012-05-09 15:07:22Z green $
package org.tzi.use.uml.sys.soil;
import org.tzi.use.uml.mm.MAttribute;
import org.tzi.use.uml.ocl.expr.Expression;
import org.tzi.use.uml.ocl.expr.ExpressionWithValue;
import org.tzi.use.uml.ocl.value.Value;
import org.tzi.use.uml.sys.MObject;
import org.tzi.use.uml.sys.MSystemException;
import org.tzi.use.uml.sys.StatementEvaluationResult;
import org.tzi.use.util.soil.exceptions.EvaluationFailedException;
/**
* TODO
*
*/
public class MAttributeAssignmentStatement extends MStatement {
/** TODO */
private Expression fObject;
/** TODO */
private MAttribute fAttribute;
/** TODO */
private MRValue fRValue;
/**
* TODO
*
* @param object
* @param attribute
* @param value
*/
public MAttributeAssignmentStatement(Expression object, MAttribute attribute, MRValue rValue) {
fObject = object;
fAttribute = attribute;
fRValue = rValue;
}
/**
* TODO
*
* @param object
* @param attribute
* @param value
*/
public MAttributeAssignmentStatement(Expression object, MAttribute attribute, Expression value) {
this(object, attribute, new MRValueExpression(value));
}
/**
* TODO
*
* @param object
* @param attribute
* @param value
*/
public MAttributeAssignmentStatement(Expression object, MAttribute attribute, Value value) {
this(object, attribute, new MRValueExpression(value));
}
/**
* TODO
*
* @param object
* @param attribute
* @param value
*/
public MAttributeAssignmentStatement(MObject object, MAttribute attribute, Expression value) {
this(new ExpressionWithValue(object.value()), attribute, value);
}
/**
* TODO
*
* @param object
* @param attribute
* @param value
*/
public MAttributeAssignmentStatement(MObject object, MAttribute attribute, Value value) {
this(new ExpressionWithValue(object.value()), attribute, new ExpressionWithValue(value));
}
/**
* TODO
*
* @return
*/
public Expression getObject() {
return fObject;
}
/**
* TODO
*
* @return
*/
public MAttribute getAttribute() {
return fAttribute;
}
/**
* TODO
*
* @return
*/
public MRValue getRValue() {
return fRValue;
}
@Override
public void execute(SoilEvaluationContext context, StatementEvaluationResult result)
throws EvaluationFailedException {
// get the actual object
MObject object = EvalUtil.evaluateObjectExpression(this, context, result, fObject);
// get the new value
Value newValue = EvalUtil.evaluateRValue(this, context, result, fRValue, false);
try {
context.getSystem().assignAttribute(result, object, fAttribute, newValue);
} catch (MSystemException e) {
throw new EvaluationFailedException(this, e.getMessage());
}
}
@Override
protected String shellCommand() {
return fObject + "." + fAttribute.name() + " := " + fRValue;
}
@Override
public String toString() {
return shellCommand();
}
}
| 25.453988
| 101
| 0.646662
|
b3953495689ba27903a52f63ab684c01de95580a
| 3,442
|
package io.github.aquerr.eaglefactions.common.commands;
import io.github.aquerr.eaglefactions.api.EagleFactions;
import io.github.aquerr.eaglefactions.api.entities.Faction;
import io.github.aquerr.eaglefactions.api.entities.FactionMemberType;
import io.github.aquerr.eaglefactions.common.PluginInfo;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import java.util.Optional;
public abstract class AbstractCommand implements CommandExecutor
{
private EagleFactions plugin;
public AbstractCommand(final EagleFactions plugin)
{
this.plugin = plugin;
}
public EagleFactions getPlugin()
{
return plugin;
}
@Override
public abstract CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException;
// @Override
// public CommandResult execute(final CommandSource source, final CommandContext context) throws CommandException
// {
// if (!(source instanceof Player))
// return CommandResult.success();
//
// final Player player = (Player)source;
// final Optional<Faction> optionalFaction = this.plugin.getFactionLogic().getFactionByPlayerUUID(player.getUniqueId());
// if (!optionalFaction.isPresent())
// throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.DARK_RED, "You don't have access to use this command!"));
//
// final Faction faction = optionalFaction.get();
// final FactionMemberType playerMemberType = faction.getPlayerMemberType(player.getUniqueId());
//
// //Check if player has access for this command.
// final Class<? extends AbstractCommand> clazz = this.getClass();
// final RequiredRank annotation = clazz.getAnnotation(RequiredRank.class);
// if (annotation != null)
// {
// if (canUseCommand(annotation.rank(), playerMemberType))
// return CommandResult.success();
// else
// {
// throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.DARK_RED, "You don't have access to use this command!"));
// }
// }
//
// return CommandResult.success();
// }
// private boolean canUseCommand(final FactionMemberType requiredRank, final FactionMemberType playerRank)
// {
// switch (requiredRank)
// {
// case LEADER:
// return playerRank == FactionMemberType.LEADER;
// case OFFICER:
// return playerRank == FactionMemberType.LEADER || playerRank == FactionMemberType.OFFICER;
// case MEMBER:
// return playerRank == FactionMemberType.LEADER || playerRank == FactionMemberType.OFFICER || playerRank == FactionMemberType.MEMBER;
// case RECRUIT:
// return playerRank == FactionMemberType.LEADER || playerRank == FactionMemberType.OFFICER || playerRank == FactionMemberType.MEMBER || playerRank == FactionMemberType.RECRUIT;
// default:
// return false;
// }
// }
}
| 41.97561
| 192
| 0.689425
|
fbefd90793d02bf731416c7f861874e2fdeb1a90
| 2,784
|
package com.lightbox.jmkv.queue;
import java.util.NoSuchElementException;
import java.util.stream.IntStream;
public final class StaticHeap {
/**
* TODO: move to test
*/
public static void main(String[] args) {
final StaticHeap staticHeap = new StaticHeap(12);
IntStream.of(
15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1
).forEach(staticHeap::add);
while (!staticHeap.empty()) {
System.out.println(staticHeap.pool());
}
}
private final int[] elements;
private int size;
public StaticHeap(final int size) {
this.elements = new int[size];
this.size = 0;
}
boolean empty() {
return this.size == 0;
}
int add(final int number) {
this.replace(this.size++, number);
return number;
}
int pool() {
if (this.size == 0) {
throw new NoSuchElementException("Heap is empty");
}
final int max = this.elements[0];
this.elements[0] = this.elements[--this.size];
this.maxHeapify(0);
return max;
}
private void replace(int position, final int value) {
this.elements[position] = value;
while (position > 1 && this.elements[this.parent(position)] < this.elements[position]) {
final int parentPosition = this.parent(position);
final int temp = this.elements[position];
this.elements[position] = this.elements[parentPosition];
this.elements[parentPosition] = temp;
position = parentPosition;
}
}
private void maxHeapify(final int currentPosition) {
final int left = this.left(currentPosition);
final int right = this.right(currentPosition);
final int largestPosition;
if (left < this.size && this.elements[left] > this.elements[currentPosition] && this.elements[left] > this.elements[right]) {
largestPosition = left;
} else if (right < this.size && this.elements[right] > this.elements[currentPosition] && this.elements[right] > this.elements[left]) {
largestPosition = right;
} else {
largestPosition = currentPosition;
}
if (largestPosition != currentPosition) {
final int temp = this.elements[currentPosition];
this.elements[currentPosition] = this.elements[largestPosition];
this.elements[largestPosition] = temp;
this.maxHeapify(largestPosition);
}
}
private int parent(final int position) {
return (position - 1) / 2;
}
private int left(final int position) {
return (position * 2) + 1;
}
private int right(final int position) {
return (position * 2) + 2;
}
}
| 30.26087
| 142
| 0.590158
|
cfcd54ce18a02bd710111356562d1700619fceaf
| 1,294
|
/**
* Copyright (C) 2011 Xavier Jodoin (xavier@jodoin.me)
*
* 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.
*
* @author xjodoin
* @version $Id: $Id
*/
package org.torpedoquery.jpa.internal.utils;
import java.beans.Introspector;
public final class FieldUtils {
private FieldUtils() {
}
/**
* <p>getFieldName.</p>
*
* @param method a {@link org.torpedoquery.jpa.internal.utils.SerializableMethod} object.
* @return a {@link java.lang.String} object.
*/
public static String getFieldName(SerializableMethod method) {
String name = method.getName();
if(name.startsWith("get"))
{
name = name.substring(3);
}
else if(name.startsWith("is"))
{
name = name.substring(2);
}
name = Introspector.decapitalize(name);
return name;
}
}
| 24.884615
| 90
| 0.695518
|
ee69be8cfce26b0044e3646c83095919d65c06cd
| 781
|
package com.github.ElfenLiedGH.charting.listener;
import com.github.ElfenLiedGH.charting.data.Entry;
import com.github.ElfenLiedGH.charting.highlight.Highlight;
/**
* Listener for callbacks when selecting values inside the chart by
* touch-gesture.
*
* @author Philipp Jahoda
*/
public interface OnChartValueSelectedListener {
/**
* Called when a value has been selected inside the chart.
*
* @param e The selected Entry
* @param h The corresponding highlight object that contains information
* about the highlighted position such as dataSetIndex, ...
*/
void onValueSelected(Entry e, Highlight h);
/**
* Called when nothing has been selected or an "un-select" has been made.
*/
void onNothingSelected();
}
| 27.892857
| 77
| 0.704225
|
582dc202bbed55409008bdaf610dea166cd42fd8
| 392
|
package edu.bu.met.cs665.builder;
import edu.bu.met.cs665.resource.Person;
import java.util.List;
/**
* Specifies all operations required to build a Movie.
* MET CS 665 Design Patterns - Class Project
* @author Nikki Tebaldi
* @since 2020-07-31
*/
public interface MovieBuilder extends ResourceBuilder {
void setCast(List<Person> castList);
void setRating(String rating);
}
| 21.777778
| 55
| 0.737245
|
27adaaad9d5ea5c9b03131a95479d0a9114ce6ab
| 386
|
package com.prashanth.imageapp.model;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Assets {
@SerializedName("huge_thumb")
private HugeThumb hugeThumb;
@Override
public String toString() {
return "Assets{" +
"hugeThumb=" + hugeThumb +
'}';
}
}
| 18.380952
| 50
| 0.642487
|
14622af8503d6cbdda86bb5fcad832fc610c4c5b
| 1,718
|
package org.pipecraft.infra.storage.google_cs;
import com.google.cloud.storage.StorageException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A simple {@link InputStream} wrapper, that converts {@link StorageException}s to IOExceptions, as expected.
*
* @author Eyal Schneider
*/
public class GSInputStream extends FilterInputStream {
/**
* Package protected constructor
*
* @param in The wrapped input stream. Any {@link StorageException} originated from this stream are converted into legitimate {@link IOException}.
*/
GSInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
try {
return super.read();
} catch (StorageException e) {
throw new IOException(e);
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
try {
return super.read(b, off, len);
} catch (StorageException e) {
throw new IOException(e);
}
}
@Override
public long skip(long n) throws IOException {
try {
return super.skip(n);
} catch (StorageException e) {
throw new IOException(e);
}
}
@Override
public int available() throws IOException {
try {
return super.available();
} catch (StorageException e) {
throw new IOException(e);
}
}
@Override
public void close() throws IOException {
try {
super.close();
} catch (StorageException e) {
throw new IOException(e);
}
}
@Override
public synchronized void reset() throws IOException {
try {
super.reset();
} catch (StorageException e) {
throw new IOException(e);
}
}
}
| 22.311688
| 148
| 0.653085
|
7fe5a8670cd88c2347a0128632363aef662596b7
| 5,498
|
/*
* TopStack (c) Copyright 2012-2013 Transcend Computing, 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.msi.tough.model.monitor;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.Session;
import org.hibernate.annotations.Index;
import com.amazonaws.util.DateUtils;
/**
* A measure is an observed value with a name, a set of dimensions, a namespace,
* a unit, and a timestamp. Input to CloudWatch. The raw data that's monitored.
* A window of times worth of Measures are aggregated into a Metric. - unique
* name - 1+ dimensions - timestamp - a unit (value) - a namespace / the service
* recorded
*
* @author heathm
*
*/
@Entity
@Table(name = "measures")
@org.hibernate.annotations.Table(appliesTo = "measures", indexes = { @Index(name = "measure_idx", columnNames = {
"timestmp", "name" }) })
public class MeasureBean {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "timestmp")
@Temporal(TemporalType.TIMESTAMP)
private Date timestamp; // ISO 8601 format possibly represent this another
// way internally in the future that's more
// convenient for calculation.
@Column(name = "name")
private String name;
@Column(name = "namespace")
private String namespace; // identifies the service that this is recorded
// from (eg. EC2/AWS)
@Column(name = "unit")
private String unit; // Possibly make this an enum of Seconds, Percent,
// Bytes, Bits, Count, Bytes, Bits/Second,
// Count/Second, and None.
@Column(name = "value")
private Double value;
// dimensions
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "measure_dimension", joinColumns = { @JoinColumn(name = "measure_id") }, inverseJoinColumns = { @JoinColumn(name = "dimension_id") })
private Set<DimensionBean> dimensions;
public MeasureBean() {
}
//
// public MeasureBean(final String instanceId, final String name,
// final String namespace, final String unit, final String value,
// final long millis) {
// this.instanceId = instanceId;
// this.name = name;
// this.namespace = namespace;
// // dimensions.addAll(dimensions);
// this.unit = unit;
// this.value = value;
// milliseconds = millis;
// final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// cal.setTimeInMillis(millis);
// /*
// * SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// * // try { // timestamp = df.parse(new
// * DateUtils().formatIso8601Date(cal.getTime())); // } catch
// * (ParseException e) {
// * e.printStackTrace(); }
// */
// // cal.add(Calendar.MILLISECOND,
// // cal.getTimeZone().getOffset(cal.getTime().getTime())*-1);
// timestamp = cal.getTime();
// }
public Set<DimensionBean> getDimensions() {
return dimensions;
}
public long getId() {
return id;
}
public String getISO8601Timestamp() {
return new DateUtils().formatIso8601Date(timestamp);
// return DateUtils.getISO8601Date(timestamp);
}
public String getName() {
return name;
}
public String getNamespace() {
return namespace;
}
public Date getTimestamp() {
return timestamp;
}
public String getUnit() {
return unit;
}
public Double getValue() {
return value;
}
public void save(final Session session) {
// dimensions.save(session);
session.saveOrUpdate(this);
}
public void setDimensions(final Set<DimensionBean> dimensions) {
this.dimensions = dimensions;
}
public void setId(final long id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
public void setNamespace(final String namespace) {
this.namespace = namespace;
}
public void setTimestamp(final Date timestamp) {
this.timestamp = timestamp;
}
public void setUnit(final String unit) {
this.unit = unit;
}
public void setValue(final Double value) {
this.value = value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("Timestamp: " + timestamp + ", ");
sb.append("Name: " + name + ", ");
sb.append("Namespace: " + namespace + ", ");
sb.append("Unit: " + unit + ", ");
sb.append("Value: " + value + ", ");
final String dims = "";
// if (dimensions != null && dimensions.getDimensions() != null) {
// for (final DimensionBean dim : dimensions.getDimensions()) {
// dims += dim.getValue() + ":";
// }
// }
sb.append("Dimensions: " + dims + ", ");
sb.append("}");
return sb.toString();
}
}
| 27.49
| 152
| 0.696071
|
ac864e55069ae87492550e53e064d18f7db766af
| 7,505
|
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jserver.Config;
/**
* extension loader for l2j
* @author galun
* @version $Id: DynamicExtension.java,v 1.3 2006/05/14 17:19:39 galun Exp $
*/
public class DynamicExtension
{
private static Logger _log = Logger.getLogger(DynamicExtension.class.getCanonicalName());
private JarClassLoader _classLoader;
private Properties _prop;
private ConcurrentHashMap<String, Object> _loadedExtensions;
private ConcurrentHashMap<String, ExtensionFunction> _getters;
private ConcurrentHashMap<String, ExtensionFunction> _setters;
/**
* create an instance of DynamicExtension
* this will be done by GameServer according to the altsettings.properties
*
*/
private DynamicExtension()
{
_getters = new ConcurrentHashMap<String, ExtensionFunction>();
_setters = new ConcurrentHashMap<String, ExtensionFunction>();
initExtensions();
}
/**
* get the singleton of DynamicInstance
* @return the singleton instance
*/
public static DynamicExtension getInstance()
{
return SingletonHolder._instance;
}
/**
* get an extension object by class name
* @param className he class name as defined in the extension properties
* @return the object or null if not found
*/
public Object getExtension(String className)
{
return _loadedExtensions.get(className);
}
/**
* initialize all configured extensions
*
*/
public String initExtensions()
{
_prop = new Properties();
String res = "";
_loadedExtensions = new ConcurrentHashMap<String, Object>();
try
{
_prop.load(new FileInputStream(Config.EXTENSIONS_CONFIG_FILE));
}
catch (FileNotFoundException ex)
{
_log.info(ex.getMessage() + ": no extensions to load");
}
catch (Exception ex)
{
_log.log(Level.WARNING, "could not load properties", ex);
}
_classLoader = new JarClassLoader();
for (Object o : _prop.keySet())
{
String k = (String) o;
if (k.endsWith("Class"))
{
res += initExtension(_prop.getProperty(k)) + "\n";
}
}
return res;
}
/**
* init a named extension
* @param name the class name and optionally a jar file name delimited with a '@' if the jar file is not
* in the class path
*/
public String initExtension(String name)
{
String className = name;
String[] p = name.split("@");
String res = name + " loaded";
if (p.length > 1)
{
_classLoader.addJarFile(p[1]);
className = p[0];
}
if (_loadedExtensions.containsKey(className))
return "already loaded";
try
{
Class<?> extension = Class.forName(className, true, _classLoader);
Object obj = extension.newInstance();
extension.getMethod("init", new Class[0]).invoke(obj, new Object[0]);
_log.info("Extension " + className + " loaded.");
_loadedExtensions.put(className, obj);
}
catch (Exception ex)
{
_log.log(Level.WARNING, name, ex);
res = ex.toString();
}
return res;
}
/**
* create a new class loader which resets the cache (jar files and loaded classes)
* on next class loading request it will read the jar again
*/
protected void clearCache()
{
_classLoader = new JarClassLoader();
}
/**
* call unloadExtension() for all known extensions
*
*/
public String unloadExtensions()
{
String res = "";
for (String e : _loadedExtensions.keySet())
res += unloadExtension(e) + "\n";
return res;
}
/**
* get all loaded extensions
* @return a String array with the class names
*/
public String[] getExtensions()
{
String[] l = new String[_loadedExtensions.size()];
_loadedExtensions.keySet().toArray(l);
return l;
}
/**
* unload a named extension
* @param name the class name and optionally a jar file name delimited with a '@'
*/
public String unloadExtension(String name)
{
String className = name;
String[] p = name.split("@");
if (p.length > 1)
{
_classLoader.addJarFile(p[1]);
className = p[0];
}
String res = className + " unloaded";
try
{
Object obj = _loadedExtensions.get(className);
Class<?> extension = obj.getClass();
_loadedExtensions.remove(className);
extension.getMethod("unload", new Class[0]).invoke(obj, new Object[0]);
_log.info("Extension " + className + " unloaded.");
}
catch (Exception ex)
{
_log.log(Level.WARNING, "could not unload " + className, ex);
res = ex.toString();
}
return res;
}
/**
* unloads all extensions, resets the cache and initializes all configured extensions
*
*/
public void reload()
{
unloadExtensions();
clearCache();
initExtensions();
}
/**
* unloads a named extension, resets the cache and initializes the extension
* @param name the class name and optionally a jar file name delimited with a '@' if the jar file is not
* in the class path
*/
public void reload(String name)
{
unloadExtension(name);
clearCache();
initExtension(name);
}
/**
* register a getter function given a (hopefully) unique name
* @param name the name of the function
* @param function the ExtensionFunction implementation
*/
public void addGetter(String name, ExtensionFunction function)
{
_getters.put(name, function);
}
/**
* deregister a getter function
* @param name the name used for registering
*/
public void removeGetter(String name)
{
_getters.remove(name);
}
/**
* call a getter function registered with DynamicExtension
* @param name the function name
* @param arg a function argument
* @return an object from the extension
*/
public Object get(String name, String arg)
{
ExtensionFunction func = _getters.get(name);
if (func != null)
return func.get(arg);
return "<none>";
}
/**
* register a setter function given a (hopefully) unique name
* @param name the name of the function
* @param function the ExtensionFunction implementation
*/
public void addSetter(String name, ExtensionFunction function)
{
_setters.put(name, function);
}
/**
* deregister a setter function
* @param name the name used for registering
*/
public void removeSetter(String name)
{
_setters.remove(name);
}
/**
* call a setter function registered with DynamicExtension
* @param name the function name
* @param arg a function argument
* @param obj an object to set
*/
public void set(String name, String arg, Object obj)
{
ExtensionFunction func = _setters.get(name);
if (func != null)
func.set(arg, obj);
}
public JarClassLoader getClassLoader()
{
return _classLoader;
}
@SuppressWarnings("synthetic-access")
private static class SingletonHolder
{
protected static final DynamicExtension _instance = new DynamicExtension();
}
}
| 25.016667
| 105
| 0.697935
|
13e11625754a1e0840a2099cbbb6725a8ab1b6dd
| 4,604
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.plannerv2.rel.physical;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.util.ImmutableBitSet;
import org.voltdb.plannerv2.rel.util.PlanCostUtil;
import org.voltdb.plannodes.AggregatePlanNode;
import java.util.List;
public class VoltPhysicalSerialAggregate extends VoltPhysicalAggregate {
// Inline Rels
final private RexNode m_offset;
final private RexNode m_limit;
/**
* Constructor
*/
public VoltPhysicalSerialAggregate(
RelOptCluster cluster, RelTraitSet traitSet, RelNode child, boolean indicator, ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls, RexNode postPredicate,
boolean isCoordinatorAggr, RexNode offset, RexNode limit) {
super(cluster, traitSet, child, indicator, groupSet, groupSets, aggCalls, postPredicate,
isCoordinatorAggr);
m_offset = offset;
m_limit = limit;
}
public VoltPhysicalSerialAggregate(
RelOptCluster cluster, RelTraitSet traitSet, RelNode child, boolean indicator, ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls, RexNode postPredicate,
boolean isCoordinatorAggr) {
super(cluster, traitSet, child, indicator, groupSet, groupSets, aggCalls, postPredicate,
isCoordinatorAggr);
m_offset = null;
m_limit = null;
}
@Override
public RelOptCost computeSelfCost(
RelOptPlanner planner, RelMetadataQuery mq) {
double rowCount =
PlanCostUtil.discountSerialAggregateRowCount(getInput().estimateRowCount(mq), getGroupCount());
return planner.getCostFactory().makeCost(rowCount, rowCount, 0);
}
@Override
public VoltPhysicalSerialAggregate copy(
RelTraitSet traitSet, RelNode input, boolean indicator, ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls) {
return new VoltPhysicalSerialAggregate(
getCluster(), traitSet, input, indicator, groupSet, groupSets, aggCalls, getPostPredicate(),
getIsCoordinatorAggr(), m_offset, m_limit);
}
@Override
public VoltPhysicalSerialAggregate copy(
RelOptCluster cluster, RelTraitSet traitSet, RelNode input, boolean indicator, ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls, RexNode havingExpression,
boolean isCoordinatorAggr) {
return new VoltPhysicalSerialAggregate(
cluster, traitSet, input, indicator, groupSet, groupSets, aggCalls, havingExpression,
isCoordinatorAggr, m_offset, m_limit);
}
@Override
public RelWriter explainTerms(RelWriter pw) {
super.explainTerms(pw);
pw.item("type", "serial");
return pw;
}
public RexNode getOffset() {
return m_offset;
}
public RexNode getLimit() {
return m_limit;
}
@Override
protected String computeDigest() {
String digest = super.computeDigest();
if (m_limit != null) {
digest += "_limit_" + m_limit.toString();
}
if (m_offset != null) {
digest += "_offset_" + m_offset.toString();
}
return digest;
}
@Override
protected AggregatePlanNode getAggregatePlanNode() {
return new AggregatePlanNode();
}
}
| 37.430894
| 116
| 0.697437
|
cc82e4a365ed0114674e0c3421972043888f2893
| 6,950
|
package de.mirkosertic.flightrecorderstarter.actuator;
import de.mirkosertic.flightrecorderstarter.actuator.model.FlightRecorderPublicSession;
import de.mirkosertic.flightrecorderstarter.core.FlightRecorder;
import de.mirkosertic.flightrecorderstarter.core.StartRecordingCommand;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The type Reactive flight recorder endpoint.
*/
@RestControllerEndpoint(id = "flightrecorder")
public class ReactiveFlightRecorderEndpoint {
private final static Logger LOGGER = Logger.getLogger(ReactiveFlightRecorderEndpoint.class.getCanonicalName());
private final FlightRecorder flightRecorder;
/**
* Instantiates a new Reactive flight recorder endpoint.
*
* @param flightRecorder the flight recorder
*/
public ReactiveFlightRecorderEndpoint(
final FlightRecorder flightRecorder) {
this.flightRecorder = flightRecorder;
}
/**
* All sessions flux.
*
* @return the flux
*/
@GetMapping("/")
public Flux<FlightRecorderPublicSession> allSessions() {
return Flux.defer(() -> {
LOGGER.info("Retrieving all known recording sessions");
return Flux.fromIterable(this.flightRecorder.sessions());
}).doOnError(e -> ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()));
}
/**
* Start recording mono.
*
* @param commandInput the command input
* @param serverWebExchange the server web exchange
* @return the mono
*/
@PostMapping("/")
public Mono<ResponseEntity<?>> startRecording(@RequestBody final Mono<StartRecordingCommand> commandInput,
final ServerWebExchange serverWebExchange) {
return commandInput.filter(command -> command.getDuration() != null && command.getTimeUnit() != null)
.doOnNext(c -> LOGGER.log(Level.INFO, "Trying to start recording for {0} {1}",
new Object[]{c.getDuration(), c.getTimeUnit()}))
.map(command -> {
Long recordingId = null;
try {
recordingId = this.flightRecorder.startRecordingFor(command);
} catch (final IOException ioe) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ioe.getMessage());
}
LOGGER.log(Level.INFO, "Created recording with ID {0}", recordingId);
return ResponseEntity
.created(UriComponentsBuilder.fromUri(serverWebExchange.getRequest().getURI())
.path("/{id}")
.build(recordingId))
.build();
})
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body("Duration and TimeUnit cannot be null")));
}
/**
* Stop recording mono.
*
* @param recordingId the recording id param
* @return the mono
*/
@PutMapping("/{recordingId}")
public Mono<ResponseEntity<?>> stopRecording(@Selector @PathVariable final Long recordingId) {
return Mono.just(recordingId).map(recordingIdMap -> {
LOGGER.log(Level.INFO, "Stopping recording with ID {0}", recordingIdMap);
final File file = this.flightRecorder.stopRecording(recordingIdMap);
if (file != null) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(this.flightRecorder.getById(recordingIdMap));
}
return ResponseEntity.notFound().build();
});
}
/**
* Delete recording mono.
*
* @param recordingId the recording id param
* @return the mono
*/
@DeleteMapping("/{recordingId}")
public Mono<ResponseEntity<?>> deleteRecording(@Selector @PathVariable final Long recordingId) {
return Mono.just(recordingId).map(recordingIdMap -> {
try {
LOGGER.log(Level.INFO, "Deleting recording with ID {0}", recordingIdMap);
final File file = this.flightRecorder.stopRecording(recordingIdMap);
if (file != null) {
this.flightRecorder.deleteRecording(recordingIdMap);
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
} catch (final Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
});
}
/**
* Download recording mono.
*
* @param recordingId the recording id param
* @return the mono
*/
@GetMapping("/{recordingId}")
public Mono<ResponseEntity<?>> downloadRecording(
@Selector @PathVariable final Long recordingId) {
return Mono.just(recordingId)
.map(recordingIdMap -> {
LOGGER.log(Level.INFO, "Closing recording with ID {0} and downloading file", recordingIdMap);
final File file = this.flightRecorder.stopRecording(recordingIdMap);
if (file != null) {
return ResponseEntity.ok()
.headers(headers -> {
headers
.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=flightrecording_" + recordingIdMap +
".jfr");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
})
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(file));
}
return ResponseEntity.notFound().build();
});
}
}
| 39.942529
| 116
| 0.592374
|
6f097b746f89bcfd101d1f4456ddd20d3df639c2
| 4,282
|
package se.gritacademy.openchat;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.Objects;
import se.gritacademy.openchat.models.ChatModel;
import se.gritacademy.openchat.models.UserModel;
public class ChatActivity extends AppCompatActivity {
private static final String TAG = "UserChat";
ImageView image;
EditText userMessage;
FirebaseAuth mAuth;
DatabaseReference mChat, mUser;
FirebaseListAdapter adapter;
String username = "null";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
userMessage = findViewById(R.id.user_message);
image = findViewById(R.id.send_image);
String UIID = mAuth.getUid();
mChat = FirebaseDatabase.getInstance().getReference().child("chats");
assert UIID != null;
mUser = FirebaseDatabase.getInstance().getReference("Users").child(UIID);
showChatMessage();
// Get username from db for use in sendMessage method
mUser.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
UserModel user = dataSnapshot.getValue(UserModel.class);
assert user != null;
username = user.getUsername();
Log.d(TAG, "Value of username " + username);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// Pushes message,username,timestamp via constructor to db
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void sendMessage(View view) {
if(userMessage.getText() != null) {
if(!userMessage.getText().toString().equals("") && username != null) {
mChat.push().setValue(new ChatModel(userMessage.getText().toString(), username, System.currentTimeMillis()));
Log.d(TAG, "usermessage pushed: success " + username + " " + userMessage);
}
}
Objects.requireNonNull(userMessage.getText()).clear();
}
// Using firebaselistoption to populate chatscreen.
public void showChatMessage(){
ListView messages = findViewById(R.id.list_message);
Query query = mChat;
Log.d(TAG,"mChat data: " +mChat);
FirebaseListOptions<ChatModel> options =
new FirebaseListOptions.Builder<ChatModel>().setQuery(query, ChatModel.class)
.setLayout(R.layout.messages).setLifecycleOwner(this).build();
adapter = new FirebaseListAdapter<ChatModel>(options) {
@Override
protected void populateView(@NonNull View v, @NonNull ChatModel model, int position) {
TextView messageText, messageUser, messageTime;
messageText = v.findViewById(R.id.message_text);
messageUser = v.findViewById(R.id.message_user);
messageTime = v.findViewById(R.id.message_time);
messageText.setText(model.getMessage());
messageUser.setText(model.getName());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getTimestamp()));
}
};
messages.setAdapter(adapter);
}
}
| 33.984127
| 125
| 0.675852
|
5000f0239dc91f4edc6b9949502cf31188bc4e66
| 111
|
package kae.demo.snake;
public interface GameListener {
void moved();
void ate();
void gameOver();
}
| 10.090909
| 31
| 0.666667
|
d9d61ed71d8cd75e0339a217223bfeb848428506
| 4,189
|
/*
* 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.ranger.biz;
import org.apache.ranger.common.MessageEnums;
import org.apache.ranger.common.RESTErrorUtil;
import org.apache.ranger.common.SearchCriteria;
import org.apache.ranger.service.XCredentialStoreService;
import org.apache.ranger.service.XPolicyExportAuditService;
import org.apache.ranger.service.XResourceService;
import org.apache.ranger.view.VXCredentialStore;
import org.apache.ranger.view.VXCredentialStoreList;
import org.apache.ranger.view.VXLong;
import org.apache.ranger.view.VXPolicyExportAudit;
import org.apache.ranger.view.VXPolicyExportAuditList;
import org.springframework.beans.factory.annotation.Autowired;
public class AssetMgrBase {
@Autowired
RESTErrorUtil restErrorUtil;
@Autowired
XResourceService xResourceService;
@Autowired
XCredentialStoreService xCredentialStoreService;
@Autowired
XPolicyExportAuditService xPolicyExportAuditService;
public VXCredentialStore getXCredentialStore(Long id){
return (VXCredentialStore)xCredentialStoreService.readResource(id);
}
public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore){
vXCredentialStore = (VXCredentialStore)xCredentialStoreService.createResource(vXCredentialStore);
return vXCredentialStore;
}
public VXCredentialStore updateXCredentialStore(VXCredentialStore vXCredentialStore) {
vXCredentialStore = (VXCredentialStore)xCredentialStoreService.updateResource(vXCredentialStore);
return vXCredentialStore;
}
public void deleteXCredentialStore(Long id, boolean force) {
if (force) {
xCredentialStoreService.deleteResource(id);
} else {
throw restErrorUtil.createRESTException(
"serverMsg.modelMgrBaseDeleteModel",
MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
}
public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) {
return xCredentialStoreService.searchXCredentialStores(searchCriteria);
}
public VXLong getXCredentialStoreSearchCount(SearchCriteria searchCriteria) {
return xCredentialStoreService.getSearchCount(searchCriteria,
xCredentialStoreService.searchFields);
}
public VXPolicyExportAudit getXPolicyExportAudit(Long id){
return (VXPolicyExportAudit)xPolicyExportAuditService.readResource(id);
}
public VXPolicyExportAudit createXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit){
vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.createResource(vXPolicyExportAudit);
return vXPolicyExportAudit;
}
public VXPolicyExportAudit updateXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) {
vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.updateResource(vXPolicyExportAudit);
return vXPolicyExportAudit;
}
public void deleteXPolicyExportAudit(Long id, boolean force) {
if (force) {
xPolicyExportAuditService.deleteResource(id);
} else {
throw restErrorUtil.createRESTException(
"serverMsg.modelMgrBaseDeleteModel",
MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
}
public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) {
return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
}
public VXLong getXPolicyExportAuditSearchCount(SearchCriteria searchCriteria) {
return xPolicyExportAuditService.getSearchCount(searchCriteria,
xPolicyExportAuditService.searchFields);
}
}
| 36.112069
| 108
| 0.822392
|
fb860b7cef64e87d69a24c3535ae971867a1cf3c
| 3,230
|
package org.kabuki.actor;
import org.kabuki.queues.Queue;
import org.kabuki.queues.Queues;
import org.kabuki.queues.mpsc.MPSC_SlotType;
import org.kabuki.utils.concurrent.WaitType;
import org.metaja.common.Composite;
import org.metaja.common.IComposite;
import org.metaja.common.Stub;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static java.util.stream.Collectors.reducing;
import static org.metaja.utils.ReflectionUtils.Modifier.PUBLIC;
public class ActorSystemMPSC_Dynamic extends ActorSystemMPSC {
private final WaitType waitType;
private final int queueSize;
private List<ActorReference<?>> actorReferences = new ArrayList<>();
public ActorSystemMPSC_Dynamic(WaitType waitType, int queueSize, String threadName, Consumer<Throwable> errorConsumer) {
super(threadName, errorConsumer);
this.waitType = waitType;
this.queueSize = queueSize;
}
@Override
public synchronized <I> I asynchronize(Class<I> i, String commitMethodName, I object) {
if (!i.isInterface() || !PUBLIC.isModified(i)) {
throw new IllegalArgumentException(i.getCanonicalName() + " is not a public interface!");
}
if (actorReferences == null) {
throw new IllegalStateException("Actor system can not make actor after first start!");
}
ActorReference<I> actorReference = new ActorReference<>(i, commitMethodName, object);
actorReferences.add(actorReference);
return actorReference.actorComposite.instance();
}
@Override
protected void initBeforeStart() {
if (actorReferences != null) {
MPSC_SlotType queueSlotType = actorReferences.stream().map(actorReference -> actorReference.type).collect(reducing(MPSC_SlotType.ZERO, MPSC_SlotType::get, MPSC_SlotType::max));
queue = Queues.mpsc(waitType, queueSlotType, queueSize, errorConsumer);
actorReferences.forEach(actorReference -> actorReference.attach(queue));
actorReferences = null;
}
}
// ===== private =====
private static class ActorReference<I> {
public final Class<I> type;
public final String commitMethodName;
public final I object;
public final IComposite<I> actorComposite;
public ActorReference(Class<I> type, String commitMethodName, I object) {
this.type = type;
this.commitMethodName = commitMethodName;
this.object = object;
this.actorComposite = Composite.create(type, Stub.create(type, () -> { throw new IllegalStateException("Actor system is not started!"); }));
}
public void attach(Queue queue) {
actorComposite.delegate(
commitMethodName == null
? queue.asynchronize(type, object)
: queue.asynchronize(type, commitMethodName, object)
);
}
}
// ----- some sugar ----
public ActorSystemMPSC_Dynamic(WaitType waitType) {
this(waitType, 1024, ActorSystemMPSC_Dynamic.class.getName(), Throwable::printStackTrace);
}
public ActorSystemMPSC_Dynamic() {
this(WaitType.LOCK);
}
}
| 35.888889
| 188
| 0.673994
|
69d6e806ab592bfba6c5df5b31328469f883c5e9
| 4,839
|
package com.vodafone.datafusion.plugins.delta.common;
import com.google.common.base.Strings;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Properties;
import static com.vodafone.datafusion.plugins.delta.constants.Constants.*;
/**
* Class to connect to SFTP server.
*/
public class SFTPConnector implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(SFTPConnector.class);
private final Session session;
private final Channel channel;
private String connID;
/**
* Informs if connection is done
*
* @param host connection host
* @param port connection port
* @param userName connection user
* @return
*/
public boolean isConnected(String host, int port, String userName) {
String cID = host + port + userName;
return connID.equals(cID);
}
/**
* Connector Object for password authentication
*
* @param host connection host
* @param port connection port
* @param userName connection user
* @param password connection password
* @param proxyIP connection proxyIP
* @param proxyPort connection proxyPort
* @param sessionProperties session properties
* @throws Exception
*/
public SFTPConnector(String host, int port, String userName, String password, String proxyIP,Integer proxyPort,Map<String, String> sessionProperties)
throws Exception {
LOG.debug("[SFTP Delta] Connecting to SFTP server via password.");
JSch jsch = new JSch();
this.session = jsch.getSession(userName, host, port);
session.setPassword(password);
LOG.debug("[SFTP Delta] Connection properties: {}", sessionProperties);
Properties properties = new Properties();
properties.putAll(sessionProperties);
session.setConfig(properties);
if(!Strings.isNullOrEmpty(proxyIP) && proxyPort!=null){
session.setProxy(new ProxyHTTP(proxyIP, proxyPort));
}
LOG.debug("[SFTP Delta] Connecting to Host: {}, Port: {}, with User: {}", host, port, userName);
session.connect(TIMEOUT);
channel = session.openChannel(CONN_SFTP);
channel.connect();
LOG.debug("[SFTP Delta] Connected.");
connID = host + port + userName;
}
/**
* Connection object for SSH PrivateKey authentication
*
* @param host connection host
* @param port connection port
* @param userName connection user
* @param privateKey connection private key
* @param proxyIP connection proxyIP
* @param proxyPort connection proxyPort
* @param passphrase passphrase
* @param sessionProperties session properties
* @throws Exception
*/
public SFTPConnector(String host, int port, String userName, byte[] privateKey,String proxyIP,Integer proxyPort,
byte[] passphrase, Map<String, String> sessionProperties) throws JSchException {
LOG.debug("[SFTP Delta] Connecting to SFTP server private key.");
JSch jsch = new JSch();
jsch.addIdentity(KEY, privateKey, null, passphrase);
this.session = jsch.getSession(userName, host, port);
LOG.debug("[SFTP Delta] Connection properties: {}", sessionProperties);
Properties properties = new Properties();
properties.putAll(sessionProperties);
session.setConfig(properties);
if(!Strings.isNullOrEmpty(proxyIP) && proxyPort!=null){
session.setProxy(new ProxyHTTP(proxyIP, proxyPort));
}
LOG.debug("[SFTP Delta] Connecting to Host: {}, Port: {}, with User: {}", host, port, userName);
session.connect(TIMEOUT);
channel = session.openChannel(CONN_SFTP);
channel.connect();
LOG.debug("[SFTP Delta] Connected.");
connID = host + port + userName;
}
/**
* Get the established sftp channel to perform operations.
*/
public ChannelSftp getSftpChannel() {
LOG.debug("[SFTP Delta] Getting SFTP channel.");
return (ChannelSftp) channel;
}
@Override
public void close() {
if (channel != null) {
try {
channel.disconnect();
LOG.debug("[SFTP Delta] Closed SFTP channel.");
} catch (Throwable t) {
LOG.warn("[SFTP Delta] Error disconnecting sftp channel.", t);
}
}
if (session != null) {
try {
session.disconnect();
LOG.debug("[SFTP Delta] Closed SFTP session.");
} catch (Throwable t) {
LOG.warn("[SFTP Delta] Error disconnecting sftp session.", t);
}
}
}
}
| 36.383459
| 153
| 0.626162
|
92b22cd71a1883ff0583ba1428a255de6e35cd94
| 4,939
|
package com.lh_lshen.mcbbs.huajiage.stand.messages;
import com.lh_lshen.mcbbs.huajiage.capability.IExposedData;
import com.lh_lshen.mcbbs.huajiage.stand.StandStates;
import com.lh_lshen.mcbbs.huajiage.stand.StandUtil;
import com.lh_lshen.mcbbs.huajiage.stand.custom.StandCustom;
import com.lh_lshen.mcbbs.huajiage.stand.custom.StandStateCustom;
import com.lh_lshen.mcbbs.huajiage.stand.custom.StandStateInfo;
import com.lh_lshen.mcbbs.huajiage.stand.instance.StandBase;
import com.lh_lshen.mcbbs.huajiage.stand.states.StandStateBase;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.network.play.server.SPacketSoundEffect;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import java.util.List;
public class MessageStandModeSwitch implements IMessage {
public MessageStandModeSwitch() {
}
@Override
public void toBytes(ByteBuf buf) {
}
@Override
public void fromBytes(ByteBuf buf) {
}
public static class Handler implements IMessageHandler<MessageStandModeSwitch, IMessage> {
@Override
public IMessage onMessage(MessageStandModeSwitch message , MessageContext ctx) {
EntityPlayerMP player = ctx.getServerHandler().player;
StandBase stand = StandUtil.getType(player);
List<String> states = stand.getStates();
IExposedData data = StandUtil.getStandData(player);
String state = StandUtil.getStandState(player);
if (ctx.side == Side.SERVER) {
FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(() ->{
if(null==stand || null==states || null==data) {
return;
}else {
boolean flag = !states.isEmpty();
if(flag) {
if(state==null){
player.sendMessage(new TextComponentTranslation("message.huajiage.stand_mode.empty_null"));
return;
}
// int index = states.indexOf(state)+1;
// if((index+1)<=states.size()){
// StandUtil.setStandState(player,states.get(index));
// }else {
// StandUtil.setStandState(player,states.get(0));
// }
switchState(player,data,stand,1);
data.setStage(StandUtil.getStandStage(player));
String state_new = StandUtil.getStandState(player);
StandStateBase stateBase = StandStates.getStandState(stand.getName(),state_new);
// for(String s : stateBase.getExtraDatas()){
// player.sendMessage(new TextComponentString(s));
// }
// if(stateBase.getExtraDatas().isEmpty()){
// player.sendMessage(new TextComponentString("empty"));
// }
if(stateBase!=null){
data.setHandDisplay(stateBase.isHandPlay());
// player.sendMessage(new TextComponentString(stateBase.getStateName()+stateBase.isHandPlay()));
}
String stand_state_format="stand.state.huajiage"+"."+state_new;
if(stand instanceof StandCustom){
StandStateBase standState = StandStates.getStandState(stand.getName(),state_new);
if(standState instanceof StandStateCustom){
StandStateInfo stateInfo = ((StandStateCustom)standState).getStateInfo();
stand_state_format = stateInfo.getStateKey();
}
}
TextComponentTranslation state_trans = new TextComponentTranslation(stand_state_format);
player.connection.sendPacket(new SPacketSoundEffect(SoundEvents.ENTITY_PLAYER_LEVELUP, SoundCategory.PLAYERS, player.posX, player.posY, player.posZ,0.5f, 1f));
player.sendMessage(new TextComponentTranslation("message.huajiage.stand_mode.switch",state_trans.getUnformattedComponentText()));
}else {
player.sendMessage(new TextComponentTranslation("message.huajiage.stand_mode.empty"));
}
}
});
}
return null;
}
}
private static void switchState(EntityPlayer player, IExposedData data, StandBase stand, int i){
String state = StandUtil.getStandState(player);
List<String> states = stand.getStates();
if(states!=null&&!state.isEmpty()){
int index = states.indexOf(state)+i;
if((index+1)<=states.size()){
StandStateBase base = StandStates.getStandState(stand.getName(),states.get(index));
if (base!=null) {
if(base.getStage()<=data.getStage()){
StandUtil.setStandState(player,states.get(index));
}else{
switchState(player,data,stand,i+1);
}
// player.sendMessage(new TextComponentString(base.getStage()+"-"+data.getStage()));
}
}else {
StandUtil.setStandState(player,states.get(0));
}
}
}
}
| 40.154472
| 165
| 0.722211
|
55e6263c02631be57b540ea0543bebde00bd01d3
| 16,752
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Copyright (C) 2018 The Android Open Source Project
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Licensed under the Apache License, Version 2.0 (the "License");
end_comment
begin_comment
comment|// you may not use this file except in compliance with the License.
end_comment
begin_comment
comment|// You may obtain a copy of the License at
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// http://www.apache.org/licenses/LICENSE-2.0
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Unless required by applicable law or agreed to in writing, software
end_comment
begin_comment
comment|// distributed under the License is distributed on an "AS IS" BASIS,
end_comment
begin_comment
comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
end_comment
begin_comment
comment|// See the License for the specific language governing permissions and
end_comment
begin_comment
comment|// limitations under the License.
end_comment
begin_package
DECL|package|com.google.gerrit.server.config
package|package
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|config
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ArrayListMultimap
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ImmutableMultimap
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|Multimap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|LinkedHashSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Objects
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|lang
operator|.
name|StringUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jgit
operator|.
name|lib
operator|.
name|Config
import|;
end_import
begin_comment
comment|/** * This event is produced by {@link GerritServerConfigReloader} and forwarded to callers * implementing {@link GerritConfigListener}. * *<p>The event intends to: * *<p>1. Help the callers figure out if any action should be taken, depending on which entries are * updated in gerrit.config. * *<p>2. Provide the callers with a mechanism to accept/reject the entries of interest: @see * accept(Set<ConfigKey> entries), @see accept(String section), @see reject(Set<ConfigKey> entries) * (+ various overloaded versions of these) */
end_comment
begin_class
DECL|class|ConfigUpdatedEvent
specifier|public
class|class
name|ConfigUpdatedEvent
block|{
DECL|field|NO_UPDATES
specifier|public
specifier|static
specifier|final
name|ImmutableMultimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|NO_UPDATES
init|=
operator|new
name|ImmutableMultimap
operator|.
name|Builder
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
argument_list|()
operator|.
name|build
argument_list|()
decl_stmt|;
DECL|field|oldConfig
specifier|private
specifier|final
name|Config
name|oldConfig
decl_stmt|;
DECL|field|newConfig
specifier|private
specifier|final
name|Config
name|newConfig
decl_stmt|;
DECL|method|ConfigUpdatedEvent (Config oldConfig, Config newConfig)
specifier|public
name|ConfigUpdatedEvent
parameter_list|(
name|Config
name|oldConfig
parameter_list|,
name|Config
name|newConfig
parameter_list|)
block|{
name|this
operator|.
name|oldConfig
operator|=
name|oldConfig
expr_stmt|;
name|this
operator|.
name|newConfig
operator|=
name|newConfig
expr_stmt|;
block|}
DECL|method|getOldConfig ()
specifier|public
name|Config
name|getOldConfig
parameter_list|()
block|{
return|return
name|this
operator|.
name|oldConfig
return|;
block|}
DECL|method|getNewConfig ()
specifier|public
name|Config
name|getNewConfig
parameter_list|()
block|{
return|return
name|this
operator|.
name|newConfig
return|;
block|}
DECL|method|getString (ConfigKey key, Config config)
specifier|private
name|String
name|getString
parameter_list|(
name|ConfigKey
name|key
parameter_list|,
name|Config
name|config
parameter_list|)
block|{
return|return
name|config
operator|.
name|getString
argument_list|(
name|key
operator|.
name|section
argument_list|()
argument_list|,
name|key
operator|.
name|subsection
argument_list|()
argument_list|,
name|key
operator|.
name|name
argument_list|()
argument_list|)
return|;
block|}
DECL|method|accept (ConfigKey entry)
specifier|public
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|accept
parameter_list|(
name|ConfigKey
name|entry
parameter_list|)
block|{
return|return
name|accept
argument_list|(
name|Collections
operator|.
name|singleton
argument_list|(
name|entry
argument_list|)
argument_list|)
return|;
block|}
DECL|method|accept (Set<ConfigKey> entries)
specifier|public
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|accept
parameter_list|(
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
parameter_list|)
block|{
return|return
name|createUpdate
argument_list|(
name|entries
argument_list|,
name|UpdateResult
operator|.
name|APPLIED
argument_list|)
return|;
block|}
DECL|method|accept (String section)
specifier|public
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|accept
parameter_list|(
name|String
name|section
parameter_list|)
block|{
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
init|=
name|getEntriesFromSection
argument_list|(
name|oldConfig
argument_list|,
name|section
argument_list|)
decl_stmt|;
name|entries
operator|.
name|addAll
argument_list|(
name|getEntriesFromSection
argument_list|(
name|newConfig
argument_list|,
name|section
argument_list|)
argument_list|)
expr_stmt|;
return|return
name|createUpdate
argument_list|(
name|entries
argument_list|,
name|UpdateResult
operator|.
name|APPLIED
argument_list|)
return|;
block|}
DECL|method|reject (ConfigKey entry)
specifier|public
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|reject
parameter_list|(
name|ConfigKey
name|entry
parameter_list|)
block|{
return|return
name|reject
argument_list|(
name|Collections
operator|.
name|singleton
argument_list|(
name|entry
argument_list|)
argument_list|)
return|;
block|}
DECL|method|reject (Set<ConfigKey> entries)
specifier|public
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|reject
parameter_list|(
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
parameter_list|)
block|{
return|return
name|createUpdate
argument_list|(
name|entries
argument_list|,
name|UpdateResult
operator|.
name|REJECTED
argument_list|)
return|;
block|}
DECL|method|getEntriesFromSection (Config config, String section)
specifier|private
specifier|static
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|getEntriesFromSection
parameter_list|(
name|Config
name|config
parameter_list|,
name|String
name|section
parameter_list|)
block|{
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|res
init|=
operator|new
name|LinkedHashSet
argument_list|<>
argument_list|()
decl_stmt|;
for|for
control|(
name|String
name|name
range|:
name|config
operator|.
name|getNames
argument_list|(
name|section
argument_list|,
literal|true
argument_list|)
control|)
block|{
name|res
operator|.
name|add
argument_list|(
name|ConfigKey
operator|.
name|create
argument_list|(
name|section
argument_list|,
name|name
argument_list|)
argument_list|)
expr_stmt|;
block|}
for|for
control|(
name|String
name|sub
range|:
name|config
operator|.
name|getSubsections
argument_list|(
name|section
argument_list|)
control|)
block|{
for|for
control|(
name|String
name|name
range|:
name|config
operator|.
name|getNames
argument_list|(
name|section
argument_list|,
name|sub
argument_list|,
literal|true
argument_list|)
control|)
block|{
name|res
operator|.
name|add
argument_list|(
name|ConfigKey
operator|.
name|create
argument_list|(
name|section
argument_list|,
name|sub
argument_list|,
name|name
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|res
return|;
block|}
DECL|method|createUpdate ( Set<ConfigKey> entries, UpdateResult updateResult)
specifier|private
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|createUpdate
parameter_list|(
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
parameter_list|,
name|UpdateResult
name|updateResult
parameter_list|)
block|{
name|Multimap
argument_list|<
name|UpdateResult
argument_list|,
name|ConfigUpdateEntry
argument_list|>
name|updates
init|=
name|ArrayListMultimap
operator|.
name|create
argument_list|()
decl_stmt|;
name|entries
operator|.
name|stream
argument_list|()
operator|.
name|filter
argument_list|(
name|this
operator|::
name|isValueUpdated
argument_list|)
operator|.
name|map
argument_list|(
name|e
lambda|->
operator|new
name|ConfigUpdateEntry
argument_list|(
name|e
argument_list|,
name|getString
argument_list|(
name|e
argument_list|,
name|oldConfig
argument_list|)
argument_list|,
name|getString
argument_list|(
name|e
argument_list|,
name|newConfig
argument_list|)
argument_list|)
argument_list|)
operator|.
name|forEach
argument_list|(
name|e
lambda|->
name|updates
operator|.
name|put
argument_list|(
name|updateResult
argument_list|,
name|e
argument_list|)
argument_list|)
expr_stmt|;
return|return
name|updates
return|;
block|}
DECL|method|isSectionUpdated (String section)
specifier|public
name|boolean
name|isSectionUpdated
parameter_list|(
name|String
name|section
parameter_list|)
block|{
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
init|=
name|getEntriesFromSection
argument_list|(
name|oldConfig
argument_list|,
name|section
argument_list|)
decl_stmt|;
name|entries
operator|.
name|addAll
argument_list|(
name|getEntriesFromSection
argument_list|(
name|newConfig
argument_list|,
name|section
argument_list|)
argument_list|)
expr_stmt|;
return|return
name|isEntriesUpdated
argument_list|(
name|entries
argument_list|)
return|;
block|}
DECL|method|isValueUpdated (String section, String subsection, String name)
specifier|public
name|boolean
name|isValueUpdated
parameter_list|(
name|String
name|section
parameter_list|,
name|String
name|subsection
parameter_list|,
name|String
name|name
parameter_list|)
block|{
return|return
operator|!
name|Objects
operator|.
name|equals
argument_list|(
name|oldConfig
operator|.
name|getString
argument_list|(
name|section
argument_list|,
name|subsection
argument_list|,
name|name
argument_list|)
argument_list|,
name|newConfig
operator|.
name|getString
argument_list|(
name|section
argument_list|,
name|subsection
argument_list|,
name|name
argument_list|)
argument_list|)
return|;
block|}
DECL|method|isValueUpdated (ConfigKey key)
specifier|public
name|boolean
name|isValueUpdated
parameter_list|(
name|ConfigKey
name|key
parameter_list|)
block|{
return|return
name|isValueUpdated
argument_list|(
name|key
operator|.
name|section
argument_list|()
argument_list|,
name|key
operator|.
name|subsection
argument_list|()
argument_list|,
name|key
operator|.
name|name
argument_list|()
argument_list|)
return|;
block|}
DECL|method|isValueUpdated (String section, String name)
specifier|public
name|boolean
name|isValueUpdated
parameter_list|(
name|String
name|section
parameter_list|,
name|String
name|name
parameter_list|)
block|{
return|return
name|isValueUpdated
argument_list|(
name|section
argument_list|,
literal|null
argument_list|,
name|name
argument_list|)
return|;
block|}
DECL|method|isEntriesUpdated (Set<ConfigKey> entries)
specifier|public
name|boolean
name|isEntriesUpdated
parameter_list|(
name|Set
argument_list|<
name|ConfigKey
argument_list|>
name|entries
parameter_list|)
block|{
for|for
control|(
name|ConfigKey
name|entry
range|:
name|entries
control|)
block|{
if|if
condition|(
name|isValueUpdated
argument_list|(
name|entry
operator|.
name|section
argument_list|()
argument_list|,
name|entry
operator|.
name|subsection
argument_list|()
argument_list|,
name|entry
operator|.
name|name
argument_list|()
argument_list|)
condition|)
block|{
return|return
literal|true
return|;
block|}
block|}
return|return
literal|false
return|;
block|}
DECL|enum|UpdateResult
specifier|public
enum|enum
name|UpdateResult
block|{
DECL|enumConstant|APPLIED
name|APPLIED
block|,
DECL|enumConstant|REJECTED
name|REJECTED
block|;
annotation|@
name|Override
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
return|return
name|StringUtils
operator|.
name|capitalize
argument_list|(
name|name
argument_list|()
operator|.
name|toLowerCase
argument_list|()
argument_list|)
return|;
block|}
block|}
DECL|enum|ConfigEntryType
specifier|public
enum|enum
name|ConfigEntryType
block|{
DECL|enumConstant|ADDED
name|ADDED
block|,
DECL|enumConstant|REMOVED
name|REMOVED
block|,
DECL|enumConstant|MODIFIED
name|MODIFIED
block|,
DECL|enumConstant|UNMODIFIED
name|UNMODIFIED
block|}
DECL|class|ConfigUpdateEntry
specifier|public
specifier|static
class|class
name|ConfigUpdateEntry
block|{
DECL|field|key
specifier|public
specifier|final
name|ConfigKey
name|key
decl_stmt|;
DECL|field|oldVal
specifier|public
specifier|final
name|String
name|oldVal
decl_stmt|;
DECL|field|newVal
specifier|public
specifier|final
name|String
name|newVal
decl_stmt|;
DECL|method|ConfigUpdateEntry (ConfigKey key, String oldVal, String newVal)
specifier|public
name|ConfigUpdateEntry
parameter_list|(
name|ConfigKey
name|key
parameter_list|,
name|String
name|oldVal
parameter_list|,
name|String
name|newVal
parameter_list|)
block|{
name|this
operator|.
name|key
operator|=
name|key
expr_stmt|;
name|this
operator|.
name|oldVal
operator|=
name|oldVal
expr_stmt|;
name|this
operator|.
name|newVal
operator|=
name|newVal
expr_stmt|;
block|}
comment|/** Note: The toString() is used to format the output from @see ReloadConfig. */
annotation|@
name|Override
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
switch|switch
condition|(
name|getUpdateType
argument_list|()
condition|)
block|{
case|case
name|ADDED
case|:
return|return
name|String
operator|.
name|format
argument_list|(
literal|"+ %s = %s"
argument_list|,
name|key
argument_list|,
name|newVal
argument_list|)
return|;
case|case
name|MODIFIED
case|:
return|return
name|String
operator|.
name|format
argument_list|(
literal|"* %s = [%s => %s]"
argument_list|,
name|key
argument_list|,
name|oldVal
argument_list|,
name|newVal
argument_list|)
return|;
case|case
name|REMOVED
case|:
return|return
name|String
operator|.
name|format
argument_list|(
literal|"- %s = %s"
argument_list|,
name|key
argument_list|,
name|oldVal
argument_list|)
return|;
case|case
name|UNMODIFIED
case|:
return|return
name|String
operator|.
name|format
argument_list|(
literal|" %s = %s"
argument_list|,
name|key
argument_list|,
name|newVal
argument_list|)
return|;
default|default:
throw|throw
operator|new
name|IllegalStateException
argument_list|(
literal|"Unexpected UpdateType: "
operator|+
name|getUpdateType
argument_list|()
operator|.
name|name
argument_list|()
argument_list|)
throw|;
block|}
block|}
DECL|method|getUpdateType ()
specifier|public
name|ConfigEntryType
name|getUpdateType
parameter_list|()
block|{
if|if
condition|(
name|oldVal
operator|==
literal|null
operator|&&
name|newVal
operator|!=
literal|null
condition|)
block|{
return|return
name|ConfigEntryType
operator|.
name|ADDED
return|;
block|}
if|if
condition|(
name|oldVal
operator|!=
literal|null
operator|&&
name|newVal
operator|==
literal|null
condition|)
block|{
return|return
name|ConfigEntryType
operator|.
name|REMOVED
return|;
block|}
if|if
condition|(
name|Objects
operator|.
name|equals
argument_list|(
name|oldVal
argument_list|,
name|newVal
argument_list|)
condition|)
block|{
return|return
name|ConfigEntryType
operator|.
name|UNMODIFIED
return|;
block|}
return|return
name|ConfigEntryType
operator|.
name|MODIFIED
return|;
block|}
block|}
block|}
end_class
end_unit
| 14.930481
| 549
| 0.80856
|
8bd500a550b3d19df17852f34959706c5e670082
| 8,435
|
/*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package thredds.server.ncss.view.dsg.station;
import thredds.server.ncss.exception.FeaturesNotFoundException;
import thredds.server.ncss.exception.NcssException;
import thredds.server.ncss.view.dsg.DsgSubsetWriter;
import ucar.ma2.StructureData;
import ucar.nc2.ft.*;
import ucar.nc2.ft.point.PointIteratorFiltered;
import ucar.nc2.ft.point.StationFeature;
import ucar.nc2.ft.point.StationPointFeature;
import ucar.nc2.ft.point.StationTimeSeriesFeatureImpl;
import ucar.nc2.ft2.coverage.SubsetParams;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarDateRange;
import ucar.unidata.geoloc.LatLonPoint;
import ucar.unidata.geoloc.LatLonPointImpl;
import ucar.unidata.geoloc.LatLonRect;
import ucar.unidata.geoloc.Station;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cwardgar on 2014/05/20.
*/
public abstract class AbstractStationSubsetWriter extends DsgSubsetWriter {
protected final StationTimeSeriesFeatureCollection stationFeatureCollection;
protected final List<StationFeature> wantedStations;
protected boolean headerDone = false;
public AbstractStationSubsetWriter(FeatureDatasetPoint fdPoint, SubsetParams ncssParams)
throws NcssException, IOException {
super(fdPoint, ncssParams);
List<DsgFeatureCollection> featColList = fdPoint.getPointFeatureCollectionList();
assert featColList.size() == 1 : "Is there ever a case when this is NOT 1?";
assert featColList.get(0) instanceof StationTimeSeriesFeatureCollection :
"This class only deals with StationTimeSeriesFeatureCollections.";
this.stationFeatureCollection = (StationTimeSeriesFeatureCollection) featColList.get(0);
this.wantedStations = getStationsInSubset(stationFeatureCollection, ncssParams);
if (this.wantedStations.isEmpty()) {
throw new FeaturesNotFoundException("No stations found in subset.");
}
}
protected abstract void writeHeader(StationPointFeature stationPointFeat) throws Exception;
protected abstract void writeStationPointFeature(StationPointFeature stationPointFeat) throws Exception;
protected abstract void writeFooter() throws Exception;
@Override
public void write() throws Exception {
// Perform spatial subset.
StationTimeSeriesFeatureCollection subsettedStationFeatCol = stationFeatureCollection.subsetFeatures(wantedStations);
int count = 0;
for (StationTimeSeriesFeature stationFeat : subsettedStationFeatCol) {
// Perform temporal subset. We do this even when a time instant is specified, in which case wantedRange
// represents a sanity check (i.e. "give me the feature closest to the specified time, but it must at
// least be within an hour").
StationTimeSeriesFeature subsettedStationFeat = stationFeat.subset(wantedRange);
if (ncssParams.getTime() != null) {
CalendarDate wantedTime = ncssParams.getTime();
subsettedStationFeat = new ClosestTimeStationFeatureSubset(
(StationTimeSeriesFeatureImpl) subsettedStationFeat, wantedTime);
}
count += writeStationTimeSeriesFeature(subsettedStationFeat);
}
if (count == 0)
throw new NcssException("No features are in the requested subset");
writeFooter();
}
protected int writeStationTimeSeriesFeature(StationTimeSeriesFeature stationFeat)
throws Exception {
int count = 0;
for (PointFeature pointFeat : stationFeat) {
assert pointFeat instanceof StationPointFeature :
"Expected pointFeat to be a StationPointFeature, not a " + pointFeat.getClass().getSimpleName();
if (!headerDone) {
writeHeader((StationPointFeature) pointFeat);
headerDone = true;
}
writeStationPointFeature((StationPointFeature) pointFeat);
count++;
}
return count;
}
protected static class ClosestTimeStationFeatureSubset extends StationTimeSeriesFeatureImpl {
private final StationTimeSeriesFeature stationFeat;
private CalendarDate closestTime;
protected ClosestTimeStationFeatureSubset(
StationTimeSeriesFeatureImpl stationFeat, CalendarDate wantedTime) throws IOException {
super(stationFeat, stationFeat.getTimeUnit(), stationFeat.getAltUnits(), -1);
this.stationFeat = stationFeat;
CalendarDateRange cdr = stationFeat.getCalendarDateRange();
if (cdr != null) {
getInfo();
info.setCalendarDateRange(cdr);
}
long smallestDiff = Long.MAX_VALUE;
stationFeat.resetIteration();
try {
while (stationFeat.hasNext()) {
PointFeature pointFeat = stationFeat.next();
CalendarDate obsTime = pointFeat.getObservationTimeAsCalendarDate();
long diff = Math.abs(obsTime.getMillis() - wantedTime.getMillis());
if (diff < smallestDiff) {
closestTime = obsTime;
}
}
} finally {
stationFeat.finish();
}
}
@Nonnull
@Override
public StructureData getFeatureData() throws IOException {
return stationFeat.getFeatureData();
}
// Filter out PointFeatures that don't have the wantedTime.
protected static class TimeFilter implements PointFeatureIterator.Filter {
private final CalendarDate wantedTime;
protected TimeFilter(CalendarDate wantedTime) {
this.wantedTime = wantedTime;
}
@Override
public boolean filter(PointFeature pointFeature) {
return pointFeature.getObservationTimeAsCalendarDate().equals(wantedTime);
}
}
@Override
public PointFeatureIterator getPointFeatureIterator() throws IOException {
if (closestTime == null) {
return stationFeat.getPointFeatureIterator();
} else {
return new PointIteratorFiltered(
stationFeat.getPointFeatureIterator(), new TimeFilter(closestTime));
}
}
}
// LOOK could do better : "all", and maybe HashSet<Name>
public static List<StationFeature> getStationsInSubset(
StationTimeSeriesFeatureCollection stationFeatCol, SubsetParams ncssParams) throws IOException {
List<StationFeature> wantedStations;
// verify SpatialSelection has some stations
if (ncssParams.getStations() != null) {
List<String> stnNames = ncssParams.getStations();
if (stnNames.get(0).equals("all")) {
wantedStations = stationFeatCol.getStationFeatures();
} else {
wantedStations = stationFeatCol.getStationFeatures(stnNames);
}
} else if (ncssParams.getLatLonBoundingBox() != null) {
LatLonRect llrect = ncssParams.getLatLonBoundingBox();
wantedStations = stationFeatCol.getStationFeatures(llrect);
} else if (ncssParams.getLatLonPoint() != null) {
Station closestStation = findClosestStation(stationFeatCol, ncssParams.getLatLonPoint());
List<String> stnList = new ArrayList<>();
stnList.add(closestStation.getName());
wantedStations = stationFeatCol.getStationFeatures(stnList);
} else { // Want all.
wantedStations = stationFeatCol.getStationFeatures();
}
return wantedStations;
}
/*
* Find the station closest to the specified point.
* The metric is (lat-lat0)**2 + (cos(lat0)*(lon-lon0))**2
*
* @param lat latitude value
* @param lon longitude value
* @return name of station closest to the specified point
* @throws IOException if read error
*/
public static Station findClosestStation(StationTimeSeriesFeatureCollection stationFeatCol, LatLonPoint pt)
throws IOException {
double lat = pt.getLatitude();
double lon = pt.getLongitude();
double cos = Math.cos(Math.toRadians(lat));
List<StationFeature> stations = stationFeatCol.getStationFeatures();
Station min_station = stations.get(0);
double min_dist = Double.MAX_VALUE;
for (Station s : stations) {
double lat1 = s.getLatitude();
double lon1 = LatLonPointImpl.lonNormal(s.getLongitude(), lon);
double dy = Math.toRadians(lat - lat1);
double dx = cos * Math.toRadians(lon - lon1);
double dist = dy * dy + dx * dx;
if (dist < min_dist) {
min_dist = dist;
min_station = s;
}
}
return min_station;
}
}
| 36.047009
| 121
| 0.719621
|
abac50dc394a2f195bc910bdbe37c4dd402e6dca
| 29,638
|
/*
* This file is part of the ONT API.
* The contents of this file are subject to the LGPL License, Version 3.0.
* Copyright (c) 2019, Avicomp Services, AO
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
*
* Alternatively, the contents of this file may be used under the terms of the Apache License, Version 2.0 in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above.
* 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 ru.avicomp.ontapi.jena.model;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.RDFList;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDFS;
import ru.avicomp.ontapi.jena.OntJenaException;
import ru.avicomp.ontapi.jena.vocabulary.OWL;
import ru.avicomp.ontapi.jena.vocabulary.RDF;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A common interface for any Ontology <b>O</b>bject <b>P</b>roperty <b>E</b>xpression.
* In OWL2 there are two types of object property expressions:
* named object property (entity) and InverseOf anonymous property expression.
* Range values for this property expression are restricted to individuals
* (as distinct from datatype valued {@link OntNDP properties}).
* <p>
* Created by @szuev on 08.11.2016.
*/
public interface OntOPE extends OntDOP {
/**
* {@inheritDoc}
* Note: a {@code PropertyChain} is not included into consideration:
* even this property is a member of some chain ({@code P owl:propertyChainAxiom ( P1 ... Pn )},
* where {@code Pj} is this property), it does not mean it has the same super property ({@code P}).
*
* @return <b>distinct</b> {@code Stream} of object property expressions
* @see #propertyChains()
* @since 1.4.0
*/
@Override
Stream<OntOPE> superProperties(boolean direct);
/**
* {@inheritDoc}
* Note: a {@code PropertyChain} is not included into consideration,
* even this property is a super property of some chain ({@code P owl:propertyChainAxiom ( P1 ... Pn )},
* where {@code P} is this property), each of chain members is not considered as sub property of this property.
*
* @return <b>distinct</b> {@code Stream} of object property expressions
* @see #propertyChains()
* @since 1.4.0
*/
@Override
Stream<OntOPE> subProperties(boolean direct);
/**
* Returns a {@code Stream} over all property chain {@link OntList ontology list}s
* that are attached to this Object Property Expression
* on the predicate {@link OWL#propertyChainAxiom owl:propertyChainAxiom}.
*
* @return {@code Stream} of {@link OntList}s with generic-parameter {@code OntOPE}
* @since 1.3.0
*/
Stream<OntList<OntOPE>> propertyChains();
/**
* Adds a negative property assertion ontology object.
*
* @param source {@link OntIndividual}
* @param target {@link OntIndividual}
* @return {@link OntNPA.ObjectAssertion}
* @see OntNDP#addNegativeAssertion(OntIndividual, Literal)
*/
OntNPA.ObjectAssertion addNegativeAssertion(OntIndividual source, OntIndividual target);
/**
* Creates a property chain logical constructions
* as a {@link OntList ontology []-list} of {@link OntOPE Object Property Expression}s
* that is attached to this Object Property Expression
* at object positions with the predicate {@link OWL#propertyChainAxiom owl:propertyChainAxiom}.
* The resulting rdf-list will consist of all the elements of the specified collection
* in the given order with the possibility of duplication.
* Note: Any {@code null}s in collection will cause {@link OntJenaException.IllegalArgument exception}.
*
* @param properties {@link Collection} (preferably {@link List}) of {@link OntOPE object property expression}s
* @return {@link OntList} of {@link OntOPE}s
* @see <a href='https://www.w3.org/TR/owl2-syntax/#a_SubObjectPropertyOfChain'>9.2.1 Object Subproperties</a>
* @see #addPropertyChainAxiomStatement(Collection)
* @see #addPropertyChain(Collection)
* @see #propertyChains()
* @see #findPropertyChain(RDFNode)
* @since 1.3.0
*/
OntList<OntOPE> createPropertyChain(Collection<OntOPE> properties);
/**
* Deletes the given property chain list including all its annotations.
*
* @param list {@link Resource} can be {@link OntList} or {@link RDFList}
* @return <b>this</b> instance to allow cascading calls
* @throws OntJenaException if in the whole graph there is no property chain with the specified []-list
* @see #clearPropertyChains()
* @see #createPropertyChain(Collection)
* @since 1.3.0
*/
OntOPE removePropertyChain(Resource list) throws OntJenaException;
/**
* Returns all ranges.
* The statement pattern is {@code P rdfs:range C}, where {@code P} is this object property,
* and {@code C} is one of the return class expressions.
*
* @return {@code Stream} of {@link OntCE}s
* @since 1.4.0
*/
@Override
default Stream<OntCE> ranges() {
return objects(RDFS.range, OntCE.class);
}
/**
* Lists all direct super properties, the pattern is {@code P1 rdfs:subPropertyOf P2}.
*
* @return {@code Stream} of {@link OntOPE}s
* @see #addSuperProperty(OntOPE)
* @see OntPE#removeSuperProperty(Resource)
* @see OntPE#superProperties(boolean)
* @see #propertyChains()
* @since 1.4.0
*/
@Override
default Stream<OntOPE> superProperties() {
return objects(RDFS.subPropertyOf, OntOPE.class);
}
/**
* Returns disjoint properties (statement: {@code P1 owl:propertyDisjointWith P2}).
*
* @return {@code Stream} of {@link OntOPE}s
* @see OntNDP#disjointProperties()
* @see OntDisjoint.ObjectProperties
* @since 1.4.0
*/
@Override
default Stream<OntOPE> disjointProperties() {
return objects(OWL.propertyDisjointWith, OntOPE.class);
}
/**
* Returns all equivalent object properties
* (i.e. {@code Pi owl:equivalentProperty Pj}, where {@code Pi} - this property).
*
* @return {@code Stream} of {@link OntOPE}s.
* @see OntNDP#equivalentProperties()
* @since 1.4.0
*/
@Override
default Stream<OntOPE> equivalentProperties() {
return objects(OWL.equivalentProperty, OntOPE.class);
}
/**
* Lists all object properties from the right part of the statement {@code _:this owl:inverseOf P}.
* Please note: the return list items are not required to be {@link Inverse Inverse Object Property Expression}s.
*
* @return {@code Stream} of {@link OntOPE}s (either {@link Inverse} or {@link OntNOP})
* @see OntNOP#createInverse()
* @since 1.4.0
*/
default Stream<OntOPE> inverseProperties() {
return objects(OWL.inverseOf, OntOPE.class);
}
/**
* Returns all associated negative object property assertions.
*
* @return {@code Stream} of {@link OntNPA.ObjectAssertion}s
* @see OntNDP#negativeAssertions()
* @see OntIndividual#negativeAssertions()
*/
@Override
default Stream<OntNPA.ObjectAssertion> negativeAssertions() {
return getModel().ontObjects(OntNPA.ObjectAssertion.class).filter(a -> OntOPE.this.equals(a.getProperty()));
}
/**
* Returns all associated negative object property assertions for the specified source individual.
*
* @param source {@link OntIndividual}
* @return {@code Stream} of {@link OntNPA.ObjectAssertion}s
* @see OntNDP#negativeAssertions(OntIndividual)
* @see OntIndividual#negativeAssertions(OntProperty)
*/
default Stream<OntNPA.ObjectAssertion> negativeAssertions(OntIndividual source) {
return negativeAssertions().filter(a -> a.getSource().equals(source));
}
/**
* Finds the <b>first</b> {@code PropertyChain} logical construction
* attached to this property for the specified []-list as object.
*
* @param list {@link RDFNode}
* @return {@code Optional} around the {@link OntList ontology []-list}
* with {@link OntOPE object property expression}s as items
* @since 1.3.0
*/
default Optional<OntList<OntOPE>> findPropertyChain(RDFNode list) {
try (Stream<OntList<OntOPE>> res = propertyChains().filter(r -> Objects.equals(r, list))) {
return res.findFirst();
}
}
/**
* Deletes all property chain lists including their annotations.
*
* @return <b>this</b> instance to allow cascading calls
* @see #removePropertyChain(Resource)
* @see #createPropertyChain(Collection)
* @since 1.3.0
*/
default OntOPE clearPropertyChains() {
propertyChains().collect(Collectors.toList()).forEach(this::removePropertyChain);
return this;
}
/**
* Lists all members from the right part of statement {@code P owl:propertyChainAxiom ( P1 ... Pn )},
* where {@code P} is this property.
* Note: the result ignores repetitions, e.g. for
* {@code SubObjectPropertyOf( ObjectPropertyChain( :hasParent :hasParent ) :hasGrandparent )},
* it returns only {@code :hasParent} property.
*
* @return <b>distinct</b> {@code Stream} of all sub-{@link OntOPE object properties},
* possible empty in case of nil-list or if there is no property-chains at all
* @see #propertyChains()
* @since 1.4.0
*/
default Stream<OntOPE> fromPropertyChain() {
return propertyChains().flatMap(OntList::members).distinct();
}
/**
* Creates a property chain {@link OntList ontology list}
* and returns the statement {@code P owl:propertyChainAxiom ( P1 ... Pn )} to allow the addition of annotations.
* About RDF Graph annotation specification see, for example,
* <a href='https://www.w3.org/TR/owl2-mapping-to-rdf/#Translation_of_Annotations'>2.3.1 Axioms that Generate a Main Triple</a>.
*
* @param properties Array of {@link OntOPE}s without {@code null}s
* @return {@link OntStatement} to provide the ability to add annotations subsequently
* @see #createPropertyChain(Collection)
* @see #addPropertyChainAxiomStatement(Collection)
* @since 1.4.0
*/
default OntStatement addPropertyChainAxiomStatement(OntOPE... properties) {
return addPropertyChainAxiomStatement(Arrays.asList(properties));
}
/**
* Adds a new sub-property-of chain statement.
*
* @param properties Collection of {@link OntOPE}s
* @return {@link OntStatement} (i.e. {@code _:this owl:propertyChainAxiom ( ... )})
* to provide the ability to add annotations subsequently
* @see #createPropertyChain(Collection)
* @see #addPropertyChainAxiomStatement(OntOPE...)
* @see <a href='https://www.w3.org/TR/owl2-mapping-to-rdf/#Translation_of_Annotations'>2.3.1 Axioms that Generate a Main Triple</a>
* @since 1.4.0
*/
default OntStatement addPropertyChainAxiomStatement(Collection<OntOPE> properties) {
return createPropertyChain(properties).getRoot();
}
/**
* Creates the {@code P rdf:type owl:InverseFunctionalProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setInverseFunctional(boolean)
* @since 1.4.0
*/
default OntStatement addInverseFunctionalDeclaration() {
return addStatement(RDF.type, OWL.InverseFunctionalProperty);
}
/**
* Creates the {@code P rdf:type owl:TransitiveProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setTransitive(boolean)
* @since 1.4.0
*/
default OntStatement addTransitiveDeclaration() {
return addStatement(RDF.type, OWL.TransitiveProperty);
}
/**
* Creates the {@code P rdf:type owl:SymmetricProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setSymmetric(boolean)
* @since 1.4.0
*/
default OntStatement addSymmetricDeclaration() {
return addStatement(RDF.type, OWL.SymmetricProperty);
}
/**
* Creates the {@code P rdf:type owl:AsymmetricProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setAsymmetric(boolean)
* @since 1.4.0
*/
default OntStatement addAsymmetricDeclaration() {
return addStatement(RDF.type, OWL.AsymmetricProperty);
}
/**
* Creates the {@code P rdf:type owl:ReflexiveProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setReflexive(boolean)
* @since 1.4.0
*/
default OntStatement addReflexiveDeclaration() {
return addStatement(RDF.type, OWL.ReflexiveProperty);
}
/**
* Creates the {@code P rdf:type owl:IrreflexiveProperty} property declaration statement,
* where {@code P} is this property.
*
* @return {@link OntStatement} to allow the subsequent addition of annotations
* @see #setIrreflexive(boolean)
* @since 1.4.0
*/
default OntStatement addIrreflexiveDeclaration() {
return addStatement(RDF.type, OWL.IrreflexiveProperty);
}
/**
* Adds a property range (i.e. {@code P rdfs:range C} statement).
*
* @param range {@link OntCE}, not {@code null}
* @return {@link OntStatement} to allow processing annotations
* @see #addRange(OntCE)
*/
default OntStatement addRangeStatement(OntCE range) {
return addStatement(RDFS.range, range);
}
/**
* Adds the given property as super property returning a new statement to annotate.
* The triple pattern is {@code this rdfs:subPropertyOf property}).
*
* @param property {@link OntOPE}, not {@code null}
* @return {@link OntStatement} to allow subsequent annotations adding
*/
default OntStatement addSubPropertyOfStatement(OntOPE property) {
return addStatement(RDFS.subPropertyOf, property);
}
/**
* Adds a new inverse-of statement.
*
* @param other {@link OntOPE}, not {@code null}
* @return {@link OntStatement} to allow subsequent annotations adding
* @see #addInverseProperty(OntOPE)
* @see #inverseProperties()
* @since 1.4.0
*/
default OntStatement addInverseOfStatement(OntOPE other) {
return addStatement(OWL.inverseOf, other);
}
/**
* Creates and returns a new {@link OWL#equivalentProperty owl:equivalentProperty} statement
* with the given property as an object and this property as a subject.
*
* @param other {@link OntOPE}, not {@code null}
* @return {@link OntStatement} to allow subsequent annotations adding
* @see #addEquivalentProperty(OntOPE)
* @see #removeEquivalentProperty(Resource)
* @see OntNDP#addEquivalentPropertyStatement(OntNDP)
* @since 1.4.0
*/
default OntStatement addEquivalentPropertyStatement(OntOPE other) {
return addStatement(OWL.equivalentProperty, other);
}
/**
* Adds a disjoint object property (i.e. the {@code _:this owl:propertyDisjointWith @other} statement).
*
* @param other {@link OntOPE}, not {@code null}
* @return {@link OntStatement} to allow subsequent annotations adding
* @see #addDisjointProperty(OntOPE)
* @see #removeDisjointProperty(Resource)
* @see OntNDP#addPropertyDisjointWithStatement(OntNDP)
* @see OntDisjoint.ObjectProperties
* @since 1.4.0
*/
default OntStatement addPropertyDisjointWithStatement(OntOPE other) {
return addStatement(OWL.propertyDisjointWith, other);
}
/**
* Adds the given property as super property returning this property itself.
*
* @param property {@link OntNDP}, not {@code null}
* @return <b>this</b> instance to allow cascading calls
* @see OntPE#removeSuperProperty(Resource)
* @since 1.4.0
*/
default OntOPE addSuperProperty(OntOPE property) {
addSubPropertyOfStatement(property);
return this;
}
/**
* Adds a statement with the {@link RDFS#range} as predicate
* and the specified {@link OntCE class expression} as an object.
*
* @param range {@link OntCE}, not {@code null}
* @return <b>this</b> instance to allow cascading calls
* @see #addRangeStatement(OntCE)
*/
default OntOPE addRange(OntCE range) {
addRangeStatement(range);
return this;
}
/**
* Adds a statement with the {@link RDFS#domain} as predicate
* and the specified {@link OntCE class expression} as an object.
*
* @param ce {@link OntCE}, not {@code null}
* @return <b>this</b> instance to allow cascading calls
* @see #addDomainStatement(OntCE)
*/
@Override
default OntOPE addDomain(OntCE ce) {
addDomainStatement(ce);
return this;
}
/**
* Adds a new {@link OWL#equivalentProperty owl:equivalentProperty} statement.
*
* @param other {@link OntOPE}, not {@code null}
* @return <b>this</b> instance to allow cascading calls
* @see #addEquivalentPropertyStatement(OntOPE)
* @see OntDOP#removeEquivalentProperty(Resource)
* @see OntNDP#addEquivalentProperty(OntNDP)
*/
default OntOPE addEquivalentProperty(OntOPE other) {
addEquivalentPropertyStatement(other);
return this;
}
/**
* Adds a new {@link OWL#propertyDisjointWith owl:propertyDisjointWith} statement
* for this and the specified property.
*
* @param other {@link OntNDP}, not {@code null}
* @return {@link OntNDP} <b>this</b> instance to allow cascading calls
* @see #addPropertyDisjointWithStatement(OntOPE)
* @see OntNDP#addDisjointProperty(OntNDP)
* @see OntDOP#removeDisjointProperty(Resource)
* @see OntDisjoint.ObjectProperties
* @since 1.4.0
*/
default OntOPE addDisjointProperty(OntOPE other) {
addPropertyDisjointWithStatement(other);
return this;
}
/**
* Adds a new inverse-of statement, returns this property instance.
*
* @param other {@link OntOPE}, not {@code null}
* @return <b>this</b> instance to allow cascading calls
* @see #addInverseOfStatement(OntOPE)
* @see #removeInverseProperty(Resource)
* @since 1.4.0
*/
default OntOPE addInverseProperty(OntOPE other) {
addInverseOfStatement(other);
return this;
}
/**
* Adds a new sub-property-of chain statement and returns this object itself.
* Note: the method saves a collection order with possible duplicates.
*
* @param properties an {@code Array} of {@link OntOPE object properties}
* @return <b>this</b> instance to allow cascading calls
* @see #addPropertyChainAxiomStatement(Collection)
* @see #addPropertyChain(Collection)
* @since 1.4.0
*/
default OntOPE addPropertyChain(OntOPE... properties) {
return addPropertyChain(Arrays.asList(properties));
}
/**
* Adds a new sub-property-of chain statement and returns this object itself.
* Note: the method saves a collection order with possible duplicates.
*
* @param properties a {@code Collection} of {@link OntOPE object properties}
* @return <b>this</b> instance to allow cascading calls
* @see #addPropertyChainAxiomStatement(Collection)
* @see #addPropertyChain(OntOPE...)
* @since 1.4.0
*/
default OntOPE addPropertyChain(Collection<OntOPE> properties) {
createPropertyChain(properties);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE removeSuperProperty(Resource property) {
remove(RDFS.subPropertyOf, property);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE removeEquivalentProperty(Resource property) {
remove(OWL.equivalentProperty, property);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE removeDisjointProperty(Resource property) {
remove(OWL.propertyDisjointWith, property);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE removeDomain(Resource domain) {
remove(RDFS.domain, domain);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE removeRange(Resource range) {
remove(RDFS.range, range);
return this;
}
/**
* Removes the statement with the predicate {@link OWL#inverseOf owl:inverseOf}
* and the given object property as object.
* If the argument is {@code null}, all {@code owl:inverseOf} statements will be removed for this object property.
* No-op in case there is no {@code owl:inverseOf} statements.
*
* @param other {@link OntOPE} or {@code null} to remove all {@code owl:inverseOf} statements
* @return <b>this</b> instance to allow cascading calls
* @see #addInverseProperty(OntOPE)
* @since 1.4.0
*/
default OntOPE removeInverseProperty(Resource other) {
remove(OWL.inverseOf, other);
return this;
}
/**
* {@inheritDoc}
*/
@Override
default OntOPE setFunctional(boolean functional) {
if (functional) {
addFunctionalDeclaration();
} else {
remove(RDF.type, OWL.FunctionalProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:InverseFunctionalProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param inverseFunctional if {@code true} the property must be inverse-functional
* @return <b>this</b> instance to allow cascading calls
* @see #addInverseFunctionalDeclaration()
*/
default OntOPE setInverseFunctional(boolean inverseFunctional) {
if (inverseFunctional) {
addInverseFunctionalDeclaration();
} else {
remove(RDF.type, OWL.InverseFunctionalProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:TransitiveProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param transitive if {@code true} the property must be transitive
* @return <b>this</b> instance to allow cascading calls
* @see #addTransitiveDeclaration()
*/
default OntOPE setTransitive(boolean transitive) {
if (transitive) {
addTransitiveDeclaration();
} else {
remove(RDF.type, OWL.TransitiveProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:SymmetricProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param symmetric if {@code true} the property must be symmetric
* @return <b>this</b> instance to allow cascading calls
* @see #addSymmetricDeclaration()
*/
default OntOPE setSymmetric(boolean symmetric) {
if (symmetric) {
addSymmetricDeclaration();
} else {
remove(RDF.type, OWL.SymmetricProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:AsymmetricProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param asymmetric if {@code true} the property must be asymmetric
* @return <b>this</b> instance to allow cascading calls
* @see #addAsymmetricDeclaration()
*/
default OntOPE setAsymmetric(boolean asymmetric) {
if (asymmetric) {
addAsymmetricDeclaration();
} else {
remove(RDF.type, OWL.AsymmetricProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:ReflexiveProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param reflexive if {@code true} the property must be reflexive
* @return <b>this</b> instance to allow cascading calls
* @see #addReflexiveDeclaration()
*/
default OntOPE setReflexive(boolean reflexive) {
if (reflexive) {
addReflexiveDeclaration();
} else {
remove(RDF.type, OWL.ReflexiveProperty);
}
return this;
}
/**
* Adds or removes the {@code P rdf:type owl:IrreflexiveProperty} statement depending on the given flag
* and returns this property to allow cascading calls.
* Note: the statement is removed along with all its annotations.
*
* @param irreflexive if {@code true} the property must be irreflexive
* @return <b>this</b> instance to allow cascading calls
* @see #addIrreflexiveDeclaration()
*/
default OntOPE setIrreflexive(boolean irreflexive) {
if (irreflexive) {
addIrreflexiveDeclaration();
} else {
remove(RDF.type, OWL.IrreflexiveProperty);
}
return this;
}
/**
* Finds the <b>first</b> object property
* from the right part of the statements {@code _:x owl:inverseOf PN} or {@code P1 owl:inverseOf P2}.
* Here {@code _:x} is an anonymous object property expression (i.e. {@link Inverse Inverse Object Property}),
* {@code PN} is a {@link OntNOP named object property}
* and {@code P1}, {@code P2} are any object property expressions.
* What exactly is the first statement is defined at the level of model; in general it is unpredictable.
*
* @return {@code Optional} of {@link OntOPE}
* @see #inverseProperties()
* @see Inverse#getDirect()
* @since 1.4.0
*/
default Optional<OntOPE> findInverseProperty() {
try (Stream<OntOPE> res = inverseProperties()) {
return res.findFirst();
}
}
/**
* @return {@code true} iff it is an inverse functional property
*/
default boolean isInverseFunctional() {
return hasType(OWL.InverseFunctionalProperty);
}
/**
* @return {@code true} iff it is a transitive property
*/
default boolean isTransitive() {
return hasType(OWL.TransitiveProperty);
}
/**
* @return {@code true} iff it is a symmetric property
*/
default boolean isSymmetric() {
return hasType(OWL.SymmetricProperty);
}
/**
* @return {@code true} iff it is an asymmetric property
*/
default boolean isAsymmetric() {
return hasType(OWL.AsymmetricProperty);
}
/**
* @return {@code true} iff it is a reflexive property
*/
default boolean isReflexive() {
return hasType(OWL.ReflexiveProperty);
}
/**
* @return {@code true} iff it is an irreflexive property
*/
default boolean isIrreflexive() {
return hasType(OWL.IrreflexiveProperty);
}
/**
* Represents a <a href="http://www.w3.org/TR/owl2-syntax/#Inverse_Object_Properties">ObjectInverseOf</a>.
* Anonymous triple {@code _:x owl:inverseOf PN} which is also object property expression.
*/
interface Inverse extends OntOPE {
/**
* Returns a named object property companion.
* Every {@link Inverse} property has its own {@link OntNOP} property.
* The triple pattern is {@code _:x owl:inverseOf PN}.
*
* @return {@link OntNDP}, not {@code null}
*/
OntNOP getDirect();
}
}
| 37.280503
| 308
| 0.658546
|
713a2c12f424d9eac16fb7fefdd3408a3c50bbb8
| 2,966
|
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
/**
*
*/
package diskRecovery;
import hydra.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import util.TestException;
import util.TestHelper;
/** Class containing methods so the test can configure when certain classes
* (such as cache listeners and cache writers should be allowed to be
* instantiated and when they should not. This is used by disk conversion tests
* to ensure that the disk conversion tool is not instantiating certain classes.
* @author lynn
*
*/
public class InstantiationHelper {
public static final String wellKnownFileName = "allowInstaniation.ser";
/** Return whether instantiation of certain classes is currently allowed or not.
*
* @return true if instantiation is allowed, false otherwise.
*/
public static boolean allowInstantiation() {
try {
FileInputStream fis = new FileInputStream(wellKnownFileName);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean allowInstantiation = ois.readBoolean();
return allowInstantiation;
} catch (FileNotFoundException e) {
// if the file is not found, default to allow instantiation
return true;
} catch (IOException e) {
throw new TestException(TestHelper.getStackTrace(e));
}
}
/** Set whether instantiation of certain classes is allowed or not.
*
* @param aVal true if instantiation is allowed, false otherwise.
*/
public static void setAllowInstantiation(boolean aVal) {
try {
FileOutputStream fos = new FileOutputStream(wellKnownFileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBoolean(aVal);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
throw new TestException(TestHelper.getStackTrace(e));
} catch (IOException e) {
throw new TestException(TestHelper.getStackTrace(e));
}
// verify the setting worked
boolean allow = allowInstantiation();
if (allow != aVal) {
throw new TestException("Test problem; unable to retrieve allowInstantion from file");
}
Log.getLogWriter().info("Set allowInstantiation to " + aVal);
}
}
| 32.955556
| 92
| 0.723196
|
bc2476bb944527240b96c611c926d2fee74ba139
| 1,421
|
package kamoncust.application.com.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import kamoncust.application.com.kamoncust.MainActivity;
import kamoncust.application.com.kamoncust.R;
public class MoreFragment extends Fragment {
public static TextView detail_menu;
public static LinearLayout retry;
public static Button btnReload;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.fragment_more, container, false);
detail_menu = (TextView) rootView.findViewById(R.id.detail_menu);
retry = (LinearLayout) rootView.findViewById(R.id.loadMask);
btnReload = (Button) rootView.findViewById(R.id.btnReload);
btnReload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
((MainActivity) getActivity()).prosesLoadDetailMenu();
}
});
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
((MainActivity) getActivity()).prosesLoadDetailMenu();
}
}
| 28.42
| 100
| 0.786066
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.