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 |
|---|---|---|---|---|---|
71bab0649b51c181115c37afa6ab71daa77af10a | 976 | package com.github.czyzby.lml.vis.parser.impl.tag;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.github.czyzby.lml.parser.LmlParser;
import com.github.czyzby.lml.parser.tag.LmlActorBuilder;
import com.github.czyzby.lml.parser.tag.LmlTag;
import com.kotcrab.vis.ui.widget.color.ExtendedColorPicker;
/** Handles {@link ExtendedColorPicker} actors. Works like {@link BasicColorPickerLmlTag}, except it contains more
* widgets and makes it easier to fully customize the chosen color. Mapped to "extendedColorPicker", "extendedPicker".
*
* @author MJ */
public class ExtendedColorPickerLmlTag extends BasicColorPickerLmlTag {
public ExtendedColorPickerLmlTag(final LmlParser parser, final LmlTag parentTag, final StringBuilder rawTagData) {
super(parser, parentTag, rawTagData);
}
@Override
protected Actor getNewInstanceOfActor(final LmlActorBuilder builder) {
return new ExtendedColorPicker(builder.getStyleName(), null);
}
}
| 42.434783 | 118 | 0.782787 |
8710515d823d0afb033d2478d38dbbe9c0b8b6b5 | 13,270 | package com.jlpt.retheviper.test.controller;
import com.jlpt.retheviper.test.bean.Problem;
import com.jlpt.retheviper.test.bean.Score;
import com.jlpt.retheviper.test.constant.Subject;
import com.jlpt.retheviper.test.gui.ListenTestStage;
import com.jlpt.retheviper.test.service.StudentManagementService;
import com.jlpt.retheviper.test.service.TestManagementService;
import com.jlpt.retheviper.test.util.CreateAlert;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
public class ListenTestViewControl implements Initializable {
// 청해 시험용 컨트롤러
public static MediaPlayer mediaPlayer; // mp3 플레이어
public static int timerSetting = 0; // 시험 시간 세팅
@FXML
private final ToggleGroup group = new ToggleGroup();
private final TestManagementService service = TestManagementService.getInstance();
private final List<Problem> tList = service.getProblem(Subject.LISTEN);
@FXML
private RadioButton firstChoice_radio, secondChoice_radio, thirdChoice_radio, forthChoice_radio;
@FXML
private TextArea passageArea;
@FXML
private Button startTestButton, previousProblemButton, nextProblemButton, submitAnswerButton, Mp3PlayButton;
@FXML
private Label problemNumberLabel, mp3CurrentTime, mp3Length, totalProblemLabel, correctAnswerLabel,
wrongAnswerLabel, skippedAnswerLabel, timer;
@FXML
private ProgressBar timeProgress, mp3Progress;
private int problemNumber = 0;
private int selectedAnswer = 0;
private String theImg = ""; // 이미지 파일 이름
private String theMp3 = ""; // mp3 파일 이름
private Media media; // mp3에 담을 미디어
private final Score score = Score.builder().subject(Subject.LISTEN).build(); // 임시로 담을 성적
private int correctAnswer = 0; // 정답 기록용
private int wrongAnswer = 0; // 오답 기록용
private int skippedAnswer = 0; // 넘긴 문제 기록용
private int settedTime = 0; // 설정된 시험 시간
private boolean getStarted = false; // MP3 세팅 확인용
public static MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public static void setMediaPlayer(MediaPlayer mediaPlayer) {
ListenTestViewControl.mediaPlayer = mediaPlayer;
}
private void startTest() { // 시험 시작
switch (this.startTestButton.getText()) {
case "시작":
this.startTestButton.setText("중단");
if (this.tList.size() > this.problemNumber) {
setProblem(problemNumber);
setTimer();
startTimerProgress();
}
break;
case "중단":
this.startTestButton.setText("시작");
final Optional<ButtonType> result = CreateAlert.withoutHeader(AlertType.CONFIRMATION, "정보",
"성적을 저장하고 끝내시겠습니까?\r\n(기존의 성적을 덮어씁니다)");
result.ifPresent(this::exiting);
break;
}
}
private void setTimer() { // 시험 시간 표시
switch (timerSetting) {
case 0:
timer.setText("50분");
settedTime = 3000;
break;
case 1:
timer.setText("35분");
settedTime = 2100;
break;
case 2:
timer.setText("20분");
settedTime = 1200;
break;
}
}
private void startTimerProgress() { // 진행에 따른 경과 표시
// 시험 시간 측정용
final Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
for (int i = 0; i <= settedTime; i++) {
updateProgress(i, settedTime);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
return null;
}
};
timeProgress.progressProperty().bind(task.progressProperty());
// task 설정
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
private void setProblem(final int index) { // 문제를 세팅
problemNumberLabel.setText(
this.tList.get(index).getPNumber() + "-"
+ this.tList.get(index).getSubNumber());
passageArea.setText(tList.get(index).getPassage());
firstChoice_radio.setText("1번: " + this.tList.get(index).getFirstChoice());
secondChoice_radio.setText("2번: " + this.tList.get(index).getSecondChoice());
thirdChoice_radio.setText("3번: " + this.tList.get(index).getThirdChoice());
forthChoice_radio.setText("4번: " + this.tList.get(index).getForthChoice());
if (!this.tList.get(index).getImgSource().equals("nah")
&& this.tList.get(index).getImgSource() != null) {
theImg = this.tList.get(index).getImgSource();
// 이미지 파일이 있을 경우 팝업에 표시
imagePopupWindowShow();
}
final Problem forMp3 = this.tList.get(index);
try { // mp3 파일을 불러옴
if (theMp3 == null || !theMp3.equals("mp3/" + forMp3.getMp3Source())) {
if (getStarted && mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING
&& problemNumber < this.tList.size()) {
mp3CurrentTime.setText("00:00");
mediaPlayer.stop();
changeMp3PlayButton();
}
theMp3 = "mp3/" + forMp3.getMp3Source();
media = new Media(new File(theMp3).toURI().toString());
mediaPlayer = new MediaPlayer(media);
getStarted = true;
mediaPlayer.setOnReady(() -> {
double millis = mediaPlayer.getTotalDuration().toMillis();
int totalSeconds = (int) (millis / 1000) % 60;
int totalMinutes = (int) mediaPlayer.getTotalDuration().toMinutes();
mp3Length.setText((totalMinutes < 10 ? "0" : "") + totalMinutes + ":" + totalSeconds);
mediaPlayer.currentTimeProperty().addListener((observable, oldValue, newValue) -> {
double progress = mediaPlayer.getCurrentTime().toSeconds()
/ mediaPlayer.getTotalDuration().toSeconds();
mp3Progress.setProgress(progress);
int seconds = (int) (mediaPlayer.getCurrentTime().toMillis() / 1000) % 60;
int minutes = (int) mediaPlayer.getCurrentTime().toMinutes();
mp3CurrentTime.setText((minutes < 10 ? "0" : "") + minutes + ":"
+ (seconds < 10 ? "0" : "") + seconds);
});
});
mediaPlayer.setOnEndOfMedia(() -> {
mp3Progress.setProgress(1.0);
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void imagePopupWindowShow() { // 첨부 이미지를 띄우는 팝업
final ImageView imageView = new ImageView(new Image(new File("img/" + theImg).toURI().toString()));
final ScrollPane pane = new ScrollPane();
final Stage stage = new Stage();
imageView.setFitWidth(735);
imageView.setPreserveRatio(true);
imageView.setSmooth(true);
pane.setContent(imageView);
stage.setScene(new Scene(pane, 750, 600));
stage.setTitle("참고 이미지");
stage.setOnCloseRequest(e -> {
stage.close();
});
stage.showAndWait();
}
private void submitAnswer() { // 선택지에 따른 답을 입력
if (startTestButton.getText().equals("시작")) {
CreateAlert.withoutHeader(AlertType.ERROR, "오류", "먼저 시작 버튼을 눌러주세요");
} else if (tList.size() > problemNumber) {
if (firstChoice_radio.isSelected()) {
selectedAnswer = 1;
} else if (secondChoice_radio.isSelected()) {
selectedAnswer = 2;
} else if (thirdChoice_radio.isSelected()) {
selectedAnswer = 3;
} else if (forthChoice_radio.isSelected()) {
selectedAnswer = 4;
} else if (!firstChoice_radio.isSelected() && !secondChoice_radio.isSelected()
&& !thirdChoice_radio.isSelected() && !forthChoice_radio.isSelected()) {
CreateAlert.withoutHeader(AlertType.ERROR, "오류", "제출할 답을 선택해주세요");
}
compareWithProblem();
}
}
private void compareWithProblem() { // 입력한 답을 정답과 비교후 기록
if (tList.get(problemNumber).getAnswer() == selectedAnswer) {
correctAnswer++;
score.setCorrectAnswer(correctAnswer);
totalProblemLabel.setText(correctAnswer + wrongAnswer + "");
correctAnswerLabel.setText(correctAnswer + "");
CreateAlert.withoutHeader(AlertType.INFORMATION, "아타리", "정답입니다");
} else {
wrongAnswer++;
score.setWrongAnswer(wrongAnswer);
totalProblemLabel.setText(correctAnswer + wrongAnswer + "");
wrongAnswerLabel.setText(wrongAnswer + "");
CreateAlert.withoutHeader(AlertType.ERROR, "잔넨", "오답입니다");
}
if (tList.size() > problemNumber + 1) {
problemNumber++;
setProblem(problemNumber);
} else {
final Optional<ButtonType> result = CreateAlert.withHeader(AlertType.CONFIRMATION, "정보", "마지막 문제",
"성적을 저장하고 끝내시겠습니까?\r\n(기존의 성적을 덮어씁니다)");
result.ifPresent(this::exiting);
}
}
private void goBack() { // 이전 문제로 가기
if (startTestButton.getText().equals("시작")) {
CreateAlert.withoutHeader(AlertType.ERROR, "오류", "먼저 시작 버튼을 눌러주세요");
} else {
if ((problemNumber - 1) != -1) {
--skippedAnswer;
setSkip(skippedAnswer);
--problemNumber;
setProblem(problemNumber);
} else {
CreateAlert.withoutHeader(AlertType.INFORMATION, "정보", "더 이상 뒤로 갈 수 없습니다");
}
}
}
private void goNext() { // 다음 문제로 가기
if (startTestButton.getText().equals("시작")) {
CreateAlert.withoutHeader(AlertType.ERROR, "오류", "먼저 시작 버튼을 눌러주세요");
} else {
if ((problemNumber + 1) < this.tList.size()) {
++skippedAnswer;
setSkip(skippedAnswer);
++problemNumber;
setProblem(problemNumber);
} else {
CreateAlert.withoutHeader(AlertType.INFORMATION, "정보", "더 이상 앞으로 갈 수 없습니다");
}
}
}
private void setSkip(final int skippedAnswer) {
score.setSkippedAnswer(skippedAnswer);
this.skippedAnswerLabel.setText(String.valueOf(this.skippedAnswer));
}
private void exiting(final ButtonType type) {
if (type == ButtonType.OK) {
final StudentManagementService sm = StudentManagementService.getInstance();
sm.recordScore(score);
ListenTestStage.getStage().hide();
}
}
private void playMp3() { // mp3 재생 버튼 클릭시
if (startTestButton.getText().equals("시작")) {
CreateAlert.withoutHeader(AlertType.ERROR, "오류", "먼저 시작 버튼을 눌러주세요");
} else {
changeMp3PlayButton();
if (Mp3PlayButton.getText().equals("■")) {
mediaPlayer.play();
} else if (Mp3PlayButton.getText().equals("▶")) {
mediaPlayer.pause();
}
}
}
private void changeMp3PlayButton() { // mp3 버튼 세팅
if (mediaPlayer != null && !(mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING)) {
Mp3PlayButton.setText("■");
mediaPlayer.setOnEndOfMedia(mediaPlayer::stop);
} else {
Mp3PlayButton.setText("▶");
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
this.firstChoice_radio.setToggleGroup(this.group);
this.secondChoice_radio.setToggleGroup(this.group);
this.thirdChoice_radio.setToggleGroup(this.group);
this.forthChoice_radio.setToggleGroup(this.group);
this.startTestButton.setOnAction(event -> startTest());
this.submitAnswerButton.setOnAction(event -> submitAnswer());
this.previousProblemButton.setOnAction(event -> goBack());
this.nextProblemButton.setOnAction(event -> goNext());
this.Mp3PlayButton.setOnAction(event -> playMp3());
}
}
| 41.598746 | 113 | 0.56526 |
5ca705f3a16496d4b9710c5e9c046a0cda90ec68 | 2,947 | package io.io.minicmd;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
/**
* @author Ramil Bischev
* @since 20.04.2020
*
* Please solve the following puzzle which simulates generic directory structures.
* The solution should be directory agnostic.
* Be succinct yet readable. You should not exceed more than 200 lines.
* Consider adding comments and asserts to help the understanding.
* Code can be compiled with javac Directory.java
* Code should be executed as: java -ea Directory (-ea option it's to enabled the assert)
*/
public class Shell {
/**
* The list contains current path as: [usr], [local], etc.
*/
private LinkedList<String> path = new LinkedList<>();
/**
* Changes current path by changing items in list.
*
* @param path Given string path.
* @return This shell object.
*/
Shell cd(final String path) {
String p = this.normalizePath(path);
this.clearIfPathStartsFromRoot(p);
List<String> dirs = this.getElementsExcludeRedundant(p);
for (String element : dirs) {
this.parseElement(element);
}
return this;
}
/**
* Replaces all many-time symbols like "///" to one "/" symbol.
*
* @param path Not-normalized path.
* @return Normalized path.
*/
private String normalizePath(String path) {
return path.replaceAll("/+", "/");
}
/**
* Get elements from given path-string, using "/" delimiter.
* Delete empty elements (length == 0) and elements not changing directory (".").
*
* @param path Path string.
* @return Array of elements from path.
*/
private List<String> getElementsExcludeRedundant(String path) {
return Arrays.stream(path.split("/"))
.filter(s -> s.length() > 0 && !s.equals("."))
.collect(Collectors.toList());
}
/**
* Checks if given path defines path from root (starts with '/' symbol.
* If so - clears our current path.
*
* @param path String path.
*/
private void clearIfPathStartsFromRoot(String path) {
if (path.startsWith("/")) {
this.path.clear();
}
}
/**
* Analyzes element and changes path according to analyze result.
*
* @param element Element to analyze.
*/
private void parseElement(String element) {
if (element.equals("..") && this.path.size() > 0) {
this.path.removeLast();
} else {
this.path.addLast(element);
}
}
/**
* Print saved path.
*
* @return String path.
*/
public String path() {
StringJoiner result = new StringJoiner("/", "/", "");
for (String dir : this.path) {
result.add(dir);
}
return result.toString();
}
}
| 28.066667 | 90 | 0.594503 |
47bd1124b8e936d0e1fef52713f068385e515ea9 | 1,503 | package uq.deco2800.singularity.common.representations.realtime;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import uq.deco2800.singularity.common.SessionType;
public class RealTimeSessionConfiguration {
@JsonProperty
private String sessionID;
@JsonProperty
private int port;
@JsonProperty
private SessionType session;
@JsonIgnore
public boolean isValid() {
if (port != 0 && (port < 1024 || port > 65535 || session == null)) {
return false;
}
return true;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(int port) {
this.port = port;
}
/**
* @return the session
*/
public SessionType getSession() {
return session;
}
/**
* @param session the session to set
*/
public void setSession(SessionType session) {
this.session = session;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String namedString = (sessionID != null) ? " <NAME=" + String.valueOf(sessionID) + ">" : "";
return "RealTimeSessionConfiguration [port=" + port
+ ", session=" + session + "]" + namedString;
}
/**
* Gets the session ID of this session
*/
public String getSessionID() {
return sessionID;
}
/**
* Sets the session ID the session ID to set
* @param sessionID
*/
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
}
| 18.7875 | 94 | 0.671989 |
a442d35cd2037b9fd9cec26887f1630acf937bab | 2,288 | /**
* 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.blur.manager.writer;
import java.io.IOException;
import java.util.Iterator;
import org.apache.blur.analysis.FieldManager;
import org.apache.blur.thrift.generated.Record;
import org.apache.lucene.document.Field;
public class RecordToDocumentIterable implements Iterable<Iterable<Field>> {
private long _count;
private final IterableRow _row;
private final FieldManager _fieldManager;
public RecordToDocumentIterable(IterableRow row, FieldManager fieldManager) {
_row = row;
_fieldManager = fieldManager;
}
@Override
public Iterator<Iterable<Field>> iterator() {
final Iterator<Record> iterator = _row.iterator();
return new Iterator<Iterable<Field>>() {
private long count = 0;
@Override
public boolean hasNext() {
boolean hasNext = iterator.hasNext();
if (!hasNext) {
_count = count;
}
return hasNext;
}
@Override
public Iterable<Field> next() {
Record record = iterator.next();
count++;
try {
return convert(record);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void remove() {
throw new RuntimeException("Not Supported.");
}
};
}
public Iterable<Field> convert(Record record) throws IOException {
return _fieldManager.getFields(_row.getRowId(), record);
}
public long count() {
return _count;
}
}
| 28.962025 | 79 | 0.688811 |
0f7d32619bfdc8ed320deccd80fd73fd257b14a6 | 4,759 | package com.sxu.smartpicture.choosepicture;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import com.sxu.permission.CheckPermission;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Freeman
* @date 17/11/8
*/
public class ChoosePhotoManager {
private Uri iconUri;
private Uri cropImageUri;
private File imageFile;
private boolean autoCrop = false;
private OnChoosePhotoListener listener;
private static final int REQUEST_CODE_TAKE_PHOTO = 1001;
private static final int REQUEST_CODE_CHOOSE_IMAGE = 1002;
private static final int REQUEST_CODE_CROP_IMAGE = 1003;
private static ChoosePhotoManager instance;
private ChoosePhotoManager() {
}
public static ChoosePhotoManager getInstance() {
if (instance == null) {
instance = new ChoosePhotoManager();
}
return instance;
}
public void choosePhotoFromAlbum(Activity activity) {
choosePhotoFromAlbum(activity, false);
}
public void choosePhotoFromAlbum(Activity activity, boolean autoCrop) {
this.autoCrop = autoCrop;
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, REQUEST_CODE_CHOOSE_IMAGE);
}
}
public void takePicture(Activity activity) {
takePicture(activity, false);
}
@CheckPermission(permissions = {Manifest.permission.CAMERA}, permissionDesc = "此功能需要相机权限才可使用")
public void takePicture(Activity activity, boolean autoCrop) {
this.autoCrop = autoCrop;
Date date = new Date();
String fileName = "IMG_" + new SimpleDateFormat("yyyyMMddHHmmss").format(date);
Log.i("out", "rootPath=" + Environment.getExternalStorageDirectory() + " cahce==" + activity.getCacheDir());
imageFile = new File(activity.getExternalCacheDir() + fileName);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
iconUri = Uri.fromFile(imageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, iconUri);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
}
}
public void cropPhoto(Activity activity, Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
// 以Uri的方式传递照片
File cropFile = new File(activity.getExternalCacheDir() + "crop_image.jpg");
cropImageUri = Uri.fromFile(cropFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// return-data=true传递的为缩略图,小米手机默认传递大图,所以会导致onActivityResult调用失败
intent.putExtra("return-data", false);
intent.putExtra("noFaceDetection", false);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}
}
public void onActivityResult(Activity activity, int requestCode, Intent intent) {
if(intent != null) {
switch (requestCode) {
case REQUEST_CODE_TAKE_PHOTO:
if (autoCrop && imageFile.length() != 0) {
cropPhoto(activity, iconUri);
}
if (listener != null && imageFile.length() != 0) {
listener.choosePhotoFromCamera(iconUri);
}
break;
case REQUEST_CODE_CHOOSE_IMAGE:
iconUri = intent.getData();
if (autoCrop && iconUri != null) {
cropPhoto(activity, iconUri);
}
if (listener != null) {
listener.choosePhotoFromAlbum(iconUri);
}
break;
case REQUEST_CODE_CROP_IMAGE:
if (listener != null) {
listener.cropPhoto(cropImageUri);
}
break;
default:
break;
}
} else {
// 关闭拍照界面或拍照完成后都会调用
if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
if (autoCrop && imageFile.length() != 0) {
cropPhoto(activity, iconUri);
}
if (listener != null && imageFile.length() != 0) {
listener.choosePhotoFromCamera(iconUri);
}
}
}
}
/**
* 选择照片或者拍照后是否需要裁剪
* @param autoCrop
*/
public void setAutoCrop(boolean autoCrop) {
this.autoCrop = autoCrop;
}
public void setChoosePhotoListener(OnChoosePhotoListener listener) {
this.listener = listener;
}
}
| 29.930818 | 110 | 0.728304 |
c19b9be844d120487b98b77795116254f507fb23 | 202 | package com.mylhyl.circledialog.view.listener;
/**
* Created by hupei on 2018/6/28 11:23.
*/
public interface OnInputCounterChangeListener {
String onCounterChange(int maxLen, int currentLen);
}
| 22.444444 | 55 | 0.757426 |
48bedcde990586473b1b2c809963651e58a6c65c | 4,105 | package pt.ipp.estg.covidresolvefoodapp.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import pt.ipp.estg.covidresolvefoodapp.Model.ReviewFirestore;
import pt.ipp.estg.covidresolvefoodapp.R;
import pt.ipp.estg.covidresolvefoodapp.Retrofit.Model.RestaurantInfoRetro;
import pt.ipp.estg.covidresolvefoodapp.Retrofit.ZomatoAPI;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class UserReviewProfileAdapter extends FirestoreRecyclerAdapter<ReviewFirestore, UserReviewProfileAdapter.UserReviewProfileViewHolder> {
private FirebaseAuth mAuth;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference userRef = db.collection("User");
public UserReviewProfileAdapter(@NonNull FirestoreRecyclerOptions<ReviewFirestore> options) {
super(options);
}
@NonNull
@Override
public UserReviewProfileViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
this.mAuth = FirebaseAuth.getInstance();
// Get layout inflater from context
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_review, parent, false);
return new UserReviewProfileViewHolder(v);
}
@Override
protected void onBindViewHolder(@NonNull UserReviewProfileViewHolder viewHolder, int position, @NonNull ReviewFirestore reviewFirestore) {
TextView mNameRestaurant = viewHolder.mNameRestaurant;
this.getAPIZomato().getRestaurant(reviewFirestore.getIdRestaurant()).enqueue(new Callback<RestaurantInfoRetro>() {
@Override
public void onResponse(Call<RestaurantInfoRetro> call, Response<RestaurantInfoRetro> response) {
mNameRestaurant.setText(response.body().getName());
}
@Override
public void onFailure(Call<RestaurantInfoRetro> call, Throwable t) {
System.out.println(call.request());
}
});
RatingBar mRatingBar = viewHolder.mRatingBar;
mRatingBar.setRating(reviewFirestore.getAvaliation());
TextView mNotaReview = viewHolder.mNotaReview;
mNotaReview.setText(String.valueOf(reviewFirestore.getAvaliation()));
TextView mContentMessage = viewHolder.mContentMessage;
mContentMessage.setText(reviewFirestore.getContentReview());
}
public class UserReviewProfileViewHolder extends RecyclerView.ViewHolder {
public TextView mNameRestaurant;
public RatingBar mRatingBar;
public TextView mNotaReview;
public TextView mContentMessage;
public UserReviewProfileViewHolder(View itemView) {
super(itemView);
this.mNameRestaurant = itemView.findViewById(R.id.anonymous_review);
this.mRatingBar = itemView.findViewById(R.id.estrelas_review);
this.mNotaReview = itemView.findViewById(R.id.nota_review);
this.mContentMessage = itemView.findViewById(R.id.content_message_review);
}
}
private Retrofit getRetrofitZomatoAPI() {
return new Retrofit.Builder()
.baseUrl("https://developers.zomato.com/api/v2.1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private ZomatoAPI getAPIZomato() {
return this.getRetrofitZomatoAPI().create(ZomatoAPI.class);
}
}
| 38.009259 | 143 | 0.738124 |
8af58cc6e2d05dcce4f26b2dfc3dbf77ab218b0a | 1,330 | package com.vaani.ctci.chap4treegraph;
import com.vaani.dsa.ds.core.tree.BinaryTreeNode;
/**
* You have two very large binary trees: T1, with millions of nodes, and T2,
* with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of
* T1. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the
* subtree of n is identical to T2. That is, if you cut off the tree at node n,
* the two trees would be identical.
*/
// O(1) space, O(mn) time
public class Question8 {
public boolean isSub(BinaryTreeNode haystack, BinaryTreeNode needle) {
if (haystack == null) {
return false;
}
if (needle == null) {
return true;
}
if (haystack.value == needle.value) { // root match
if (match(haystack, needle)) {
return true;
}
}
return isSub(haystack.left, needle) || isSub(haystack.right, needle);
}
private boolean match(BinaryTreeNode haystack, BinaryTreeNode needle) {
if (haystack == null && needle == null) {
return true;
}
if (haystack.value != needle.value) {
return false;
}
// compare left and right
return match(haystack.left, needle.left) && match(haystack.right, needle.right);
}
}
| 30.930233 | 88 | 0.603759 |
8d266dc97c50d2d258cb8ef53d0563497fdf3ff2 | 3,136 | package edu.jhu.thrax.hadoop.jobs;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.AlignedRuleWritable;
import edu.jhu.thrax.hadoop.datatypes.Annotation;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.extraction.ExtractionCombiner;
import edu.jhu.thrax.hadoop.extraction.ExtractionReducer;
import edu.jhu.thrax.util.Vocabulary;
public class ParaphraseCountAggregationJob implements ThraxJob {
private static HashSet<Class<? extends ThraxJob>> prereqs =
new HashSet<Class<? extends ThraxJob>>();
public Job getJob(Configuration conf) throws IOException {
Job job = Job.getInstance(conf, "count-aggregate");
job.setJarByClass(ExtractionReducer.class);
job.setMapperClass(CountAggregationMapper.class);
job.setCombinerClass(ExtractionCombiner.class);
job.setReducerClass(ExtractionReducer.class);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapOutputKeyClass(AlignedRuleWritable.class);
job.setMapOutputValueClass(Annotation.class);
job.setOutputKeyClass(RuleWritable.class);
job.setOutputValueClass(Annotation.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setSortComparatorClass(AlignedRuleWritable.RuleYieldComparator.class);
job.setPartitionerClass(AlignedRuleWritable.RuleYieldPartitioner.class);
FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.work-dir") + "count-pivoted"));
int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize * 20);
int numReducers = conf.getInt("thrax.reducers", 4);
job.setNumReduceTasks(numReducers);
FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "rules"));
return job;
}
public String getName() {
return "count-aggregate";
}
public static void addPrerequisite(Class<? extends ThraxJob> c) {
prereqs.add(c);
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
prereqs.add(ParaphraseCountPivotingJob.class);
return prereqs;
}
public String getOutputSuffix() {
return null;
}
}
class CountAggregationMapper
extends Mapper<AlignedRuleWritable, Annotation, AlignedRuleWritable, Annotation> {
protected void setup(Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
Vocabulary.initialize(conf);
}
protected void map(AlignedRuleWritable key, Annotation value, Context context)
throws IOException, InterruptedException {
context.write(key, value);
context.progress();
}
}
| 34.086957 | 95 | 0.776467 |
d699f7527426cbe80e1f44ecfc9b11cbd3311ccd | 1,886 | /**
* Copyright 2009-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.javacrumbs.shedlock.spring.it;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.core.SchedulerLock;
import net.javacrumbs.shedlock.core.SimpleLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractSchedulerConfig {
private static final Logger logger = LoggerFactory.getLogger(ProxyIntegrationTest.class);
@Bean
public LockProvider lockProvider() {
LockProvider lockProvider = mock(LockProvider.class);
when(lockProvider.lock(any())).thenReturn(Optional.of(mock(SimpleLock.class)));
return lockProvider;
}
@Bean
public ScheduledBean scheduledBean() {
return new ScheduledBean();
}
// Does not work if scheduler configured in Configuration
public static class ScheduledBean {
@SchedulerLock(name = "taskName")
@Scheduled(fixedRate = 10)
public void run() {
logger.info("Task executed");
}
}
}
| 33.087719 | 93 | 0.73701 |
aace5086bf80afead99ab23dd50271069cb3b99c | 2,692 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.elyssiamc.Micc.JavaMee6APIWrapper.DataStructures.Adapters;
/**
* Auto-generated code used to translate Guild a JSON Response to a Java object
*
* @author Micc
*
*/
public class Role
{
private int position;
private String id;
private boolean managed;
private long color;
private String name;
private boolean hoist;
private long permissions;
private boolean mentionable;
public int getPosition ()
{
return position;
}
public void setPosition (int position)
{
this.position = position;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public boolean getManaged ()
{
return managed;
}
public void setManaged (boolean managed)
{
this.managed = managed;
}
public long getColor ()
{
return color;
}
public void setColor (long color)
{
this.color = color;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public boolean getHoist ()
{
return hoist;
}
public void setHoist (boolean hoist)
{
this.hoist = hoist;
}
public long getPermissions ()
{
return permissions;
}
public void setPermissions (long permissions)
{
this.permissions = permissions;
}
public boolean getMentionable ()
{
return mentionable;
}
public void setMentionable (boolean mentionable)
{
this.mentionable = mentionable;
}
@Override
public String toString()
{
return "ClassPojo [position = "+position+", id = "+id+", managed = "+managed+", color = "+color+", name = "+name+", hoist = "+hoist+", permissions = "+permissions+", mentionable = "+mentionable+"]";
}
} | 20.549618 | 206 | 0.639673 |
9024ce7228e7efb71b34b3eda14c046d425883e5 | 33,456 | package com.orientechnologies.orient.core.record.impl;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.serialization.ODocumentSerializable;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.*;
import static org.junit.Assert.*;
public class ODocumentSchemalessBinarySerializationTest {
protected ORecordSerializer serializer;
public ODocumentSchemalessBinarySerializationTest() {
serializer = new ORecordSerializerBinary();
}
@Test
public void testSimpleSerialization() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
document.field("name", "name");
document.field("age", 20);
document.field("youngAge", (short) 20);
document.field("oldAge", (long) 20);
document.field("heigth", 12.5f);
document.field("bitHeigth", 12.5d);
document.field("class", (byte) 'C');
document.field("nullField", (Object) null);
document.field("character", 'C');
document.field("alive", true);
document.field("dateTime", new Date());
document.field("bigNumber", new BigDecimal("43989872423376487952454365232141525434.32146432321442534"));
ORidBag bag = new ORidBag();
bag.add(new ORecordId(1, 1));
bag.add(new ORecordId(2, 2));
// document.field("ridBag", bag);
Calendar c = Calendar.getInstance();
document.field("date", c.getTime(), OType.DATE);
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.MILLISECOND, 0);
c1.set(Calendar.SECOND, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.HOUR_OF_DAY, 0);
document.field("date1", c1.getTime(), OType.DATE);
byte[] byteValue = new byte[10];
Arrays.fill(byteValue, (byte) 10);
document.field("bytes", byteValue);
document.field("utf8String", new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C"));
document.field("recordId", new ORecordId(10, 10));
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("name"), document.field("name"));
assertEquals(extr.<Object>field("age"), document.field("age"));
assertEquals(extr.<Object>field("youngAge"), document.field("youngAge"));
assertEquals(extr.<Object>field("oldAge"), document.field("oldAge"));
assertEquals(extr.<Object>field("heigth"), document.field("heigth"));
assertEquals(extr.<Object>field("bitHeigth"), document.field("bitHeigth"));
assertEquals(extr.<Object>field("class"), document.field("class"));
// TODO fix char management issue:#2427
// assertEquals(document.field("character"), extr.field("character"));
assertEquals(extr.<Object>field("alive"), document.field("alive"));
assertEquals(extr.<Object>field("dateTime"), document.field("dateTime"));
assertEquals(extr.field("date"), c.getTime());
assertEquals(extr.field("date1"), c1.getTime());
// assertEquals(extr.<String>field("bytes"), document.field("bytes"));
Assertions.assertThat(extr.<Object>field("bytes")).isEqualTo(document.field("bytes"));
assertEquals(extr.<String>field("utf8String"), document.field("utf8String"));
assertEquals(extr.<Object>field("recordId"), document.field("recordId"));
assertEquals(extr.<Object>field("bigNumber"), document.field("bigNumber"));
assertNull(extr.field("nullField"));
// assertEquals(extr.field("ridBag"), document.field("ridBag"));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSimpleLiteralArray() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
String[] strings = new String[3];
strings[0] = "a";
strings[1] = "b";
strings[2] = "c";
document.field("listStrings", strings);
Short[] shorts = new Short[3];
shorts[0] = (short) 1;
shorts[1] = (short) 2;
shorts[2] = (short) 3;
document.field("shorts", shorts);
Long[] longs = new Long[3];
longs[0] = (long) 1;
longs[1] = (long) 2;
longs[2] = (long) 3;
document.field("longs", longs);
Integer[] ints = new Integer[3];
ints[0] = 1;
ints[1] = 2;
ints[2] = 3;
document.field("integers", ints);
Float[] floats = new Float[3];
floats[0] = 1.1f;
floats[1] = 2.2f;
floats[2] = 3.3f;
document.field("floats", floats);
Double[] doubles = new Double[3];
doubles[0] = 1.1d;
doubles[1] = 2.2d;
doubles[2] = 3.3d;
document.field("doubles", doubles);
Date[] dates = new Date[3];
dates[0] = new Date();
dates[1] = new Date();
dates[2] = new Date();
document.field("dates", dates);
Byte[] bytes = new Byte[3];
bytes[0] = (byte) 0;
bytes[1] = (byte) 1;
bytes[2] = (byte) 3;
document.field("bytes", bytes);
// TODO: char not currently supported in orient.
Character[] chars = new Character[3];
chars[0] = 'A';
chars[1] = 'B';
chars[2] = 'C';
// document.field("chars", chars);
Boolean[] booleans = new Boolean[3];
booleans[0] = true;
booleans[1] = false;
booleans[2] = false;
document.field("booleans", booleans);
Object[] arrayNulls = new Object[3];
// document.field("arrayNulls", arrayNulls);
// Object[] listMixed = new ArrayList[9];
// listMixed[0] = new Boolean(true);
// listMixed[1] = 1;
// listMixed[2] = (long) 5;
// listMixed[3] = (short) 2;
// listMixed[4] = 4.0f;
// listMixed[5] = 7.0D;
// listMixed[6] = "hello";
// listMixed[7] = new Date();
// listMixed[8] = (byte) 10;
// document.field("listMixed", listMixed);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(((List) extr.field("listStrings")).toArray(), document.field("listStrings"));
assertEquals(((List) extr.field("integers")).toArray(), document.field("integers"));
assertEquals(((List) extr.field("doubles")).toArray(), document.field("doubles"));
assertEquals(((List) extr.field("dates")).toArray(), document.field("dates"));
assertEquals(((List) extr.field("bytes")).toArray(), document.field("bytes"));
assertEquals(((List) extr.field("booleans")).toArray(), document.field("booleans"));
// assertEquals(((List) extr.field("arrayNulls")).toArray(), document.field("arrayNulls"));
// assertEquals(extr.field("listMixed"), document.field("listMixed"));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSimpleLiteralList() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
List<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
strings.add("c");
document.field("listStrings", strings);
List<Short> shorts = new ArrayList<Short>();
shorts.add((short) 1);
shorts.add((short) 2);
shorts.add((short) 3);
document.field("shorts", shorts);
List<Long> longs = new ArrayList<Long>();
longs.add((long) 1);
longs.add((long) 2);
longs.add((long) 3);
document.field("longs", longs);
List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
document.field("integers", ints);
List<Float> floats = new ArrayList<Float>();
floats.add(1.1f);
floats.add(2.2f);
floats.add(3.3f);
document.field("floats", floats);
List<Double> doubles = new ArrayList<Double>();
doubles.add(1.1);
doubles.add(2.2);
doubles.add(3.3);
document.field("doubles", doubles);
List<Date> dates = new ArrayList<Date>();
dates.add(new Date());
dates.add(new Date());
dates.add(new Date());
document.field("dates", dates);
List<Byte> bytes = new ArrayList<Byte>();
bytes.add((byte) 0);
bytes.add((byte) 1);
bytes.add((byte) 3);
document.field("bytes", bytes);
// TODO: char not currently supported in orient.
List<Character> chars = new ArrayList<Character>();
chars.add('A');
chars.add('B');
chars.add('C');
// document.field("chars", chars);
List<Boolean> booleans = new ArrayList<Boolean>();
booleans.add(true);
booleans.add(false);
booleans.add(false);
document.field("booleans", booleans);
List listMixed = new ArrayList();
listMixed.add(true);
listMixed.add(1);
listMixed.add((long) 5);
listMixed.add((short) 2);
listMixed.add(4.0f);
listMixed.add(7.0D);
listMixed.add("hello");
listMixed.add(new Date());
listMixed.add((byte) 10);
document.field("listMixed", listMixed);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("listStrings"), document.field("listStrings"));
assertEquals(extr.<Object>field("integers"), document.field("integers"));
assertEquals(extr.<Object>field("doubles"), document.field("doubles"));
assertEquals(extr.<Object>field("dates"), document.field("dates"));
assertEquals(extr.<Object>field("bytes"), document.field("bytes"));
assertEquals(extr.<Object>field("booleans"), document.field("booleans"));
assertEquals(extr.<Object>field("listMixed"), document.field("listMixed"));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSimpleLiteralSet() throws InterruptedException {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Set<String> strings = new HashSet<String>();
strings.add("a");
strings.add("b");
strings.add("c");
document.field("listStrings", strings);
Set<Short> shorts = new HashSet<Short>();
shorts.add((short) 1);
shorts.add((short) 2);
shorts.add((short) 3);
document.field("shorts", shorts);
Set<Long> longs = new HashSet<Long>();
longs.add((long) 1);
longs.add((long) 2);
longs.add((long) 3);
document.field("longs", longs);
Set<Integer> ints = new HashSet<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
document.field("integers", ints);
Set<Float> floats = new HashSet<Float>();
floats.add(1.1f);
floats.add(2.2f);
floats.add(3.3f);
document.field("floats", floats);
Set<Double> doubles = new HashSet<Double>();
doubles.add(1.1);
doubles.add(2.2);
doubles.add(3.3);
document.field("doubles", doubles);
Set<Date> dates = new HashSet<Date>();
dates.add(new Date());
Thread.sleep(1);
dates.add(new Date());
Thread.sleep(1);
dates.add(new Date());
document.field("dates", dates);
Set<Byte> bytes = new HashSet<Byte>();
bytes.add((byte) 0);
bytes.add((byte) 1);
bytes.add((byte) 3);
document.field("bytes", bytes);
// TODO: char not currently supported in orient.
Set<Character> chars = new HashSet<Character>();
chars.add('A');
chars.add('B');
chars.add('C');
// document.field("chars", chars);
Set<Boolean> booleans = new HashSet<Boolean>();
booleans.add(true);
booleans.add(false);
booleans.add(false);
document.field("booleans", booleans);
Set listMixed = new HashSet();
listMixed.add(true);
listMixed.add(1);
listMixed.add((long) 5);
listMixed.add((short) 2);
listMixed.add(4.0f);
listMixed.add(7.0D);
listMixed.add("hello");
listMixed.add(new Date());
listMixed.add((byte) 10);
listMixed.add(new ORecordId(10, 20));
document.field("listMixed", listMixed);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("listStrings"), document.field("listStrings"));
assertEquals(extr.<Object>field("integers"), document.field("integers"));
assertEquals(extr.<Object>field("doubles"), document.field("doubles"));
assertEquals(extr.<Object>field("dates"), document.field("dates"));
assertEquals(extr.<Object>field("bytes"), document.field("bytes"));
assertEquals(extr.<Object>field("booleans"), document.field("booleans"));
assertEquals(extr.<Object>field("listMixed"), document.field("listMixed"));
}
@Test
public void testLinkCollections() {
ODatabaseDocument db = new ODatabaseDocumentTx("memory:ODocumentSchemalessBinarySerializationTest").create();
try {
ODocument document = new ODocument();
Set<ORecordId> linkSet = new HashSet<ORecordId>();
linkSet.add(new ORecordId(10, 20));
linkSet.add(new ORecordId(10, 21));
linkSet.add(new ORecordId(10, 22));
linkSet.add(new ORecordId(11, 22));
document.field("linkSet", linkSet, OType.LINKSET);
List<ORecordId> linkList = new ArrayList<ORecordId>();
linkList.add(new ORecordId(10, 20));
linkList.add(new ORecordId(10, 21));
linkList.add(new ORecordId(10, 22));
linkList.add(new ORecordId(11, 22));
document.field("linkList", linkList, OType.LINKLIST);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(((Set<?>) extr.field("linkSet")).size(), ((Set<?>) document.field("linkSet")).size());
assertTrue(((Set<?>) extr.field("linkSet")).containsAll((Set<?>) document.field("linkSet")));
assertEquals(extr.<Object>field("linkList"), document.field("linkList"));
} finally {
db.drop();
}
}
@Test
public void testSimpleEmbeddedDoc() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
ODocument embedded = new ODocument();
embedded.field("name", "test");
embedded.field("surname", "something");
document.field("embed", embedded, OType.EMBEDDED);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(document.fields(), extr.fields());
ODocument emb = extr.field("embed");
assertNotNull(emb);
assertEquals(emb.<Object>field("name"), embedded.field("name"));
assertEquals(emb.<Object>field("surname"), embedded.field("surname"));
}
@Test
public void testSimpleMapStringLiteral() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Map<String, String> mapString = new HashMap<String, String>();
mapString.put("key", "value");
mapString.put("key1", "value1");
document.field("mapString", mapString);
Map<String, Integer> mapInt = new HashMap<String, Integer>();
mapInt.put("key", 2);
mapInt.put("key1", 3);
document.field("mapInt", mapInt);
Map<String, Long> mapLong = new HashMap<String, Long>();
mapLong.put("key", 2L);
mapLong.put("key1", 3L);
document.field("mapLong", mapLong);
Map<String, Short> shortMap = new HashMap<String, Short>();
shortMap.put("key", (short) 2);
shortMap.put("key1", (short) 3);
document.field("shortMap", shortMap);
Map<String, Date> dateMap = new HashMap<String, Date>();
dateMap.put("key", new Date());
dateMap.put("key1", new Date());
document.field("dateMap", dateMap);
Map<String, Float> floatMap = new HashMap<String, Float>();
floatMap.put("key", 10f);
floatMap.put("key1", 11f);
document.field("floatMap", floatMap);
Map<String, Double> doubleMap = new HashMap<String, Double>();
doubleMap.put("key", 10d);
doubleMap.put("key1", 11d);
document.field("doubleMap", doubleMap);
Map<String, Byte> bytesMap = new HashMap<String, Byte>();
bytesMap.put("key", (byte) 10);
bytesMap.put("key1", (byte) 11);
document.field("bytesMap", bytesMap);
Map<String, String> mapWithNulls = new HashMap<String, String>();
mapWithNulls.put("key", "dddd");
mapWithNulls.put("key1", null);
document.field("bytesMap", mapWithNulls);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("mapString"), document.field("mapString"));
assertEquals(extr.<Object>field("mapLong"), document.field("mapLong"));
assertEquals(extr.<Object>field("shortMap"), document.field("shortMap"));
assertEquals(extr.<Object>field("dateMap"), document.field("dateMap"));
assertEquals(extr.<Object>field("doubleMap"), document.field("doubleMap"));
assertEquals(extr.<Object>field("bytesMap"), document.field("bytesMap"));
}
@Test
public void testlistOfList() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
List<List<String>> list = new ArrayList<List<String>>();
List<String> ls = new ArrayList<String>();
ls.add("test1");
ls.add("test2");
list.add(ls);
document.field("complexList", list);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("complexList"), document.field("complexList"));
}
@Test
public void testArrayOfArray() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
String[][] array = new String[1][];
String[] ls = new String[2];
ls[0] = "test1";
ls[1] = "test2";
array[0] = ls;
document.field("complexArray", array);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
List<List<String>> savedValue = extr.field("complexArray");
assertEquals(savedValue.size(), array.length);
assertEquals(savedValue.get(0).size(), array[0].length);
assertEquals(savedValue.get(0).get(0), array[0][0]);
assertEquals(savedValue.get(0).get(1), array[0][1]);
}
@Test
public void testEmbeddedListOfEmbeddedMap() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
List<Map<String, String>> coll = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("first", "something");
map.put("second", "somethingElse");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("first", "something");
map2.put("second", "somethingElse");
coll.add(map);
coll.add(map2);
document.field("list", coll);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("list"), document.field("list"));
}
@Test
public void testMapOfEmbeddedDocument() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
ODocument embeddedInMap = new ODocument();
embeddedInMap.field("name", "test");
embeddedInMap.field("surname", "something");
Map<String, ODocument> map = new HashMap<String, ODocument>();
map.put("embedded", embeddedInMap);
document.field("map", map, OType.EMBEDDEDMAP);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
Map<String, ODocument> mapS = extr.field("map");
assertEquals(1, mapS.size());
ODocument emb = mapS.get("embedded");
assertNotNull(emb);
assertEquals(emb.<Object>field("name"), embeddedInMap.field("name"));
assertEquals(emb.<Object>field("surname"), embeddedInMap.field("surname"));
}
@Test
public void testMapOfLink() {
// needs a database because of the lazy loading
ODatabaseDocument db = new ODatabaseDocumentTx("memory:ODocumentSchemalessBinarySerializationTest").create();
try {
ODocument document = new ODocument();
Map<String, OIdentifiable> map = new HashMap<String, OIdentifiable>();
map.put("link", new ORecordId(0, 0));
document.field("map", map, OType.LINKMAP);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("map"), document.field("map"));
} finally {
db.drop();
}
}
@Test
public void testDocumentWithClassName() {
ODatabaseDocument db = new ODatabaseDocumentTx("memory:ODocumentSchemalessBinarySerializationTest").create();
try {
ODocument document = new ODocument("TestClass");
document.field("test", "test");
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.getClassName(), document.getClassName());
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("test"), document.field("test"));
} finally {
db.drop();
}
}
@Test
public void testDocumentWithCostum() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
document.field("test", "test");
document.field("custom", new Custom());
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.getClassName(), document.getClassName());
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("test"), document.field("test"));
assertEquals(extr.<Object>field("custom"), document.field("custom"));
}
@Test
public void testDocumentWithCostumDocument() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
document.field("test", "test");
document.field("custom", new CustomDocument());
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(extr.getClassName(), document.getClassName());
assertEquals(extr.fields(), document.fields());
assertEquals(extr.<Object>field("test"), document.field("test"));
assertEquals(extr.<Object>field("custom"), document.field("custom"));
}
@Test(expected = OSerializationException.class)
public void testSetOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Set<Object> embeddedSet = new HashSet<Object>();
embeddedSet.add(new WrongData());
document.field("embeddedSet", embeddedSet, OType.EMBEDDEDSET);
serializer.toStream(document, false);
}
@Test(expected = OSerializationException.class)
public void testListOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
List<Object> embeddedList = new ArrayList<Object>();
embeddedList.add(new WrongData());
document.field("embeddedList", embeddedList, OType.EMBEDDEDLIST);
serializer.toStream(document, false);
}
@Test(expected = OSerializationException.class)
public void testMapOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Map<String, Object> embeddedMap = new HashMap<String, Object>();
embeddedMap.put("name", new WrongData());
document.field("embeddedMap", embeddedMap, OType.EMBEDDEDMAP);
serializer.toStream(document, false);
}
@Test(expected = ClassCastException.class)
public void testLinkSetOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Set<Object> linkSet = new HashSet<Object>();
linkSet.add(new WrongData());
document.field("linkSet", linkSet, OType.LINKSET);
serializer.toStream(document, false);
}
@Test(expected = ClassCastException.class)
public void testLinkListOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
List<Object> linkList = new ArrayList<Object>();
linkList.add(new WrongData());
document.field("linkList", linkList, OType.LINKLIST);
serializer.toStream(document, false);
}
@Test(expected = ClassCastException.class)
public void testLinkMapOfWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
Map<String, Object> linkMap = new HashMap<String, Object>();
linkMap.put("name", new WrongData());
document.field("linkMap", linkMap, OType.LINKMAP);
serializer.toStream(document, false);
}
@Test(expected = OSerializationException.class)
public void testFieldWrongData() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
document.field("wrongData", new WrongData());
serializer.toStream(document, false);
}
@Test
public void testCollectionOfEmbeddedDocument() {
ODatabaseRecordThreadLocal.INSTANCE.remove();
ODocument document = new ODocument();
ODocument embeddedInList = new ODocument();
embeddedInList.field("name", "test");
embeddedInList.field("surname", "something");
ODocument embeddedInList2 = new ODocument();
embeddedInList2.field("name", "test1");
embeddedInList2.field("surname", "something2");
List<ODocument> embeddedList = new ArrayList<ODocument>();
embeddedList.add(embeddedInList);
embeddedList.add(embeddedInList2);
embeddedList.add(null);
embeddedList.add(new ODocument());
document.field("embeddedList", embeddedList, OType.EMBEDDEDLIST);
ODocument embeddedInSet = new ODocument();
embeddedInSet.field("name", "test2");
embeddedInSet.field("surname", "something3");
ODocument embeddedInSet2 = new ODocument();
embeddedInSet2.field("name", "test5");
embeddedInSet2.field("surname", "something6");
Set<ODocument> embeddedSet = new HashSet<ODocument>();
embeddedSet.add(embeddedInSet);
embeddedSet.add(embeddedInSet2);
embeddedSet.add(new ODocument());
document.field("embeddedSet", embeddedSet, OType.EMBEDDEDSET);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
List<ODocument> ser = extr.field("embeddedList");
assertEquals(ser.size(), 4);
assertNotNull(ser.get(0));
assertNotNull(ser.get(1));
assertNull(ser.get(2));
assertNotNull(ser.get(3));
ODocument inList = ser.get(0);
assertNotNull(inList);
assertEquals(inList.<Object>field("name"), embeddedInList.field("name"));
assertEquals(inList.<Object>field("surname"), embeddedInList.field("surname"));
Set<ODocument> setEmb = extr.field("embeddedSet");
assertEquals(setEmb.size(), 3);
boolean ok = false;
for (ODocument inSet : setEmb) {
assertNotNull(inSet);
if (embeddedInSet.field("name").equals(inSet.field("name")) && embeddedInSet.field("surname").equals(inSet.field("surname")))
ok = true;
}
assertTrue("not found record in the set after serilize", ok);
}
@Test
public void testSerializableValue() {
ODocument document = new ODocument();
SimpleSerializableClass ser = new SimpleSerializableClass();
ser.name = "testName";
document.field("seri", ser);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertNotNull(extr.field("seri"));
assertEquals(extr.fieldType("seri"), OType.CUSTOM);
SimpleSerializableClass newser = extr.field("seri");
assertEquals(newser.name, ser.name);
}
@Test
public void testFieldNames() {
ODocument document = new ODocument();
document.fields("a", 1, "b", 2, "c", 3);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
final String[] fields = extr.fieldNames();
assertNotNull(fields);
assertEquals(fields.length, 3);
assertEquals(fields[0], "a");
assertEquals(fields[1], "b");
assertEquals(fields[2], "c");
}
@Test
public void testFieldNamesRaw() {
ODocument document = new ODocument();
document.fields("a", 1, "b", 2, "c", 3);
byte[] res = serializer.toStream(document, false);
final String[] fields = serializer.getFieldNames(document, res);
assertNotNull(fields);
assertEquals(fields.length, 3);
assertEquals(fields[0], "a");
assertEquals(fields[1], "b");
assertEquals(fields[2], "c");
}
@Test
public void testPartial() {
ODocument document = new ODocument();
document.field("name", "name");
document.field("age", 20);
document.field("youngAge", (short) 20);
document.field("oldAge", (long) 20);
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] { "name", "age" });
assertEquals(document.field("name"), extr.<Object>field("name"));
assertEquals(document.<Object>field("age"), extr.field("age"));
assertNull(extr.field("youngAge"));
assertNull(extr.field("oldAge"));
}
@Test
public void testWithRemove() {
ODocument document = new ODocument();
document.field("name", "name");
document.field("age", 20);
document.field("youngAge", (short) 20);
document.field("oldAge", (long) 20);
document.removeField("oldAge");
byte[] res = serializer.toStream(document, false);
ODocument extr = (ODocument) serializer.fromStream(res, new ODocument(), new String[] {});
assertEquals(document.field("name"), extr.<Object>field("name"));
assertEquals(document.<Object>field("age"), extr.field("age"));
assertEquals(document.<Object>field("youngAge"), extr.field("youngAge"));
assertNull(extr.field("oldAge"));
}
@Test
public void testPartialCustom() {
ODocument document = new ODocument();
document.field("name", "name");
document.field("age", 20);
document.field("youngAge", (short) 20);
document.field("oldAge", (long) 20);
byte[] res = serializer.toStream(document, false);
ODocument extr = new ODocument(res);
ORecordInternal.setRecordSerializer(extr, serializer);
assertEquals(document.field("name"), extr.<Object>field("name"));
assertEquals(document.<Object>field("age"), extr.field("age"));
assertEquals(document.<Object>field("youngAge"), extr.field("youngAge"));
assertEquals(document.<Object>field("oldAge"), extr.field("oldAge"));
assertEquals(document.fieldNames().length, extr.fieldNames().length);
}
public static class Custom implements OSerializableStream {
byte[] bytes = new byte[10];
@Override
public OSerializableStream fromStream(byte[] iStream) throws OSerializationException {
bytes = iStream;
return this;
}
@Override
public byte[] toStream() throws OSerializationException {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) i;
}
return bytes;
}
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof Custom && Arrays.equals(bytes, ((Custom) obj).bytes);
}
}
public static class CustomDocument implements ODocumentSerializable {
private ODocument document;
@Override
public void fromDocument(ODocument document) {
this.document = document;
}
@Override
public ODocument toDocument() {
document = new ODocument();
document.field("test", "some strange content");
return document;
}
@Override
public boolean equals(Object obj) {
return obj != null && document.field("test").equals(((CustomDocument) obj).document.field("test"));
}
}
private class WrongData {
}
}
| 35.478261 | 131 | 0.668998 |
10670e2cd70dfbeeb394652a1e717beebd7fda6a | 352 | package co.com.practicaJava.ejercicio4;
public class Producto {
private Double precio;
private final Double iva = 0.21;
public Producto(Double precio) {
this.precio = precio;
}
public double precioFinal(){
return importeIva() + precio;
}
public double importeIva(){
return precio * iva;
}
}
| 17.6 | 39 | 0.625 |
b1977c5cdf6d921d516193f0c32e34bf04e6a96b | 1,166 | package com.gitclone.classnotfound;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.gitclone.classnotfound.model.Cnf_pomattr;
public class XmlTest {
public static void main(String[] args) throws Exception {
String url = "https://repo1.maven.org/maven2/org/springframework/spring-context/5.3.15/spring-context-5.3.15.pom" ;
Cnf_pomattr cnf_pomattr = parsePom(url);
if (cnf_pomattr!=null) {
System.out.println(cnf_pomattr.getUrl().substring(0,5)) ;
}
}
private static Cnf_pomattr parsePom(String url) {
Document doc;
try {
Cnf_pomattr cnf_pomattr = new Cnf_pomattr() ;
doc = Jsoup.connect(url).timeout(60000).get();
cnf_pomattr.setGroupId(doc.select("groupId").first().text());
cnf_pomattr.setArtifactId(doc.select("artifactId").first().text());
cnf_pomattr.setUrl(doc.select("url").first().text());
cnf_pomattr.setVersion(doc.select("version").first().text());
cnf_pomattr.setName(doc.select("name").first().text());
cnf_pomattr.setDescription(doc.select("description").first().text());
return cnf_pomattr ;
} catch (IOException e) {
return null ;
}
}
}
| 30.684211 | 117 | 0.716123 |
0de468a4066daf331a262fc68dd62938b84959e2 | 8,738 | package com.option_u.stolpersteine.api.test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import android.test.AndroidTestCase;
import com.option_u.stolpersteine.api.RetrieveStolpersteineRequest;
import com.option_u.stolpersteine.api.SearchData;
import com.option_u.stolpersteine.api.StolpersteineNetworkService;
import com.option_u.stolpersteine.api.model.Stolperstein;
public class NetworkServiceTest extends AndroidTestCase {
private static int TIME_OUT = 5;
private CountDownLatch doneLatch;
private StolpersteineNetworkService networkService;
public void setUp() {
doneLatch = new CountDownLatch(1);
networkService = new StolpersteineNetworkService(getContext(), null, null);
}
public void testRetrieveStolpersteine() throws InterruptedException {
networkService.retrieveStolpersteine(null, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals("Wrong number of stolpersteine", 5, stolpersteine.size());
for (Stolperstein stolperstein : stolpersteine) {
// Mandatory fields
assertNotNull("Wrong ID", stolperstein.getId());
assertTrue("Wrong type", stolperstein.getType() == Stolperstein.Type.STOLPERSTEIN
|| stolperstein.getType() == Stolperstein.Type.STOLPERSCHWELLE);
assertNotNull("Wrong source", stolperstein.getSource());
assertNotNull("Wrong source name", stolperstein.getSource().getName());
assertNotNull("Wrong source URI", stolperstein.getSource().getUri());
assertNotNull("Wrong person", stolperstein.getPerson());
assertNotNull("Wrong person last name", stolperstein.getPerson().getLastName());
assertNotNull("Wrong person biography URI", stolperstein.getPerson().getBiographyUri());
assertNotNull("Wrong location street", stolperstein.getLocation().getStreet());
assertNotNull("Wrong location city", stolperstein.getLocation().getCity());
assertFalse("Wrong location latitude", stolperstein.getLocation().getCoordinates().latitude == 0.0);
assertFalse("Wrong location longitude", stolperstein.getLocation().getCoordinates().longitude == 0.0);
// Optional fields
if (!stolperstein.getPerson().getFirstName().isEmpty()) {
assertTrue("Wrong location first name", stolperstein.getPerson().getFirstName().length() > 0);
}
if (!stolperstein.getLocation().getZipCode().isEmpty()) {
assertTrue("Wrong location zip code", stolperstein.getLocation().getZipCode().length() > 0);
}
}
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteineKeyword() throws InterruptedException {
final SearchData searchData = new SearchData();
searchData.setKeyword("Ern");
networkService.retrieveStolpersteine(searchData, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertTrue(stolpersteine.size() > 0);
for (Stolperstein stolperstein : stolpersteine) {
boolean found = stolperstein.getPerson().getFirstName().startsWith(searchData.getKeyword());
found |= stolperstein.getPerson().getLastName().startsWith(searchData.getKeyword());
assertTrue("Wrong search result", found);
}
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteineStreet() throws InterruptedException {
final SearchData searchData = new SearchData();
searchData.setStreet("Turmstraße");
networkService.retrieveStolpersteine(searchData, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertTrue(stolpersteine.size() > 0);
for (Stolperstein stolperstein : stolpersteine) {
boolean found = stolperstein.getLocation().getStreet().startsWith(searchData.getStreet());
assertTrue("Wrong search result", found);
}
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteineCity() throws InterruptedException {
final SearchData searchData = new SearchData();
searchData.setCity("Berlin");
networkService.retrieveStolpersteine(searchData, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertTrue(stolpersteine.size() > 0);
for (Stolperstein stolperstein : stolpersteine) {
boolean found = stolperstein.getLocation().getCity().startsWith(searchData.getCity());
assertTrue("Wrong search result", found);
}
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteineCityInvalid() throws InterruptedException {
networkService.getDefaultSearchData().setCity("Berlin"); // will be overridden by specific data
final SearchData searchData = new SearchData();
searchData.setCity("xyz");
networkService.retrieveStolpersteine(searchData, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals(0, stolpersteine.size());
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteineCityDefaultInvalid() throws InterruptedException {
networkService.getDefaultSearchData().setCity("xyz"); // will be overridden by specific data
networkService.retrieveStolpersteine(null, 0, 5, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals(0, stolpersteine.size());
doneLatch.countDown();
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
public void testRetrieveStolpersteinePaging() throws InterruptedException {
// Load first two stolpersteine
networkService.retrieveStolpersteine(null, 0, 2, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals(2, stolpersteine.size());
final String stolpersteinId0 = stolpersteine.get(0).getId();
final String stolpersteinId1 = stolpersteine.get(1).getId();
// First page
networkService.retrieveStolpersteine(null, 0, 1, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals(1, stolpersteine.size());
assertEquals(stolpersteinId0, stolpersteine.get(0).getId());
// Second page
networkService.retrieveStolpersteine(null, 1, 1, new RetrieveStolpersteineRequest.Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
assertEquals(1, stolpersteine.size());
assertEquals(stolpersteinId1, stolpersteine.get(0).getId());
doneLatch.countDown();
}
});
}
});
}
});
assertTrue(doneLatch.await(TIME_OUT, TimeUnit.SECONDS));
}
}
| 45.748691 | 122 | 0.622683 |
5ca3a6f6064dec65558434d48714fa11a023fc08 | 1,427 | package ml.northwestwind.moreboots.init.item.boots;
import ml.northwestwind.moreboots.init.ItemInit;
import ml.northwestwind.moreboots.init.item.BootsItem;
import net.minecraft.core.BlockPos;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
public class BlazeBootsItem extends BootsItem {
public BlazeBootsItem() {
super(ItemInit.ModArmorMaterial.BLAZE, "blaze_boots");
}
@Override
public void onLivingHurt(LivingHurtEvent event) {
DamageSource source = event.getSource();
if (source.equals(DamageSource.IN_FIRE) || source.equals(DamageSource.LAVA) || source.equals(DamageSource.ON_FIRE))
event.setCanceled(true);
}
@Override
public void onLivingUpdate(LivingEvent.LivingUpdateEvent event) {
LivingEntity entity = event.getEntityLiving();
BlockPos blockPos = entity.blockPosition();
BlockPos under = blockPos.below();
BlockState underneath = entity.level.getBlockState(under);
if (underneath.canOcclude() && entity.level.isEmptyBlock(blockPos))
entity.level.setBlockAndUpdate(blockPos, Blocks.FIRE.defaultBlockState());
}
}
| 40.771429 | 123 | 0.751927 |
b175c33cce82562a7caa5410172a89f0af299dde | 2,750 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2012 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others.
*
*See COPYING for Details
*
*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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package plugins.collaboration.socket;
/**
* Thread with termination methods.
* @author foltin
* @date 05.09.2012
*/
public abstract class TerminateableThread extends Thread {
protected boolean mShouldTerminate = false;
protected boolean mIsTerminated = false;
protected static java.util.logging.Logger logger = null;
protected int mSleepTime;
/**
*
*/
public TerminateableThread(String pName) {
super(pName);
if (logger == null) {
logger = freemind.main.Resources.getInstance().getLogger(
this.getClass().getName());
}
mSleepTime = 1000;
}
public void run() {
while (!mShouldTerminate) {
boolean shouldBeCalledDirectlyAgain = false;
try {
shouldBeCalledDirectlyAgain = processAction();
} catch (Exception e) {
freemind.main.Resources.getInstance().logException(e);
}
if(!shouldBeCalledDirectlyAgain) {
try {
Thread.sleep(mSleepTime);
} catch (InterruptedException e) {
freemind.main.Resources.getInstance().logException(e);
}
}
}
mIsTerminated = true;
}
/**
* Method that does the work in this thread.
* Must return every second, to be able to terminate thread.
* @return true, if the method wants to be called directly again. Otherwise sleep is carried out.
* @throws Exception
*/
public abstract boolean processAction() throws Exception;
public void commitSuicide() {
mShouldTerminate = true;
int timeout = 10;
logger.info("Shutting down thread " + getName() + ".");
while (!mIsTerminated && timeout-- > 0) {
try {
Thread.sleep(mSleepTime);
} catch (InterruptedException e) {
freemind.main.Resources.getInstance().logException(e);
}
}
if (timeout == 0) {
logger.warning("Can't stop thread " + getName() + "!");
} else {
logger.info("Shutting down thread " + getName() + " complete.");
}
}
} | 29.255319 | 104 | 0.704 |
02731eaa453df23ef76674379ca2c89b888753be | 1,049 | /**
* Copyright 2015 Santhosh Kumar Tekuri
*
* The JLibs authors license 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 jlibs.swing.outline;
import jlibs.core.graph.Path;
/**
* @author Santhosh Kumar T
*/
public class ClassColumn extends DefaultColumn{
public ClassColumn(){
super("Class", Class.class, null);
}
@Override
public Object getValueFor(Object obj){
if(obj instanceof Path)
obj = ((Path)obj).getElement();
return obj.getClass().getSimpleName();
}
}
| 29.138889 | 78 | 0.700667 |
94f21ddea5eaf96d234b5dadc211a1f6225b7352 | 697 | abstract class BackgroundInitializer<T> implements ConcurrentInitializer<T> {
/**
* Returns the {@code Future} object that was created when {@link #start()}
* was called. Therefore this method can only be called after {@code
* start()}.
*
* @return the {@code Future} object wrapped by this initializer
* @throws IllegalStateException if {@link #start()} has not been called
*/
public synchronized Future<T> getFuture() {
if (future == null) {
throw new IllegalStateException("start() must be called first!");
}
return future;
}
/** Stores the handle to the background task. */
private Future<T> future;
}
| 30.304348 | 89 | 0.658537 |
5b7ecb6a7a7e4c5bcca3204e8bb86fede2893633 | 10,098 | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.grid.inv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import com.raytheon.uf.common.dataplugin.grid.GridRecord;
import com.raytheon.uf.common.dataplugin.grid.derivparam.GridInventoryUpdater;
import com.raytheon.uf.common.dataplugin.grid.derivparam.GridMapKey;
import com.raytheon.uf.common.dataplugin.grid.derivparam.cache.GridTimeCache;
import com.raytheon.uf.common.dataplugin.grid.derivparam.tree.GridRequestableNode;
import com.raytheon.uf.common.derivparam.tree.AbstractBaseDataNode;
import com.raytheon.uf.common.derivparam.tree.AbstractDerivedDataNode;
import com.raytheon.uf.common.inventory.tree.AbstractRequestableNode.Dependency;
import com.raytheon.uf.common.parameter.Parameter;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.viz.alerts.observers.ProductAlertObserver;
import com.raytheon.viz.grid.GridExtensionManager;
/**
* Listens for updates to grid data and generates alerts for derived parameters.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------- -------- --------- ----------------------------------------
* Mar 25, 2010 3547 bsteffen Initial creation
* Aug 30, 2013 2298 rjpeter Make getPluginName abstract
* Sep 09, 2014 3356 njensen Remove CommunicationException
* Mar 03, 2016 5439 bsteffen Allow grid derived parameters from edex
* Aug 15, 2017 6332 bsteffen Move radar specific logic to extension
* Aug 23, 2017 6125 bsteffen Split common updating code to GridInventoryUpdater.
* Nov 30, 2018 7673 bsteffen Prevent full queue from blocking.
* Jun 24, 2019 ---- mjames Remove umlaut in "schrodingers"
*
* </pre>
*
* @author bsteffen
*/
public class GridUpdater extends GridInventoryUpdater {
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(GridUpdater.class);
private static class UpdateValue {
public int timeOffset;
public AbstractDerivedDataNode node;
public UpdateValue(Integer timeOffset, AbstractDerivedDataNode node) {
this.timeOffset = timeOffset == null ? 0 : timeOffset;
this.node = node;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((node == null) ? 0 : node.hashCode());
result = (prime * result) + timeOffset;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
UpdateValue other = (UpdateValue) obj;
if (node == null) {
if (other.node != null) {
return false;
}
} else if (!node.equals(other.node)) {
return false;
}
if (timeOffset != other.timeOffset) {
return false;
}
return true;
}
}
private final Map<GridMapKey, Set<UpdateValue>> updateMap = new HashMap<>();
private final BlockingQueue<String> uriUpdateQueue = new LinkedBlockingQueue<>();
private final Job sendDerivedAlerts = new Job(
"Sending Derived Grid Alerts") {
@Override
protected IStatus run(IProgressMonitor monitor) {
Set<String> datauris = new HashSet<>();
uriUpdateQueue.drainTo(datauris);
ProductAlertObserver.processDataURIAlerts(datauris);
return Status.OK_STATUS;
}
};
public GridUpdater(VizGridInventory inventory) {
super(inventory);
sendDerivedAlerts.setSystem(true);
}
public synchronized void addNode(AbstractDerivedDataNode node) {
List<Dependency> dependencies = node.getDependencies();
if ((dependencies == null) || dependencies.isEmpty()) {
return;
}
List<Dependency> dep = new ArrayList<>(dependencies);
for (int i = 0; i < dep.size(); i++) {
Dependency dependency = dep.get(i);
if (dependency.node instanceof GridRequestableNode) {
GridRequestableNode gNode = (GridRequestableNode) dependency.node;
GridMapKey updateKey = new GridMapKey(
gNode.getRequestConstraintMap());
Set<UpdateValue> set = updateMap.get(updateKey);
if (set == null) {
set = new HashSet<>();
updateMap.put(updateKey, set);
}
set.add(new UpdateValue(dependency.timeOffset, node));
} else if (dependency.node instanceof AbstractBaseDataNode) {
GridMapKey updateKey = GridExtensionManager
.getUpdateKey((AbstractBaseDataNode) (dependency.node));
if (updateKey != null) {
Set<UpdateValue> set = updateMap.get(updateKey);
if (set == null) {
set = new HashSet<>();
updateMap.put(updateKey, set);
}
set.add(new UpdateValue(dependency.timeOffset, node));
}
} else if (dependency.node instanceof AbstractDerivedDataNode) {
AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) dependency.node;
for (Dependency d : dataNode.getDependencies()) {
d.timeOffset += dependency.timeOffset;
if (!dep.contains(d)) {
dep.add(d);
}
}
}
}
}
@Override
public synchronized void update(GridRecord record) {
super.update(record);
GridMapKey updateKey = new GridMapKey(record);
GridTimeCache.getInstance().clearTimes(updateKey);
Set<UpdateValue> set = updateMap.get(updateKey);
if (set == null) {
return;
}
for (UpdateValue value : set) {
/*
* A record in an ambiguous state. It may be valid and derivable or
* it may be missing dependencies and completely fake. It's
* impossible to know which state it is in without looking in the
* database to determine availability of all dependencies. Since
* many updates are not used it doesn't make sense to determine the
* real state of the record here and it is left to the receiver of
* updates to figure it out.
*/
GridRecord schrodingersRecord = new GridRecord();
DataTime time = record.getDataTime();
schrodingersRecord.setDataTime(new DataTime(time.getRefTime(),
time.getFcstTime() - value.timeOffset));
schrodingersRecord.setDatasetId(value.node.getModelName());
Parameter param = new Parameter(
value.node.getDesc().getAbbreviation(),
value.node.getDesc().getName(),
value.node.getDesc().getUnit());
schrodingersRecord.setParameter(param);
schrodingersRecord.setLevel(value.node.getLevel());
if (value.node instanceof GatherLevelNode) {
schrodingersRecord.setEnsembleId(null);
} else {
schrodingersRecord.setEnsembleId(record.getEnsembleId());
}
schrodingersRecord.setSecondaryId(record.getSecondaryId());
schrodingersRecord.setLocation(record.getLocation());
try {
uriUpdateQueue.put(schrodingersRecord.getDataURI());
} catch (InterruptedException e) {
statusHandler.handle(Priority.PROBLEM,
"Failed to send derived update for "
+ schrodingersRecord.getDataURI(),
e);
}
}
sendDerivedAlerts.schedule();
}
public synchronized void refreshNodes() {
GridTimeCache.getInstance().flush();
Set<AbstractDerivedDataNode> oldNodes = new HashSet<>();
for (Set<UpdateValue> values : updateMap.values()) {
for (UpdateValue value : values) {
oldNodes.add(value.node);
}
}
updateMap.clear();
for (AbstractDerivedDataNode node : oldNodes) {
// Get Node will automatically add this to the updater.
inventory.getNode(node.getModelName(),
node.getDesc().getAbbreviation(), node.getLevel());
}
}
}
| 39.6 | 93 | 0.602793 |
5908e718d5278d11ea6b657eeaaf1e000ed80b31 | 1,258 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import com.intellij.concurrency.AsyncFuture;
import com.intellij.openapi.util.Condition;
import org.jetbrains.annotations.NotNull;
public class FilteredQuery<T> extends AbstractQuery<T> {
private final Query<T> myOriginal;
private final Condition<? super T> myFilter;
public FilteredQuery(@NotNull Query<T> original, @NotNull Condition<? super T> filter) {
myOriginal = original;
myFilter = filter;
}
@Override
protected boolean processResults(@NotNull Processor<? super T> consumer) {
return delegateProcessResults(myOriginal, new MyProcessor(consumer));
}
@NotNull
@Override
public AsyncFuture<Boolean> forEachAsync(@NotNull Processor<? super T> consumer) {
return myOriginal.forEachAsync(new MyProcessor(consumer));
}
private class MyProcessor implements Processor<T> {
private final Processor<? super T> myConsumer;
MyProcessor(@NotNull Processor<? super T> consumer) {
myConsumer = consumer;
}
@Override
public boolean process(final T t) {
return !myFilter.value(t) || myConsumer.process(t);
}
}
}
| 29.952381 | 140 | 0.732909 |
5e18c9ec932b418d3739a7adb4a5e0811ef4ec8c | 8,387 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RESTServer;
import Controller.Controller;
import Persistence.Entry;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* Klasse für die Verarbeitung von Anfagen an die RES API für Entrys
*
* @author Timo Laser
*/
@RequestScoped
@Path("/entry")
public class RestEntry {
/**
* Schnitstelle zur Hauptlogik und Persistence
*/
@Inject
private Controller controller;
/**
* Nimmt Anfragen direkt an /entry entgegen und gibt alle Entries zurück
*
* @return Gibt Ein JsonObject mit einem JsonAray mit allen Entrys zurück, kann leer sein
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllEntrys() {
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (Entry e : this.controller.getEntries()) {
arrayBuilder.add(entrytoJson(e));
}
return Response.ok(objectBuilder.add("data", arrayBuilder.build()).build()).header("Access-Control-Allow-Origin", "*").build();
}
/**
* Nimmt Anfragen an /entry/{username} entgegen
* und gibt alle Entries die von dem Nutzer erstellt wuden zurück
*
* @param userName Der Nutzename des Nutzers
* @return Gibt ein JsonObject mit einem JsonArray zurück, welches alle oder
* keine Entries die von dem Nutzer erstellt wurden zurück
*/
@GET
@Path("/user/{userName}")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllEntrysByUserName(@PathParam("userName") String userName) {
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (Entry e : this.controller.getMemberEntries(userName)) {
arrayBuilder.add(entrytoJson(e));
}
return Response.ok(objectBuilder.add("data", arrayBuilder.build()).build()).header("Access-Control-Allow-Origin", "*").build();
}
/**
* Gibt ein Entry zu der übergebenen ID zurück
*
* @param id Die ID des Entries
* @return Gibt ein JsonObject zurück, bei Erfolg mit den Daten des Entry, ansonsten mit einer Fehlermeldung
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{entryId}")
public Response getEntryById(@PathParam("entryId") int id) {
Entry e;
if ((e = this.controller.getEntry(id)) != null) {
return Response.ok(this.entrytoJson(e)).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(Json.createObjectBuilder().add("error", Constants.ErrorMessages.CANT_FIND_ENTRY).build()).header("Access-Control-Allow-Origin", "*").build();
}
/**
* Erstellt ein neues Entry via POST Anfage.
* Erwartet ein JsonObject mit "name", "url", description" und "username"
*
* @param o Ein JsonObject mit allen nötigen Entry Daten
* @return Gibt einen leeren String zurück
*/
@POST
@Produces("text/plain")
@Consumes(MediaType.APPLICATION_JSON)
public Response addEntyPost(JsonObject o) {
//TODO Bestätiegungs- oder Fehlermeldung zurück geben
this.controller.addEntry(new Entry(o.getString("name"), o.getString("description"), o.getString("url"), o.getString("username")));
return Response.ok("").header("Access-Control-Allow-Origin", "*").build();
}
/**
* Erstellt ein neues Entry via GET Anfage.
* Erwartet "name", "url", description"
* und "username" als Query parameter
*
* @param name Der Titel
* @param url URL zur Website
* @param description Beschreibung der Bewertung
* @param userName Nutzername der das Entry erstellt
* @return Gibt einen leeren String zurück
*/
@GET
@Path("/create")
@Produces("text/plain")
@Consumes(MediaType.APPLICATION_JSON)
public Response addEnty(@QueryParam("name") String name, @QueryParam("url") String url, @QueryParam("desc") String description, @QueryParam("user") String userName) {
//TODO Bestätiegungs- oder Fehlermeldung zurück geben
this.controller.addEntry(new Entry(name, description, url, userName));
return Response.ok("").header("Access-Control-Allow-Origin", "*").build();
}
/**
* Erhöht Anzahl Sterne eines Entries. Die Entry-Id und der Nutzername müssen
* im Pfad zu Resource enthalten sein: "entry/[entryId]/incStars/{userName}"
*
* @param name Nutzername des Nutzers der die Anzahl der Sterne erhöht
* @param id ID des Entries desen Sterne erhöht werden sollen
* @return Bei fehlendem Nutzernamen wird "userName required!" zurückgegeben
* sosnt die Meldung des Controllers
* @see Controller
*/
@GET
@Path("/{entryId}/incStars/{userName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("text/plain")
public Response incEntryStart(@PathParam("userName") String name, @PathParam("entryId") int id) {
if (name != null) {
if (name != "") {
return Response.ok(this.controller.incrementEntry(id, name)).header("Access-Control-Allow-Origin", "*").build();
}
}
return Response.ok("userName required!").header("Access-Control-Allow-Origin", "*").build();
}
/**
* Veringert Anzahl Sterne eines Entries. Die Enry-Id und der Nutzername müssen
* im Pfad zu Resource enthalten sein: "entry/[entryId]/decStars/{userName}"
*
* @param name Nutzername des Nutzers der die Anzahl der Sterne veringert
* @param id ID des Entries desen Sterne veringert werden sollen
* @return Bei fehlendem Nutzernamen wird "userName required!" zurückgegeben
* sosnt die Meldung des Controllers
* @see Controller
*/
@GET
@Path("/{entryId}/decStars/{userName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("text/plain")
public Response decEntryStart(@PathParam("userName") String name, @PathParam("entryId") int id) {
if (name != null) {
if (name != null) {
return Response.ok(this.controller.decrementEntry(id, name)).header("Access-Control-Allow-Origin", "*").build();
}
}
return Response.ok("userName required!").header("Access-Control-Allow-Origin", "*").build();
}
/**
* Entfernt ein Entry. Entry-Id muss im Pfad zur Resource enthalten sein
* /entry/delete/{entryId}
*
* @param id Id des zu entfernen Entries
* @return wird kein Entry zu der ID gefunden wird "Entry not Found!" zurückgegeben, ansonsten
* die Meldung des Controllers
* @see Controller
*/
@GET
@Path("/delete/{entryId}")
@Produces("text/plain")
public Response deleteEntry(@PathParam("entryId") int id) {
Entry e;
if ((e = this.controller.getEntry(id)) != null) {
return Response.ok(this.controller.deleteEntry(id)).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(Constants.ErrorMessages.CANT_FIND_ENTRY).header("Access-Control-Allow-Origin", "*").build();
}
/**
* Konvertiert ein Entry Objekt in ein JsonObjekt
*
* @param e Das zu konvertierende Entry Objekt
* @return Ein JsonObjekt mit allen Entry Daten
*/
private JsonObject entrytoJson(Entry e) {
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
return objectBuilder
.add("id", e.getId())
.add("name", e.getName())
.add("description", e.getDescription())
.add("url", e.getUrl())
.add("stars", e.getStars())
.add("username", e.getUser())
.build();
}
}
| 38.122727 | 170 | 0.651484 |
c7e2683d0bda7afd36ae2b1a880c104b2c72044c | 1,303 | package Servlets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "MultiplicationTableServlet", urlPatterns = {"/MultiplicationTableServlet"})
public class MultiplicationTableServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
int upperLimit = Integer.parseInt(request.getParameter("upperLimit"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
request.setAttribute("upperLimit", upperLimit);
request.setAttribute("quantity", quantity);
request.getRequestDispatcher("multiplicationTableResult.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
processRequest(request, response);
}
} | 39.484848 | 97 | 0.762855 |
e6f157fcd04bd9e1b4404130f550b21646349f3d | 3,723 | package kernbeisser.Windows.Setting;
import java.util.Arrays;
import kernbeisser.Enums.PermissionKey;
import kernbeisser.Enums.Setting;
import kernbeisser.Main;
import kernbeisser.Security.Key;
import kernbeisser.Windows.LogIn.LogInModel;
import kernbeisser.Windows.MVC.Controller;
import lombok.var;
import org.jetbrains.annotations.NotNull;
public class SettingController extends Controller<SettingView, SettingModel> {
@Key(PermissionKey.ACTION_OPEN_APPLICATION_SETTINGS)
public SettingController() {
super(new SettingModel());
}
@NotNull
@Override
public SettingModel getModel() {
return model;
}
@Override
public void fillView(SettingView settingView) {
var view = getView();
view.setEditEnable(false);
view.setValues(Arrays.asList(Setting.values()));
}
public void apply() {
var view = getView();
Setting setting = model.getSelectedSettingValue();
if ((setting.equals(Setting.LAST_PRINTED_ACOUNTING_REPORT_NR)
|| setting.equals(Setting.LAST_PRINTED_BON_NR))
&& !SettingView.confirmAccounting()) return;
switch (Setting.getExpectedType(model.getSelectedSettingValue()).getSimpleName()) {
case "Integer":
try {
Integer.parseInt(view.getValue());
} catch (NumberFormatException e) {
if (!view.commitType("ganze Zahl(-2147483648 bis +2147483647)")) {
return;
}
}
break;
case "Long":
try {
Long.parseLong(view.getValue());
} catch (NumberFormatException e) {
if (!getView()
.commitType(
"ganze Zahl(-9,223,372,036,854,775,808 bis +9,223,372,036,854,775,807)")) {
return;
}
}
break;
case "Double":
try {
Double.parseDouble(view.getValue());
} catch (NumberFormatException e) {
if (!getView()
.commitType("Kommazahl(-4.94065645841246544e-324d bis +1.79769313486231570e+308d)")) {
return;
}
}
break;
case "Float":
try {
Float.parseFloat(view.getValue());
} catch (NumberFormatException e) {
if (!getView()
.commitType("Kommazahl(1.40129846432481707e-45 bis 3.40282346638528860e+38)")) {
return;
}
}
break;
case "Boolean":
if (view.getValue().equals("false") || view.getValue().equals("true")) {
break;
} else {
if (!view.commitType("Boolean wert(ja = true, nein = false)")) {
return;
}
}
break;
}
model.edit(view.getValue());
view.setValues(Arrays.asList(Setting.values()));
Main.logger.info(
"User["
+ LogInModel.getLoggedIn().getId()
+ "] set "
+ model.getSelectedSettingValue().toString()
+ " to '"
+ view.getValue()
+ "'");
}
public void cancel() {
var view = getView();
view.back();
}
public void resetAllSettings() {
var view = getView();
if (view.commitResetSettings()) {
for (Setting value : Setting.values()) {
if (value != Setting.DB_INITIALIZED) {
value.changeValue(value.getDefaultValue());
}
}
view.setValues(Arrays.asList(Setting.values()));
Main.logger.info(
"User[" + LogInModel.getLoggedIn().getId() + "] set all settings to default");
}
}
public void select(Setting settingValue) {
var view = getView();
view.setValue(settingValue.getValue());
view.setSelectedSetting(settingValue);
view.setEditEnable(true);
model.setSelectedValue(settingValue);
}
}
| 29.085938 | 100 | 0.594682 |
167aa563308b7869caca16f1c638fd84381952c0 | 2,836 | /*******************************************************************************
* Copyright (c) 2010 Fabian Steeg. All rights reserved. This program and
* the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* <p/>
* Contributors: Fabian Steeg - initial API and implementation; see bug 277380
*******************************************************************************/
package org.eclipse.zest.internal.dot;
import org.eclipse.zest.core.widgets.Graph;
import org.eclipse.zest.core.widgets.GraphConnection;
import org.eclipse.zest.core.widgets.GraphNode;
/**
* Imports the content of a Zest graph generated from DOT into an existing Zest
* graph.
*
* @author Fabian Steeg (fsteeg)
*/
final class ZestGraphImport {
private Graph graphFromDot;
/**
* @param sourceGraph
* The Zest source graph to import into another graph. Note that
* this will only support a subset of the graph attributes, as it
* is used for import of Zest graphs created from DOT input.
*/
ZestGraphImport(Graph sourceGraph) {
this.graphFromDot = sourceGraph;
}
/**
* @param targetGraph
* The graph to add content to
*/
void into(Graph targetGraph) {
Graph sourceGraph = graphFromDot;
targetGraph.setNodeStyle(sourceGraph.getNodeStyle());
targetGraph.setConnectionStyle(sourceGraph.getConnectionStyle());
targetGraph.setLayoutAlgorithm(sourceGraph.getLayoutAlgorithm(), true);
for (Object edge : sourceGraph.getConnections()) {
copy((GraphConnection) edge, targetGraph);
}
for (Object node : sourceGraph.getNodes()) {
copy((GraphNode) node, targetGraph);
}
targetGraph.update();
}
private GraphConnection copy(GraphConnection edge, Graph targetGraph) {
GraphNode source = copy(edge.getSource(), targetGraph);
GraphNode target = copy(edge.getDestination(), targetGraph);
GraphConnection copy = new GraphConnection(targetGraph,
edge.getStyle(), source, target);
copy.setText(edge.getText());
copy.setData(edge.getData());
copy.setLineStyle(edge.getLineStyle());
return copy;
}
private GraphNode copy(GraphNode node, Graph targetGraph) {
GraphNode find = find(node, targetGraph);
if (find == null) {
GraphNode copy = new GraphNode(targetGraph, node.getStyle(),
node.getText());
copy.setImage(node.getImage());
copy.setData(node.getData());
return copy;
}
return find; // target already contains the node to copy over
}
private GraphNode find(GraphNode node, Graph graph) {
for (Object o : graph.getNodes()) {
GraphNode n = (GraphNode) o;
if (node.getData() != null && node.getData().equals(n.getData())) {
return n;
}
}
return null;
}
}
| 33.364706 | 81 | 0.672779 |
2fe01ec5c936a0fa77dc6a667fff5a292d90489c | 80 | /**
* This package contains jOOQ's exceptions.
*/
package org.jooq.exception;
| 16 | 43 | 0.7125 |
75dfba9fdcba406b980c7b4d230f6fd86a83f380 | 2,178 | package com.carrotsearch.hppcrt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Assert;
import org.junit.Test;
/**
*
*/
public class AbstractIteratorTest
{
public static class RangeIterator extends AbstractIterator<Integer>
{
int start;
int count;
public RangeIterator(final int start, final int count)
{
this.start = start;
this.count = count;
}
@Override
protected Integer fetch()
{
if (this.count == 0)
{
return done();
}
this.count--;
return this.start++;
}
}
@Test
public void testEmpty()
{
final RangeIterator i = new RangeIterator(1, 0);
Assert.assertFalse(i.hasNext());
Assert.assertFalse(i.hasNext());
}
@Test(expected = NoSuchElementException.class)
public void testEmptyExceptionOnNext()
{
final RangeIterator i = new RangeIterator(1, 0);
i.next();
}
@Test
public void testNonEmpty()
{
final RangeIterator i = new RangeIterator(1, 1);
Assert.assertTrue(i.hasNext());
Assert.assertTrue(i.hasNext());
i.next();
Assert.assertFalse(i.hasNext());
Assert.assertFalse(i.hasNext());
try
{
i.next();
Assert.fail();
} catch (final NoSuchElementException e)
{
// expected.
}
}
@Test
public void testValuesAllRight()
{
Assert.assertEquals(Arrays.asList(1), AbstractIteratorTest.addAll(new RangeIterator(1, 1)));
Assert.assertEquals(Arrays.asList(1, 2), AbstractIteratorTest.addAll(new RangeIterator(1, 2)));
Assert.assertEquals(Arrays.asList(1, 2, 3), AbstractIteratorTest.addAll(new RangeIterator(1, 3)));
}
private static <T> List<T> addAll(final Iterator<T> i)
{
final List<T> t = new ArrayList<T>();
while (i.hasNext()) {
t.add(i.next());
}
return t;
}
}
| 23.673913 | 106 | 0.570707 |
b2741166b42de3bfc8f81a236724179fd2052e62 | 7,738 | /*
* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.
*/
package com.supermap.gaf.authority.service.impl;
import com.supermap.gaf.authority.commontype.AuthRoleApi;
import com.supermap.gaf.authority.constant.CacheGroupConstant;
import com.supermap.gaf.authority.constant.CommonConstant;
import com.supermap.gaf.authority.constant.DbFieldNameConstant;
import com.supermap.gaf.authority.dao.AuthRoleApiMapper;
import com.supermap.gaf.authority.service.AuthRoleApiService;
import com.supermap.gaf.authority.service.AuthRoleService;
import com.supermap.gaf.authority.vo.AuthRoleApiSelectVo;
import com.supermap.gaf.authority.vo.RoleApiVo;
import com.supermap.gaf.exception.GafException;
import com.supermap.gaf.utils.LogUtil;
import org.slf4j.Logger;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* 角色接口服务实现类
* @author yangdong
* @date:2021/3/25
*
*/
@Service
public class AuthRoleApiServiceImpl implements AuthRoleApiService {
private final AuthRoleApiMapper authRoleApiMapper;
private final AuthRoleService authRoleService;
private static final Logger logger = LogUtil.getLocLogger(AuthRoleApiServiceImpl.class);
public AuthRoleApiServiceImpl(AuthRoleApiMapper authRoleApiMapper, AuthRoleService authRoleService) {
this.authRoleApiMapper = authRoleApiMapper;
this.authRoleService = authRoleService;
}
@Override
public AuthRoleApi getById(String roleApiId) {
if (StringUtils.isEmpty(roleApiId)) {
throw new GafException("roleApiId不能为空");
}
return authRoleApiMapper.select(roleApiId);
}
@Cacheable(value = CacheGroupConstant.ROLE_API, key = "#roleId", unless = "#result == null")
@Override
public List<AuthRoleApi> listByRole(String roleId) {
if (StringUtils.isEmpty(roleId)) {
throw new GafException("roleId不能为空");
}
return authRoleApiMapper.listByRole(roleId);
}
@Override
public List<AuthRoleApi> getByRoleId(String roleId, Boolean status){
if(StringUtils.isEmpty(roleId)){
return new ArrayList<>();
}
return authRoleApiMapper.getByRoleId(roleId,status);
}
@CacheEvict(value = CacheGroupConstant.ROLE_API, key = "#roleApiVo.roleId")
@Override
public void handleRoleApi(RoleApiVo roleApiVo){
String roleId = roleApiVo.getRoleId();
if(roleId == null || StringUtils.isEmpty(roleId)){
throw new GafException("角色id为空");
}
logger.info(roleId);
if(authRoleService.getById(roleId)==null){
throw new GafException("角色不存在:" + roleId);
}
List<String> newList = roleApiVo.getApiList();
List<String> oldList = getByRoleId(roleId,true).stream().map(AuthRoleApi ::getResourceApiId).collect(Collectors.toList());
List<String> addList = new ArrayList<>();
List<String> removeList = new ArrayList<>();
newList.forEach(item ->{
if(!oldList.contains(item)){
addList.add(item);
}
});
logger.info("toadd:");
oldList.forEach(item ->{
if(!newList.contains(item)){
removeList.add(item);
}
});
logger.info("toremove:");
//新增或修改
if(!CollectionUtils.isEmpty(addList)){
List<AuthRoleApi> addRoleApiList = new ArrayList<>();
List<String> updateList = new ArrayList<>();
addList.forEach(item->{
AuthRoleApi oldRoleApi = getByRoleAndApi(roleId,item,false);
if(oldRoleApi!=null){
updateList.add(oldRoleApi.getRoleApiId());
}else{
AuthRoleApi authRoleApi = AuthRoleApi.builder()
.resourceApiId(item)
.roleId(roleId)
.status(true)
.sortSn(1)
.build();
addRoleApiList.add(authRoleApi);
}
});
//批量修改
if(!CollectionUtils.isEmpty(updateList)){
batchUpdate(updateList);
}
//批量新增
if(!CollectionUtils.isEmpty(addRoleApiList)){
batchInsertRoleApi(addRoleApiList);
}
}
//禁用
if(!CollectionUtils.isEmpty(removeList)){
//根据角色id和接口id获取角色接口关联id
List<String> roleApiIds = new ArrayList<>();
removeList.forEach(item->{
AuthRoleApi authRoleApi = getByRoleAndApi(roleId,item,true);
if(authRoleApi!=null){
roleApiIds.add(authRoleApi.getRoleApiId());
}
});
batchDelete(roleApiIds);
}
}
public AuthRoleApi getByRoleAndApi(String roleId, String apiId,Boolean status){
if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(apiId)){
return null;
}
return authRoleApiMapper.getByRoleAndApi(roleId, apiId,status);
}
@Override
public Map<String, Object> pageList(AuthRoleApiSelectVo authRoleApiSelectVo) {
if (authRoleApiSelectVo.getPageSize() == null || authRoleApiSelectVo.getPageSize() == 0) {
authRoleApiSelectVo.setPageSize(50);
}
List<AuthRoleApi> pageList;
if (authRoleApiSelectVo.getOffset() == null || authRoleApiSelectVo.getOffset() < CommonConstant.OFFSET_MAX_FOR_SQL_BETTER) {
pageList = authRoleApiMapper.pageList(authRoleApiSelectVo);
} else {
pageList = authRoleApiMapper.bigOffsetPageList(authRoleApiSelectVo);
}
int totalCount = authRoleApiMapper.pageListCount();
Map<String, Object> result = new HashMap<>(2);
result.put(DbFieldNameConstant.PAGE_LIST, pageList);
result.put(DbFieldNameConstant.TOTAL_COUNT, totalCount);
return result;
}
@Override
public Map<String, Object> searchList(AuthRoleApiSelectVo authRoleApiSelectVo) {
if (authRoleApiSelectVo.getPageSize() == null || authRoleApiSelectVo.getPageSize() == 0) {
authRoleApiSelectVo.setPageSize(50);
}
List<AuthRoleApi> pageList = authRoleApiMapper.searchList(authRoleApiSelectVo);
Integer totalCount = authRoleApiMapper.countOneField(authRoleApiSelectVo.getSearchFieldName(), authRoleApiSelectVo.getSearchFieldValue());
Map<String, Object> result = new HashMap<>(2);
result.put(DbFieldNameConstant.PAGE_LIST, pageList);
result.put(DbFieldNameConstant.TOTAL_COUNT, totalCount);
return result;
}
@Override
public void batchInsertRoleApi(List<AuthRoleApi> authRoleApis){
if (authRoleApis != null && !CollectionUtils.isEmpty(authRoleApis)) {
authRoleApis.forEach(authRoleApi -> authRoleApi.setRoleApiId(UUID.randomUUID().toString()));
authRoleApiMapper.batchInsert(authRoleApis);
}
}
@Override
public void batchDelete(List<String> roleApiIds) {
authRoleApiMapper.batchDelete(roleApiIds);
}
/**
* 批量修改
* @author zhm
**/
public void batchUpdate(List<String> authRoleApiIds){
authRoleApiMapper.batchUpdate(authRoleApiIds);
}
}
| 37.931373 | 146 | 0.65146 |
3935c75e7a7c6e69bfa930c9367edecdbc5a56d7 | 4,615 | package net.jselby.escapists.data;
import net.jselby.escapists.data.chunks.ReflectionsHandle;
import net.jselby.escapists.util.ByteReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* Decodes chunks into a List.
*
* @author j_selby
*/
public class ChunkDecoder {
/**
* Decodes a series of Chunks.
* @param buf The buffer to read from
* @return A parsed list of Chunks
*/
public static List<Chunk> decodeChunk(ByteReader buf) {
ExecutorService threadManager = Executors.newCachedThreadPool();
Inflater inflater = new Inflater();
ArrayList<Chunk> chunks = new ArrayList<Chunk>();
while(true) {
int id = buf.getShort();
ChunkType type = ChunkType.getTypeForID(id);
int flags = buf.getShort();
int size = buf.getInt();
if (type == ChunkType.Last) {
if (size != 0) {
buf.skipBytes(size);
}
break;
}
byte[] data = buf.getBytes(size);
if ((flags & 1) != 0) { // Compression
if ((flags & 2) != 0) { // Encryption
byte[] dataCopy = new byte[size - 4];
System.arraycopy(data, 4, dataCopy, 0, size - 4);
dataCopy = ChunkTransforms.transform(dataCopy);
System.arraycopy(dataCopy, 0, data, 4, size - 4);
}
ByteReader decompressionSizing = new ByteReader(data);
int decompressedSize = decompressionSizing.getInt();
decompressionSizing.getInt(); // Compressed size
data = decompressionSizing.getBytes(size - decompressionSizing.getPosition());
try {
byte[] decompData = new byte[decompressedSize];
inflater.reset();
inflater.setInput(data);
inflater.inflate(decompData);
data = decompData;
} catch (DataFormatException e) {
System.out.printf("Failed to inflate chunk %d (%s): %s.\n", id, type.name(), e.getMessage());
}
} else if ((flags & 2) != 0) { // Encryption
data = ChunkTransforms.transform(data);
}
//System.out.println(type.name() + " (" + id + "): " + data.length + "/" + size + " bytes, " + flags + " flags.");
// TODO: Clean up this mess, create our own runnable tracker
// Attempt to find a copy
try {
Class<?> potentialChunkDef = Class.forName(ReflectionsHandle.class.getPackage().getName() + "." + type.name());
final Chunk chunk = potentialChunkDef.asSubclass(Chunk.class).newInstance();
final byte[] finalData = data;
threadManager.submit(new Runnable() {
@Override
public void run() {
try {
chunk.init(new ByteReader(ByteBuffer.wrap(finalData).order(ByteOrder.LITTLE_ENDIAN)), finalData.length);
} catch (Exception e) {
e.printStackTrace();
}
}
});
chunks.add(chunk);
} catch (ClassNotFoundException e) {
if (type == ChunkType.Unknown) {
System.err.printf("Failed to find a chunk representation for ID: %d.\n", id);
} else {
System.err.printf("Failed to find a chunk representation for \"%s\" (ID: %d).\n", type.name(), id);
}
} catch (InstantiationException e) {
System.err.printf("Failed to create chunk representation for \"%s\" (ID: %d): ", type.name(), id);
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.printf("Failed to create chunk representation for \"%s\" (ID: %d): ", type.name(), id);
e.printStackTrace();
}
}
try {
threadManager.shutdown();
threadManager.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
return chunks;
}
}
| 37.827869 | 132 | 0.528494 |
f6bc8d6bb424c564e67399da9f88804d72c16b31 | 1,635 | /*
* This class is distributed as part of the Botania Mod.
* Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package vazkii.botania.common.item.equipment.bauble;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import vazkii.botania.api.mana.ManaItemHandler;
public class ItemMiningRing extends ItemBauble {
public ItemMiningRing(Properties props) {
super(props);
}
@Override
public void onWornTick(ItemStack stack, LivingEntity entity) {
if (entity instanceof Player player && !player.level.isClientSide) {
int manaCost = 5;
boolean hasMana = ManaItemHandler.instance().requestManaExact(stack, player, manaCost, false);
if (!hasMana) {
onUnequipped(stack, player);
} else {
if (player.getEffect(MobEffects.DIG_SPEED) != null) {
player.removeEffect(MobEffects.DIG_SPEED);
}
player.addEffect(new MobEffectInstance(MobEffects.DIG_SPEED, Integer.MAX_VALUE, 1, true, true));
}
if (player.attackAnim == 0.25F) {
ManaItemHandler.instance().requestManaExact(stack, player, manaCost, true);
}
}
}
@Override
public void onUnequipped(ItemStack stack, LivingEntity player) {
MobEffectInstance effect = player.getEffect(MobEffects.DIG_SPEED);
if (effect != null && effect.getAmplifier() == 1) {
player.removeEffect(MobEffects.DIG_SPEED);
}
}
}
| 29.727273 | 100 | 0.744343 |
31ec4ce4ad6ec0fdacbe16a9e72c4cce1179121b | 10,733 | /*
Copyright: All contributers to the Umple Project
This file is made available subject to the open source license found at:
http://umple.org/license
*/
package cruise.umple.compiler;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import org.junit.*;
import cruise.umple.parser.ErrorTypeSingleton;
import cruise.umple.parser.ParseResult;
import cruise.umple.parser.analysis.RuleBasedParser;
import cruise.umple.util.SampleFileWriter;
public class FilterTest
{
UmpleFile uFile;
UmpleModel model;
String pathToInput;
String umpleParserName;
UmpleParser parser;
@Before
public void setUp()
{
SampleFileWriter.createFile("model.ump", "class Student {}");
uFile = new UmpleFile("model.ump");
model = new UmpleModel(new UmpleFile("model.ump"));
umpleParserName = "cruise.umple.compiler.UmpleInternalParser";
pathToInput = SampleFileWriter.rationalize("test/cruise/umple/compiler");
}
@After
public void tearDown()
{
SampleFileWriter.destroy("model.ump");
}
@Test
public void byDefaultNoFilterPresent()
{
assertEquals(0, model.getFilters().size());
}
@Test
public void getFilter_defaultsToNull()
{
assertEquals(null, model.getFilter("aaa"));
}
@Test
public void getFilterTest()
{
model = parse("601_simpleFilter.ump");
assertEquals(1, model.getFilters().size());
assertNotNull(model.getFilter("roles"));
}
@Test
public void isSettableInModel()
{
Filter f = new Filter("aaa");
model.addFilter(f);
model.getFilter("aaa").addValue("Student");
model.getFilter("aaa").addValue("Mentor");
assertEquals(f, model.getFilter("aaa"));
assertEquals("aaa", model.getFilter("aaa").getName());
assertEquals("Student",model.getFilter("aaa").getValue(0));
assertEquals("Mentor",model.getFilter("aaa").getValue(1));
}
@Test
public void hasAssociationTest()
{
Filter f = new Filter("aaa");
assertEquals(false, f.hasAssociation());
f.setAssociationCount(-2);
assertEquals(false, f.hasAssociation());
f.setAssociationCount(0);
assertEquals(false, f.hasAssociation());
f.setAssociationCount(1);
assertEquals(true, f.hasAssociation());
}
@Test
public void hasSuperTest()
{
Filter f = new Filter("aaa");
assertEquals(false, f.hasSuper());
f.setSuperCount(-1);
assertEquals(false, f.hasSuper());
f.setSuperCount(1);
assertEquals(true, f.hasSuper());
}
@Test
public void hasSubTest()
{
Filter f = new Filter("aaa");
assertEquals(false, f.hasSub());
f.setSubCount(0);
assertEquals(false, f.hasSub());
f.setSubCount(1);
assertEquals(true, f.hasSub());
f.setSubCount(-1);
assertEquals(false, f.hasSub());
}
@Test
public void hasNestedFilter()
{
Filter f = new Filter("aaa");
assertEquals(false, f.hasNestedFilter());
f.addFilterValue("bbb");
assertEquals(true, f.hasNestedFilter());
}
@Test
public void isIncluded()
{
Filter f = new Filter("aaa");
f.addValue("Student");
f.addValue("Mentor");
Assert.assertEquals(true, f.isIncluded("Student"));
Assert.assertEquals(false, f.isIncluded("Blah"));
Assert.assertEquals(false, f.isIncluded((String)null));
Assert.assertEquals(true, f.isIncluded(new UmpleClass("Student")));
Assert.assertEquals(false, f.isIncluded(new UmpleClass("Blah")));
Assert.assertEquals(false, f.isIncluded((UmpleClass)null));
}
@Test
public void isEmpty_hasNothing()
{
Filter f = new Filter("bbb");
Assert.assertEquals(true, f.isEmpty());
}
@Test
public void isEmpty_handlesNull()
{
Filter f = new Filter("bbb");
f.addValue(null);
Assert.assertEquals(false, f.isEmpty());
}
@Test
public void isEmpty_hasValues()
{
Filter f = new Filter("bbb");
f.addValue("abc");
Assert.assertEquals(false, f.isEmpty());
}
@Test
public void applyFilter_OnlyKeepListedClasses()
{
model = parse("601_simpleFilter.ump");
model.applyFilter("roles");
Assert.assertEquals(2, model.numberOfUmpleClasses());
}
@Test
public void applyFilter_Association()
{
model = parse("601_simpleFilter.ump");
model.applyFilter("roles");
Assert.assertEquals(1, model.numberOfAssociations());
}
@Test
public void applyFilter_Empty()
{
model = parse("603_defaultFilter.ump");
Assert.assertEquals(3, model.numberOfUmpleClasses());
model.applyFilter(null);
Assert.assertEquals(3, model.numberOfUmpleClasses());
}
@Test
public void applyFilter_IncludeAll()
{
model = parse("603_defaultFilter.ump");
Filter f = new Filter("includeAll");
f.addValue("*");
model.applyFilter("includeAll");
Assert.assertEquals(3, model.numberOfUmpleClasses());
}
@Test
public void applyFilter_NullCheck()
{
Filter f = new Filter("aaa");
model.addUmpleClass("Mentor");
model.addUmpleClass("Student");
model.addFilter(f);
model.getFilter("aaa").addValue(null);
model.applyFilter("aaa");
Assert.assertEquals(0, model.numberOfUmpleClasses());
}
@Test
public void oneAssociationHop()
{
model = parse("602_associationFilter.ump");
Filter f = new Filter("association_one");
f.setAssociationCount(1);
f.addValue("X");
model.addFilter(f);
model.applyFilter("association_one");
Assert.assertEquals(2, model.numberOfUmpleClasses());
ArrayList<String> names = new ArrayList<String>();
names.add("X");
names.add("Y");
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void multipleAssociationHops()
{
model = parse("602_associationFilter.ump");
Filter f = new Filter("association_multiple");
f.setAssociationCount(2);
f.addValue("X");
model.addFilter(f);
model.applyFilter("association_multiple");
Assert.assertEquals(3, model.numberOfUmpleClasses());
ArrayList<String> names = new ArrayList<String>();
names.add("X");
names.add("Y");
names.add("Z");
assertFiltered(names, model.getUmpleClasses());
model = parse("602_associationFilter.ump");
f.setAssociationCount(3);
model.addFilter(f);
model.applyFilter("association_multiple");
Assert.assertEquals(4, model.numberOfUmpleClasses());
names.add("P");
assertFiltered(names, model.getUmpleClasses());
model = parse("602_associationFilter.ump");
f.setAssociationCount(4);
model.addFilter(f);
model.applyFilter("association_multiple");
Assert.assertEquals(5, model.numberOfUmpleClasses());
names.add("Q");
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void applyFilter_includeAllSuperClass()
{
model = parse("604_inheritanceFilter.ump");
Filter f = new Filter("inheritance");
model.addFilter(f);
model.getFilter("inheritance").addValue("Y");
model.applyFilter("inheritance");
ArrayList<String> names = new ArrayList<String>();
names.add("Y");
names.add("Z");
names.add("P");
names.add("Q");
Assert.assertEquals(4, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void applyFilter_overWriteSuper()
{
model = parse("604_inheritanceFilter.ump");
Filter f = new Filter("inheritance");
f.setSuperCount(2);
model.addFilter(f);
model.getFilter("inheritance").addValue("Y");
model.applyFilter("inheritance");
ArrayList<String> names = new ArrayList<String>();
names.add("Y");
names.add("Z");
names.add("P");
Assert.assertEquals(3, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
model = parse("604_inheritanceFilter.ump");
f.setSuperCount(0);
model.addFilter(f);
model.applyFilter("inheritance");
names = new ArrayList<String>();
names.add("Y");
Assert.assertEquals(1, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void applyFilter_defaultSub()
{
model = parse("604_inheritanceFilter.ump");
Filter f = new Filter("inheritance");
model.addFilter(f);
model.getFilter("inheritance").addValue("P");
model.applyFilter("inheritance");
ArrayList<String> names = new ArrayList<String>();
names.add("P");
names.add("Q");
Assert.assertEquals(2, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void applyFilter_overWriteSub()
{
model = parse("604_inheritanceFilter.ump");
Filter f = new Filter("inheritance");
f.setSubCount(2);
model.addFilter(f);
model.getFilter("inheritance").addValue("P");
model.applyFilter("inheritance");
ArrayList<String> names = new ArrayList<String>();
names.add("Y");
names.add("Z");
names.add("P");
names.add("Q");
Assert.assertEquals(4, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
}
@Test
public void applyFilter_NestedFilter()
{
model = parse("601_simpleFilter.ump");
Filter nf = new Filter("nestedFilter");
nf.addFilterValue("StudentFilter");
nf.addFilterValue("MentorFilter");
model.addFilter(nf);
Filter sf = new Filter("StudentFilter");
sf.addValue("Student");
model.addFilter(sf);
Filter mf = new Filter("MentorFilter");
mf.addValue("Mentor");
model.addFilter(mf);
model.applyFilter("nestedFilter");
ArrayList<String> names = new ArrayList<String>();
names.add("Student");
names.add("Mentor");
Assert.assertEquals(2, model.numberOfUmpleClasses());
assertFiltered(names, model.getUmpleClasses());
}
private void assertFiltered(ArrayList<String> names, List<UmpleClass> list)
{
ArrayList<String> className = new ArrayList<String>();
for(UmpleClass c : list)
{
className.add(c.getName());
}
Assert.assertEquals(names, className);
}
public UmpleModel parse(String filename)
{
//String input = SampleFileWriter.readContent(new File(pathToInput, filename));
File file = new File(pathToInput,filename);
ErrorTypeSingleton.getInstance().reset();
model = new UmpleModel(new UmpleFile(pathToInput,filename));
model.setShouldGenerate(false);
RuleBasedParser rbp = new RuleBasedParser();
parser = new UmpleInternalParser(umpleParserName,model,rbp);
ParseResult result = rbp.parse(file);
model.setLastResult(result);
boolean answer = result.getWasSuccess();
if (answer)
{
parser.analyze(false).getWasSuccess();
}
else
{
Assert.fail("Unable to parse " + filename);
}
return model;
}
}
| 26.967337 | 83 | 0.673158 |
636dcbd24947f273e3a19937a46812b6d1ad66b8 | 596 | package com.egzosn.infrastructure.database.splittable;
import java.lang.annotation.*;
/**
* 分表字段标识
* @author egan
* @email egzosn@gmail.com
* @date 2017/11/22
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@SplitTableField
public @interface SplitTable {
/**
* 是否需要主表当成分表的前缀,
* @return 是否主表当成分表的前缀
*/
boolean prefix() default true;
/**
* 获取表名称的处理器 默认字段值处理器
* @return 获取表名称的处理器
*/
Class handler() default FieldValueTableHandler.class;
/**
*
* @return 分表所需的字段
*/
String field();
}
| 15.684211 | 57 | 0.63255 |
8d9168f4e0330010636a365ff0d600ff293451fe | 1,089 | package ch.b2btec.bl.domain;
public class Customer {
private final String name;
private final int businessNumber;
private final Profile profile;
public Customer(String name, int businessNumber, Profile profile) {
checkCustomerName(name);
this.name = name;
checkBusinessNumber(businessNumber);
this.businessNumber = businessNumber;
checkNonNull(profile);
this.profile = profile;
}
public String getName() {
return name;
}
public int getBusinessNumber() {
return businessNumber;
}
public Profile getProfile() {
return profile;
}
private static void checkCustomerName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Customer name cannot be null or just blanks");
}
}
private static void checkBusinessNumber(int businessNumber) {
if (businessNumber <= 0) {
throw new IllegalArgumentException("Business number cannot be zero or negative");
}
}
private static void checkNonNull(Profile profile) {
if (profile == null) {
throw new IllegalArgumentException("Profile must not be null");
}
}
}
| 23.170213 | 85 | 0.733701 |
4bbfa83c96b8f3f7c56c9bf2d0041aa07b33d84f | 2,235 | // Source : https://leetcode.com/problems/construct-string-from-binary-tree/
// Author : Kris
// Date : 2020-11-28
/*****************************************************************************************************
*
* You need to construct a string consists of parenthesis and integers from a binary tree with the
* preorder traversing way.
*
* The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the
* empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string
* and the original binary tree.
*
* Example 1:
*
* Input: Binary tree: [1,2,3,4]
* 1
* / \
* 2 3
* /
* 4
*
* Output: "1(2(4))(3)"
* Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the
* unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)".
*
* Example 2:
*
* Input: Binary tree: [1,2,3,null,4]
* 1
* / \
* 2 3
* \
* 4
*
* Output: "1(2()(4))(3)"
* Explanation: Almost the same as the first example, except we can't omit the first parenthesis pair
* to break the one-to-one mapping relationship between the input and the output.
*
******************************************************************************************************/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public String tree2str(TreeNode t) {
if (t == null) {
return "";
}
var left = tree2str(t.left);
var right = tree2str(t.right);
var sb = new StringBuilder();
sb.append(t.val);
if (left != "" || (left == "" && right != "")) {
sb.append('(').append(left).append(')');
}
if (right != "") {
sb.append('(').append(right).append(')');
}
return sb.toString();
}
} | 29.407895 | 104 | 0.491723 |
d8b0d2c03f7da0cbb35bddeb5f568f421a14897d | 403 | package com.github.punchat.am.domain.invite.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties("punchat")
public class DefaultInviteProperties {
private Admin admin = new Admin();
@Getter
@Setter
public static class Admin {
private String email;
}
}
| 21.210526 | 75 | 0.754342 |
3d253aa5abe2af54fc95e155a1535c0a10f6d2e6 | 4,391 | package com.example.activity;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.example.adapter.MyPagerAdapter;
import com.example.adapter.ResourceAdapter;
import com.example.admin.myapplication.R;
import com.example.bean.ResultBean;
import com.example.fragment.DigFragment;
import com.example.fragment.PersonFragment;
import com.example.fragment.VPNFragment;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
private static final String TAG = "MainActivity";
private ViewPager vp_home;
private RadioButton rb_vpn;
private RadioButton rb_dug;
private RadioButton rb_person;
private RadioGroup rg_home;
private View mSpaceLineView;
private ArrayList<RadioButton> radioButtons;
private MyPagerAdapter adapter;
private List<Fragment> fragments;
private long mBackTime = 0L;//记录点击返回键的时间点
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(setContentViewId());
// }
@Override
public int setContentViewId() {
//getWindow().setBackgroundDrawable(null);// 防止过度绘制
return R.layout.activity_main;
}
@Override
public void initView() {
Log.d("xxx","initView被调用");
vp_home = findViewById(R.id.vp_home_activity);//viewpager
rb_vpn = findViewById(R.id.rb_vpn);//vpn按钮
rb_dug = findViewById(R.id.rb_dug);//挖币按钮
rb_person = findViewById(R.id.rb_person);//个人信息按钮
rg_home = findViewById(R.id.rg_home);//RadioGroup
radioButtons = new ArrayList<>();
mSpaceLineView = findViewById(R.id.home_space_line);//分割线
}
@Override
public void initData() {
Log.d("xxx","initData被调用");
radioButtons.add(0, rb_vpn);
radioButtons.add(1, rb_dug);
radioButtons.add(2, rb_person);
rg_home.check(R.id.rb_vpn);
fragments = new ArrayList<>();
fragments.add(new VPNFragment());
fragments.add(new DigFragment());
fragments.add(new PersonFragment());
vp_home.setOffscreenPageLimit(3);
adapter = new MyPagerAdapter(getSupportFragmentManager(),MainActivity.this,fragments);
vp_home.setAdapter(adapter);
vp_home.addOnPageChangeListener(this);
initListenter();
}
private void initListenter() {
rg_home.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_vpn:
vp_home.setCurrentItem(0);
break;
case R.id.rb_dug:
vp_home.setCurrentItem(1);
break;
case R.id.rb_person:
vp_home.setCurrentItem(2);
break;
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
for(int i = 0;i < radioButtons.size();i++) {
if(position == i) {
fragments.get(i).onResume();
} else {
fragments.get(i).onPause();
}
}
if(radioButtons != null) {
radioButtons.get(position).setChecked(true);
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
@Override
public void onBackPressed() {
if(System.currentTimeMillis() - mBackTime < 2000) {
super.onBackPressed();
} else {
mBackTime = System.currentTimeMillis();
Toast.makeText(MainActivity.this,getString(R.string.home_twice_back_exit),Toast.LENGTH_SHORT).show();
}
}
}
| 29.07947 | 113 | 0.634252 |
8dd831e38d4456da405bea13a0ff6512c3a0a7d6 | 2,591 | package me.pavo.ui;
import java.util.Hashtable;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import me.pavo.Main;
import me.pavo.PavoException;
import me.pavo.Post;
import me.pavo.logic.Showable;
import me.pavo.server.Connection;
import me.pavo.server.Future;
import me.pavo.server.FutureCallback;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
public class VideoView extends javax.microedition.lcdui.Canvas implements CommandListener, FutureCallback, Showable {
private Player player;
private VideoControl vidc;
private Form form;
private Waiting waiting;
public VideoView(Form form, String kind, String name, Post post) {
this.form = form;
waiting = new Waiting("Connecting");
waiting.show();
addCommand(new Command("Stop", Command.OK, 1));
setCommandListener(this);
Connection.getInstance().getAttachment(kind, name, post.getId(), Post.ATTACHMENT_VIDEO).addCallback(this);
}
public void commandAction(Command c, Displayable d)
{
stop();
}
private synchronized void play(String url) {
try {
player = Manager.createPlayer(url);
player.prefetch();
player.realize();
javax.microedition.lcdui.Display.getDisplay(Main.INSTANCE).setCurrent(this);
vidc = (VideoControl) ((Player) player).getControl("VideoControl");
vidc.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
vidc.setDisplayFullScreen(true);
vidc.setVisible(true);
player.start();
} catch (Exception e) {
Connection.sendException(this, new PavoException("play", e));
}
}
private synchronized void stop() {
if(player != null) {
vidc.setVisible(false);
try { player.stop(); } catch (Exception e) { }
try { player.close(); } catch (Exception e) { }
try { player.deallocate(); } catch (Exception e) { }
player = null;
}
Display.getInstance().callSerially(new Runnable() {
public void run() {
form.show();
}
});
}
public void callbackFired(Future future) {
String location = (String) ((Hashtable) future.getResult()).get("video");
play(location);
}
protected void paint(Graphics arg0) {
}
public void show() {
javax.microedition.lcdui.Display.getDisplay(Main.INSTANCE).setCurrent(this);
}
} | 28.472527 | 119 | 0.693555 |
2802cd0251ae4396e146e2680b7f0fd866f8a484 | 984 | package com.nickperov.oca_1Z0_803.tests;
public class Test2 {
public static void main(String[] args) {
}
}
class T1 {
public int i;
}
class T2 extends T1 {
private int i;
}
class ChangeTest {
private int myValue = 0;
public void showOne(int myValue){
myValue = myValue;
System.out.println(this.myValue);
}
public void showTwo(int myValue){
this.myValue = myValue;
System.out.println(this.myValue);
}
public static void main(String[] args) {
ChangeTest ct = new ChangeTest();
ct.showOne(100);
ct.showTwo(200);
}
}
class TC extends java.util.ArrayList{
public TC(){
super(100);
System.out.println("TC created");
}
}
/*class TestClass extends TC{
public TestClass(){
System.out.println("TestClass created");
}
public static void main(String[] args){ new TestClass(); }
}
*/
interface AI {
}
interface BI {}
interface II extends AI, BI {
} | 16.677966 | 61 | 0.614837 |
d09ae4a67eb642be47ef36d57544e45b9c8f1769 | 1,404 | /*
* Option control of type Integer
* (these are basically wrappers to ensure our floats stay within a certain range)
*/
package mygame;
/**
*
* @author SeanTheBest
*/
public class ControlInteger {
private int var, min, max;
private int def; // default
public ControlInteger(int var, int min, int max) {
this.var = var;
this.min = min;
this.max = max;
def = var;
}
public int getValue() {
return var;
}
public void setValue(int newVar) {
var = newVar;
}
public int add(int toAdd) {
if (var + toAdd > max) {
var = max;
return var;
}
else {
var += toAdd;
return var;
}
}
public int timesTwo() {
if (var * 2 > max)
var = max;
else
var *= 2;
return var;
}
public int divTwo() {
if (var / 2 < min)
var = min;
else
var /= 2;
return var;
}
public int subtract(int toSub) {
if (var - toSub < min) {
var = min;
return var;
}
else {
var -= toSub;
return var;
}
}
public void reset() {
var = def;
}
}
| 18.972973 | 83 | 0.413818 |
6fbd6eea091f1737d6d9b95ea2d3403d65a4528f | 1,953 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.json.shared;
import java.util.Comparator;
/**
* Defines a simple interface for a list/array.
*
* When used with DTOs:
*
* On the client it is safe to cast this to a
* {@link com.google.collide.json.client.JsoArray}.
*
* Native to JavaScript "sparse" arrays are not supported.
*
* On the server, this is an instance of
* {@link com.google.collide.json.server.JsonArrayListAdapter} which
* is a wrapper around a List.
*
*/
public interface JsonArray<T> {
void add(T item);
void addAll(JsonArray<? extends T> item);
void clear();
boolean contains(T item);
JsonArray<T> copy();
T get(int index);
int indexOf(T item);
boolean isEmpty();
String join(String separator);
T peek();
T pop();
T remove(int index);
Iterable<T> asIterable();
boolean remove(T item);
void reverse();
/**
* Assigns a new value to the slot with specified index.
*
* @throws IndexOutOfBoundsException if index is not in [0..length) range
*/
void set(int index, T item);
/**
* Sorts the array according to the comparator. Mutates the array.
*/
void sort(Comparator<? super T> comparator);
int size();
JsonArray<T> slice(int start, int end);
JsonArray<T> splice(int index, int deleteCount, T value);
JsonArray<T> splice(int index, int deleteCount);
}
| 22.709302 | 75 | 0.694828 |
bab59d091b20d72881b9c8894937c0deec5c8243 | 25,984 | /*
* 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.facebook.presto.execution;
import com.facebook.presto.OutputBuffers;
import com.facebook.presto.ScheduledSplit;
import com.facebook.presto.TaskSource;
import com.facebook.presto.client.FailureInfo;
import com.facebook.presto.event.query.QueryMonitor;
import com.facebook.presto.execution.SharedBuffer.QueueState;
import com.facebook.presto.execution.StateMachine.StateChangeListener;
import com.facebook.presto.execution.TaskExecutor.TaskHandle;
import com.facebook.presto.operator.Driver;
import com.facebook.presto.operator.DriverContext;
import com.facebook.presto.operator.DriverFactory;
import com.facebook.presto.operator.DriverStats;
import com.facebook.presto.operator.PipelineContext;
import com.facebook.presto.operator.TaskContext;
import com.facebook.presto.operator.TaskOutputOperator.TaskOutputFactory;
import com.facebook.presto.sql.analyzer.Session;
import com.facebook.presto.sql.planner.LocalExecutionPlanner;
import com.facebook.presto.sql.planner.LocalExecutionPlanner.LocalExecutionPlan;
import com.facebook.presto.sql.planner.PlanFragment;
import com.facebook.presto.sql.planner.PlanFragment.PlanDistribution;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.util.SetThreadName;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import org.joda.time.DateTime;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static com.facebook.presto.util.Failures.toFailures;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Math.max;
public class SqlTaskExecution
implements TaskExecution
{
private final TaskId taskId;
private final URI location;
private final TaskExecutor taskExecutor;
private final Executor notificationExecutor;
private final TaskStateMachine taskStateMachine;
private final TaskContext taskContext;
private final SharedBuffer sharedBuffer;
private final QueryMonitor queryMonitor;
private final TaskHandle taskHandle;
private final List<WeakReference<Driver>> drivers = new CopyOnWriteArrayList<>();
/**
* Number of drivers that have been sent to the TaskExecutor that have not finished.
*/
private final AtomicInteger remainingDrivers = new AtomicInteger();
// guarded for update only
@GuardedBy("this")
private final ConcurrentMap<PlanNodeId, TaskSource> unpartitionedSources = new ConcurrentHashMap<>();
@GuardedBy("this")
private long maxAcknowledgedSplit = Long.MIN_VALUE;
private final AtomicReference<DateTime> lastHeartbeat = new AtomicReference<>(DateTime.now());
private final PlanNodeId partitionedSourceId;
private final DriverSplitRunnerFactory partitionedDriverFactory;
private final List<DriverSplitRunnerFactory> unpartitionedDriverFactories;
private final AtomicLong nextTaskInfoVersion = new AtomicLong(TaskInfo.STARTING_VERSION);
public static SqlTaskExecution createSqlTaskExecution(Session session,
TaskId taskId,
URI location,
PlanFragment fragment,
List<TaskSource> sources,
OutputBuffers outputBuffers,
LocalExecutionPlanner planner,
DataSize maxBufferSize,
TaskExecutor taskExecutor,
ExecutorService notificationExecutor,
DataSize maxTaskMemoryUsage,
DataSize operatorPreAllocatedMemory,
QueryMonitor queryMonitor,
boolean cpuTimerEnabled)
{
SqlTaskExecution task = new SqlTaskExecution(session,
taskId,
location,
fragment,
outputBuffers,
planner,
maxBufferSize,
taskExecutor,
maxTaskMemoryUsage,
operatorPreAllocatedMemory,
queryMonitor,
notificationExecutor,
cpuTimerEnabled
);
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
task.start();
task.addSources(sources);
task.recordHeartbeat();
return task;
}
}
private SqlTaskExecution(Session session,
TaskId taskId,
URI location,
PlanFragment fragment,
OutputBuffers outputBuffers,
LocalExecutionPlanner planner,
DataSize maxBufferSize,
TaskExecutor taskExecutor,
DataSize maxTaskMemoryUsage,
DataSize operatorPreAllocatedMemory,
QueryMonitor queryMonitor,
Executor notificationExecutor,
boolean cpuTimerEnabled)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
this.taskId = checkNotNull(taskId, "taskId is null");
this.location = checkNotNull(location, "location is null");
this.taskExecutor = checkNotNull(taskExecutor, "driverExecutor is null");
this.notificationExecutor = checkNotNull(notificationExecutor, "notificationExecutor is null");
this.taskStateMachine = new TaskStateMachine(taskId, notificationExecutor);
taskStateMachine.addStateChangeListener(new StateChangeListener<TaskState>()
{
@Override
public void stateChanged(TaskState taskState)
{
if (taskState.isDone()) {
SqlTaskExecution.this.taskExecutor.removeTask(taskHandle);
// make sure buffers are cleaned up
if (taskState != TaskState.FAILED) {
// don't close buffers for a failed query
// closed buffers signal to upstream tasks that everything finished cleanly
sharedBuffer.destroy();
}
}
}
});
this.taskContext = new TaskContext(taskStateMachine,
notificationExecutor,
session,
checkNotNull(maxTaskMemoryUsage, "maxTaskMemoryUsage is null"),
checkNotNull(operatorPreAllocatedMemory, "operatorPreAllocatedMemory is null"),
cpuTimerEnabled);
this.sharedBuffer = new SharedBuffer(
taskId,
notificationExecutor,
checkNotNull(maxBufferSize, "maxBufferSize is null"),
outputBuffers);
sharedBuffer.addStateChangeListener(new StateChangeListener<QueueState>()
{
@Override
public void stateChanged(QueueState taskState)
{
if (taskState == QueueState.FINISHED) {
checkTaskCompletion();
}
}
});
this.queryMonitor = checkNotNull(queryMonitor, "queryMonitor is null");
taskHandle = taskExecutor.addTask(taskId);
LocalExecutionPlan localExecutionPlan = planner.plan(session, fragment.getRoot(), fragment.getSymbols(), new TaskOutputFactory(sharedBuffer));
List<DriverFactory> driverFactories = localExecutionPlan.getDriverFactories();
// index driver factories
DriverSplitRunnerFactory partitionedDriverFactory = null;
ImmutableList.Builder<DriverSplitRunnerFactory> unpartitionedDriverFactories = ImmutableList.builder();
for (DriverFactory driverFactory : driverFactories) {
if (driverFactory.getSourceIds().contains(fragment.getPartitionedSource())) {
checkState(partitionedDriverFactory == null, "multiple partitioned sources are not supported");
partitionedDriverFactory = new DriverSplitRunnerFactory(driverFactory);
}
else {
unpartitionedDriverFactories.add(new DriverSplitRunnerFactory(driverFactory));
}
}
this.unpartitionedDriverFactories = unpartitionedDriverFactories.build();
if (fragment.getDistribution() == PlanDistribution.SOURCE) {
checkArgument(partitionedDriverFactory != null, "Fragment is partitioned, but no partitioned driver found");
}
this.partitionedSourceId = fragment.getPartitionedSource();
this.partitionedDriverFactory = partitionedDriverFactory;
}
}
//
// This code starts registers a callback with access to this class, and this
// call back is access from another thread, so this code can not be placed in the constructor
private void start()
{
// start unpartitioned drivers
List<DriverSplitRunner> runners = new ArrayList<>();
for (DriverSplitRunnerFactory driverFactory : unpartitionedDriverFactories) {
runners.add(driverFactory.createDriverRunner(null, false));
driverFactory.setNoMoreSplits();
}
enqueueDrivers(true, runners);
}
@Override
public TaskId getTaskId()
{
return taskId;
}
@Override
public TaskContext getTaskContext()
{
return taskContext;
}
@Override
public void waitForStateChange(TaskState currentState, Duration maxWait)
throws InterruptedException
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
taskStateMachine.waitForStateChange(currentState, maxWait);
}
}
@Override
public TaskInfo getTaskInfo(boolean full)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
checkTaskCompletion();
TaskState state = taskStateMachine.getState();
List<FailureInfo> failures = ImmutableList.of();
if (state == TaskState.FAILED) {
failures = toFailures(taskStateMachine.getFailureCauses());
}
return new TaskInfo(
taskStateMachine.getTaskId(),
nextTaskInfoVersion.getAndIncrement(),
state,
location,
lastHeartbeat.get(),
sharedBuffer.getInfo(),
getNoMoreSplits(),
taskContext.getTaskStats(),
failures);
}
}
@Override
public void addSources(List<TaskSource> sources)
{
checkNotNull(sources, "sources is null");
checkState(!Thread.holdsLock(this), "Can not add sources while holding a lock on the %s", getClass().getSimpleName());
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
// update our record of sources and schedule drivers for new partitioned splits
Map<PlanNodeId, TaskSource> updatedUnpartitionedSources = updateSources(sources);
// tell existing drivers about the new splits; it is safe to update drivers
// multiple times and out of order because sources contain full record of
// the unpartitioned splits
for (TaskSource source : updatedUnpartitionedSources.values()) {
// tell all the existing drivers this source is finished
for (WeakReference<Driver> driverReference : drivers) {
Driver driver = driverReference.get();
// the driver can be GCed due to a failure or a limit
if (driver != null) {
driver.updateSource(source);
}
else {
// remove the weak reference from the list to avoid a memory leak
// NOTE: this is a concurrent safe operation on a CopyOnWriteArrayList
drivers.remove(driverReference);
}
}
}
}
}
private synchronized Map<PlanNodeId, TaskSource> updateSources(List<TaskSource> sources)
{
Map<PlanNodeId, TaskSource> updatedUnpartitionedSources = new HashMap<>();
// don't update maxAcknowledgedSplit until the end because task sources may not
// be in sorted order and if we updated early we could skip splits
long newMaxAcknowledgedSplit = maxAcknowledgedSplit;
for (TaskSource source : sources) {
PlanNodeId sourceId = source.getPlanNodeId();
if (sourceId.equals(partitionedSourceId)) {
// partitioned split
ImmutableList.Builder<DriverSplitRunner> runners = ImmutableList.builder();
for (ScheduledSplit scheduledSplit : source.getSplits()) {
// only add a split if we have not already scheduled it
if (scheduledSplit.getSequenceId() > maxAcknowledgedSplit) {
// create a new driver for the split
runners.add(partitionedDriverFactory.createDriverRunner(scheduledSplit, true));
newMaxAcknowledgedSplit = max(scheduledSplit.getSequenceId(), newMaxAcknowledgedSplit);
}
}
enqueueDrivers(false, runners.build());
if (source.isNoMoreSplits()) {
partitionedDriverFactory.setNoMoreSplits();
}
}
else {
// unpartitioned split
// update newMaxAcknowledgedSplit
for (ScheduledSplit scheduledSplit : source.getSplits()) {
newMaxAcknowledgedSplit = max(scheduledSplit.getSequenceId(), newMaxAcknowledgedSplit);
}
// create new source
TaskSource newSource;
TaskSource currentSource = unpartitionedSources.get(sourceId);
if (currentSource == null) {
newSource = source;
}
else {
newSource = currentSource.update(source);
}
// only record new source if something changed
if (newSource != currentSource) {
unpartitionedSources.put(sourceId, newSource);
updatedUnpartitionedSources.put(sourceId, newSource);
}
}
}
maxAcknowledgedSplit = newMaxAcknowledgedSplit;
return updatedUnpartitionedSources;
}
@Override
public synchronized void addResultQueue(OutputBuffers outputBuffers)
{
checkNotNull(outputBuffers, "outputBuffers is null");
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
sharedBuffer.setOutputBuffers(outputBuffers);
}
}
private synchronized void enqueueDrivers(boolean forceRunSplit, List<DriverSplitRunner> runners)
{
// schedule driver to be executed
List<ListenableFuture<?>> finishedFutures = taskExecutor.enqueueSplits(taskHandle, forceRunSplit, runners);
checkState(finishedFutures.size() == runners.size(), "Expected %s futures but got %s", runners.size(), finishedFutures.size());
// record new driver
remainingDrivers.addAndGet(finishedFutures.size());
// when driver completes, update state and fire events
for (int i = 0; i < finishedFutures.size(); i++) {
ListenableFuture<?> finishedFuture = finishedFutures.get(i);
final DriverSplitRunner splitRunner = runners.get(i);
Futures.addCallback(finishedFuture, new FutureCallback<Object>()
{
@Override
public void onSuccess(Object result)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
// record driver is finished
remainingDrivers.decrementAndGet();
checkTaskCompletion();
queryMonitor.splitCompletionEvent(taskId, splitRunner.getDriverContext().getDriverStats());
}
}
@Override
public void onFailure(Throwable cause)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
taskStateMachine.failed(cause);
// record driver is finished
remainingDrivers.decrementAndGet();
DriverContext driverContext = splitRunner.getDriverContext();
DriverStats driverStats;
if (driverContext != null) {
driverStats = driverContext.getDriverStats();
}
else {
// split runner did not start successfully
driverStats = new DriverStats();
}
// fire failed event with cause
queryMonitor.splitFailedEvent(taskId, driverStats, cause);
}
}
}, notificationExecutor);
}
}
private Set<PlanNodeId> getNoMoreSplits()
{
ImmutableSet.Builder<PlanNodeId> noMoreSplits = ImmutableSet.builder();
if (partitionedDriverFactory != null && partitionedDriverFactory.isNoMoreSplits()) {
noMoreSplits.add(partitionedSourceId);
}
for (TaskSource taskSource : unpartitionedSources.values()) {
if (taskSource.isNoMoreSplits()) {
noMoreSplits.add(taskSource.getPlanNodeId());
}
}
return noMoreSplits.build();
}
private synchronized void checkTaskCompletion()
{
if (taskStateMachine.getState().isDone()) {
return;
}
// are there more partition splits expected?
if (partitionedDriverFactory != null && !partitionedDriverFactory.isNoMoreSplits()) {
return;
}
// do we still have running tasks?
if (remainingDrivers.get() != 0) {
return;
}
// no more output will be created
sharedBuffer.finish();
// are there still pages in the output buffer
if (!sharedBuffer.isFinished()) {
return;
}
// Cool! All done!
taskStateMachine.finished();
}
@Override
public void cancel()
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
taskStateMachine.cancel();
}
}
@Override
public void fail(Throwable cause)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
taskStateMachine.failed(cause);
}
}
@Override
public BufferResult getResults(String outputId, long startingSequenceId, DataSize maxSize, Duration maxWait)
throws InterruptedException
{
checkNotNull(outputId, "outputId is null");
checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte");
checkNotNull(maxWait, "maxWait is null");
checkState(!Thread.holdsLock(this), "Can not get result data while holding a lock on the %s", getClass().getSimpleName());
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
return sharedBuffer.get(outputId, startingSequenceId, maxSize, maxWait);
}
}
@Override
public void abortResults(String outputId)
{
try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
sharedBuffer.abort(outputId);
}
}
@Override
public void recordHeartbeat()
{
this.lastHeartbeat.set(DateTime.now());
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.add("taskId", taskId)
.add("remainingDrivers", remainingDrivers)
.add("unpartitionedSources", unpartitionedSources)
.toString();
}
private class DriverSplitRunnerFactory
{
private final DriverFactory driverFactory;
private final PipelineContext pipelineContext;
private final AtomicInteger pendingCreation = new AtomicInteger();
private final AtomicBoolean noMoreSplits = new AtomicBoolean();
private DriverSplitRunnerFactory(DriverFactory driverFactory)
{
this.driverFactory = driverFactory;
this.pipelineContext = taskContext.addPipelineContext(driverFactory.isInputDriver(), driverFactory.isOutputDriver());
}
private DriverSplitRunner createDriverRunner(@Nullable ScheduledSplit partitionedSplit, boolean isPartitionedDriver)
{
pendingCreation.incrementAndGet();
// create driver context immediately so the driver existence is recorded in the stats
// the number of drivers is used to balance work across nodes
DriverContext driverContext = pipelineContext.addDriverContext(isPartitionedDriver);
return new DriverSplitRunner(this, driverContext, partitionedSplit);
}
private Driver createDriver(DriverContext driverContext, @Nullable ScheduledSplit partitionedSplit)
{
Driver driver = driverFactory.createDriver(driverContext);
// record driver so other threads add unpartitioned sources can see the driver
// NOTE: this MUST be done before reading unpartitionedSources, so we see a consistent view of the unpartitioned sources
drivers.add(new WeakReference<>(driver));
if (partitionedSplit != null) {
// TableScanOperator requires partitioned split to be added before the first call to process
driver.updateSource(new TaskSource(partitionedSourceId, ImmutableSet.of(partitionedSplit), true));
}
// add unpartitioned sources
for (TaskSource source : unpartitionedSources.values()) {
driver.updateSource(source);
}
pendingCreation.decrementAndGet();
closeDriverFactoryIfFullyCreated();
return driver;
}
private boolean isNoMoreSplits()
{
return noMoreSplits.get();
}
private void setNoMoreSplits()
{
noMoreSplits.set(true);
closeDriverFactoryIfFullyCreated();
}
private void closeDriverFactoryIfFullyCreated()
{
if (isNoMoreSplits() && pendingCreation.get() <= 0) {
driverFactory.close();
}
}
}
private static class DriverSplitRunner
implements SplitRunner
{
private final DriverSplitRunnerFactory driverSplitRunnerFactory;
private final DriverContext driverContext;
@Nullable
private final ScheduledSplit partitionedSplit;
@GuardedBy("this")
private Driver driver;
private DriverSplitRunner(DriverSplitRunnerFactory driverSplitRunnerFactory, DriverContext driverContext, @Nullable ScheduledSplit partitionedSplit)
{
this.driverSplitRunnerFactory = checkNotNull(driverSplitRunnerFactory, "driverFactory is null");
this.driverContext = checkNotNull(driverContext, "driverContext is null");
this.partitionedSplit = partitionedSplit;
}
public synchronized DriverContext getDriverContext()
{
if (driver == null) {
return null;
}
return driver.getDriverContext();
}
@Override
public synchronized boolean isFinished()
{
return driver.isFinished();
}
@Override
public synchronized ListenableFuture<?> processFor(Duration duration)
{
if (driver == null) {
driver = driverSplitRunnerFactory.createDriver(driverContext, partitionedSplit);
}
return driver.processFor(duration);
}
@Override
public synchronized void close()
{
if (driver != null) {
driver.close();
}
}
}
}
| 39.015015 | 156 | 0.627348 |
89a471bd25a07f42786fcb5788d731ef8e385a30 | 921 | package com.microfin.logic.dao;
import java.util.List;
import com.microfin.logic.entity.UserRole;
/**
* 用户角色表操作
*
* @author lipeng 2015-03-25
*/
public interface UserRoleDao {
List<UserRole> getUserRoleList(UserRole userRole);
List<UserRole> getRoleInfoList(UserRole userRole);
int getCountByRoleId(String r_id);
List<String> selectUserId(UserRole userRole);
void insertRoleData(UserRole userRole);
void deleteRole(String ur_id);
String getUAccount(String xzrl);
int isAdmin(String userAccount);
List<UserRole> selectUserRoleList(String u_account);
/**
* 通过角色名找到对应的人
*
* @param roleName
* @return
*/
List<UserRole> getUserRolesByRoleName(String roleName);
boolean isExistRole(String pro_no);
boolean selectAministrtor(String u_account);
/**
* 删除用户时同时删除用户权限表下的权限
*/
void deleteRoleByAccount(String u_id);
}
| 18.795918 | 59 | 0.697068 |
f034549dc74bd49865ee0f8055c452ec62cbc244 | 2,545 | package com.d0klabs.vashinternet_client.ui.sklad;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.d0klabs.vashinternet_client.R;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> implements ItemTouchHelperCallback.ItemTouchHelperAdapter {
private static final String TAG = "CustomAdapter";
public static final int TITLE = 0;
public static final int LOAD_MORE = 1;
public static Button[] buttons;
private boolean hasLoadButton = true;
public static final int HEADER = 1;
private static final int ITEM = 2;
@Override
public void onItemDismiss(int position) {
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
public ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView;
}
}
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == TITLE) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_item_list, viewGroup, false);
return new ViewHolder(v);
} else if (viewType == LOAD_MORE) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_item_list_more, viewGroup, false);
return new ViewHolder(v);
}else {
return null;
}
}
@Override
public void onBindViewHolder(CustomAdapter.ViewHolder viewHolder, int position) {
Log.d(TAG, "Element " + position + " set.");
viewHolder.text.setText(Items.recyclerItemList[position]);
}
public boolean isHasLoadButton() {
return hasLoadButton;
}
public void setHasLoadButton(boolean hasLoadButton) {
this.hasLoadButton = hasLoadButton;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
/*
if (hasLoadButton) {
return buttons.length; //+1
} else {
return buttons.length;
}
*/
return Items.recyclerItemList.length;
}
@Override
public int getItemViewType(int position) {
if (position < getItemCount()) {
return TITLE;
} else {
return LOAD_MORE;
}
}
}
| 26.510417 | 141 | 0.646365 |
f3751efbb4f1476106b5a0c6b0ef67d6b748c6dd | 2,317 | package com.jbtits.otus.lecture12.web;
import com.jbtits.otus.lecture12.auth.AuthFilter;
import com.jbtits.otus.lecture12.auth.AuthService;
import com.jbtits.otus.lecture12.cache.CacheService;
import com.jbtits.otus.lecture12.cache.CacheServiceImpl;
import com.jbtits.otus.lecture12.dbService.DBService;
import com.jbtits.otus.lecture12.dbService.DBServiceHibernateImpl;
import com.jbtits.otus.lecture12.dbService.dataSets.DataSet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.servlet.DispatcherType;
import java.util.EnumSet;
public class WebServer {
private final static int PORT = 8080;
private final DBService dbService;
private final CacheService<String, DataSet> cacheService;
private final AuthService authService;
private int port;
WebServer(int port) {
cacheService = new CacheServiceImpl<>(10, 1000);
dbService = new DBServiceHibernateImpl(cacheService);
authService = new AuthService(dbService);
this.port = port;
}
private void start() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new CacheStatisticsServlet(cacheService, dbService)), "/");
context.addFilter(new FilterHolder(new AuthFilter(dbService)), "/*", EnumSet.of(DispatcherType.ASYNC,
DispatcherType.ERROR,
DispatcherType.FORWARD,
DispatcherType.INCLUDE,
DispatcherType.REQUEST));
Server server = new Server(port);
server.setHandler(new HandlerList(context));
try {
server.start();
server.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
int port = PORT;
if (args.length > 1 && args[0].equals("-p")) {
int portArg = Integer.parseInt(args[1]);
if (portArg > 0) {
port = portArg;
}
}
WebServer webServer = new WebServer(port);
webServer.start();
}
}
| 34.58209 | 109 | 0.68839 |
6d20ea0711cfb0b8e927e4b35aea7377ba664b1d | 16,879 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UserInterface.Government;
import business.Enterprise.Enterprise;
import business.Investment.Investment;
import business.Investment.InvestmentItem;
import business.Utilities;
import business.WorkQueue.GovernmentWorkRequest;
import java.awt.CardLayout;
import java.awt.Color;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
/**
*
* @author Vrushali Shah
*/
public class ViewCustomerDetailsJPanel extends javax.swing.JPanel {
private JPanel viewCustomerHistoryContainer;
private GovernmentWorkRequest gwr;
/**
* Creates new form ViewCustomerDetailsJPanel
*/
public ViewCustomerDetailsJPanel(JPanel viewCustomerHistoryContainer, GovernmentWorkRequest gwr) {
initComponents();
this.viewCustomerHistoryContainer = viewCustomerHistoryContainer;
this.gwr = gwr;
populateEnterpriseTable();
txtID.setText(String.valueOf(gwr.getCustomer().getId()));
txtCustName.setText(gwr.getCustomer().getFirstName() + " " + gwr.getCustomer().getLastName());
}
private void populateEnterpriseTable() {
DefaultTableModel model = (DefaultTableModel) tblDetails.getModel();
model.setRowCount(0);
for (Map.Entry<Enterprise, List<Investment>> entry : gwr.getEnterpriseInvestMap().entrySet()) {
Enterprise enterprise = entry.getKey();
Object[] row = new Object[3];
row[0] = enterprise.getEnterpriseId();
row[1] = enterprise;
row[2] = entry.getValue() == null ? "Waiting for data" : entry.getValue().size();
model.addRow(row);
}
}
private void populateInvestments(Enterprise e) {
List<Investment> investmentList = gwr.getEnterpriseInvestMap().get(e);
DefaultTableModel model = (DefaultTableModel) tblEnterpriseInvestments.getModel();
model.setRowCount(0);
for (Investment investment : investmentList) {
for (InvestmentItem item : investment.getInvestmentList()) {
Object[] row = new Object[4];
row[0] = item.getStock();
row[1] = item.getStock().getCompanyName();
row[2] = item.getQuantity();
row[3] = item.getPrice();
model.addRow(row);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblCustId = new javax.swing.JLabel();
txtID = new javax.swing.JTextField();
lblCustId1 = new javax.swing.JLabel();
txtCustName = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
tblEnterpriseInvestments = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
tblDetails = new javax.swing.JTable();
btnEnterpriseInvestments = new javax.swing.JButton();
btnViewCustomerAnalysis = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 255, 255));
lblCustId.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
lblCustId.setForeground(new java.awt.Color(255, 153, 0));
lblCustId.setText("Customer ID:");
txtID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIDActionPerformed(evt);
}
});
lblCustId1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
lblCustId1.setForeground(new java.awt.Color(255, 153, 0));
lblCustId1.setText("Customer Name");
txtCustName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtCustNameActionPerformed(evt);
}
});
tblEnterpriseInvestments.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Stock Id", "Stock Name", "Quantity", "Price"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblEnterpriseInvestments);
tblDetails.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Enterprise Id", "Enterprise Name", "Number of Investment"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(tblDetails);
btnEnterpriseInvestments.setBackground(new java.awt.Color(0, 153, 153));
btnEnterpriseInvestments.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
btnEnterpriseInvestments.setForeground(new java.awt.Color(255, 255, 255));
btnEnterpriseInvestments.setText("View Enterprise Investments");
btnEnterpriseInvestments.setMaximumSize(new java.awt.Dimension(200, 200));
btnEnterpriseInvestments.setMinimumSize(new java.awt.Dimension(200, 200));
btnEnterpriseInvestments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEnterpriseInvestmentsActionPerformed(evt);
}
});
btnViewCustomerAnalysis.setBackground(new java.awt.Color(0, 153, 153));
btnViewCustomerAnalysis.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
btnViewCustomerAnalysis.setForeground(new java.awt.Color(255, 255, 255));
btnViewCustomerAnalysis.setText("View Customer Analysis");
btnViewCustomerAnalysis.setMaximumSize(new java.awt.Dimension(200, 200));
btnViewCustomerAnalysis.setMinimumSize(new java.awt.Dimension(200, 200));
btnViewCustomerAnalysis.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnViewCustomerAnalysisActionPerformed(evt);
}
});
btnBack.setBackground(new java.awt.Color(0, 153, 153));
btnBack.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
btnBack.setForeground(new java.awt.Color(255, 255, 255));
btnBack.setText("<<");
btnBack.setMaximumSize(new java.awt.Dimension(200, 200));
btnBack.setMinimumSize(new java.awt.Dimension(200, 200));
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(88, 88, 88)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblCustId1)
.addGap(18, 18, 18)
.addComponent(txtCustName, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblCustId)
.addGap(18, 18, 18)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnViewCustomerAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnBack, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnEnterpriseInvestments, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 901, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 901, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(54, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCustId)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCustId1)
.addComponent(txtCustName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnViewCustomerAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(btnEnterpriseInvestments, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(42, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void txtIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIDActionPerformed
private void txtCustNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtCustNameActionPerformed
private void btnEnterpriseInvestmentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnterpriseInvestmentsActionPerformed
// TODO add your handling code here:
int selectedRow = tblDetails.getSelectedRow();
if (selectedRow < 0) {
JOptionPane.showMessageDialog(null, "Please select the enterprise from table to view investments", "Warning", JOptionPane.WARNING_MESSAGE);
} else {
Enterprise e = (Enterprise) tblDetails.getValueAt(selectedRow, 1);
if (gwr.getEnterpriseInvestMap().get(e) != null) {
populateInvestments(e);
} else {
DefaultTableModel model = (DefaultTableModel) tblEnterpriseInvestments.getModel();
model.setRowCount(0);
JOptionPane.showMessageDialog(null, "Data not received yet", "Infomation", JOptionPane.INFORMATION_MESSAGE);
}
}
}//GEN-LAST:event_btnEnterpriseInvestmentsActionPerformed
private void btnViewCustomerAnalysisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewCustomerAnalysisActionPerformed
// TODO add your handling code here:
Map<String, Integer> stockInv = new HashMap<>();
for (Map.Entry<Enterprise, List<Investment>> customerEntry : gwr.getEnterpriseInvestMap().entrySet()) {
Enterprise enterprise = customerEntry.getKey();
List<Investment> investmentList = customerEntry.getValue();
if (investmentList != null) {
for (Investment inv : investmentList) {
for (InvestmentItem item : inv.getInvestmentList()) {
String companyName = item.getStock().getNetwork().getCountry().name();
if (stockInv.containsKey(companyName)) {
stockInv.put(companyName, stockInv.get(companyName) + 1);
} else {
stockInv.put(companyName, 1);
}
}
}
}
}
if (stockInv.size() == 0) {
return;
}
JFreeChart piechart = ChartFactory.createPieChart(
"Customer Stock Investment",
Utilities.createPieDataset(stockInv), true,
true,
false);
// PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator(
// "Quantity {0} : ({3})", new DecimalFormat("0"), new DecimalFormat("0%"));
// ((PiePlot) piechart.getPlot()).setLabelGenerator(labelGenerator);
//CategoryPlot plot = piechart.getCategoryPlot();
PiePlot plot = (PiePlot) piechart.getPlot();
//plot.setRangeGridlinePaint(Color.ORANGE);
plot.setCircular(true);
plot.setLabelGap(0.01);
ChartFrame frame = new ChartFrame("Pie Chart", piechart);
plot.setBackgroundPaint(Color.white);
frame.setVisible(true);
frame.setSize(800, 800);
}//GEN-LAST:event_btnViewCustomerAnalysisActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
// TODO add your handling code here:
viewCustomerHistoryContainer.remove(this);
CardLayout layout = (CardLayout) viewCustomerHistoryContainer.getLayout();
layout.previous(viewCustomerHistoryContainer);
}//GEN-LAST:event_btnBackActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBack;
private javax.swing.JButton btnEnterpriseInvestments;
private javax.swing.JButton btnViewCustomerAnalysis;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblCustId;
private javax.swing.JLabel lblCustId1;
private javax.swing.JTable tblDetails;
private javax.swing.JTable tblEnterpriseInvestments;
private javax.swing.JTextField txtCustName;
private javax.swing.JTextField txtID;
// End of variables declaration//GEN-END:variables
}
| 47.680791 | 173 | 0.648202 |
db80ee4e12d3ccb581d269dea69d00ccea6bea37 | 728 | package com.zup.propostas.controller.dto;
import java.time.LocalDateTime;
public class CarteiraCartaoApiResponse {
private String id;
private String email;
private LocalDateTime associadoEm;
private String emissor;
public CarteiraCartaoApiResponse(String id, String email, LocalDateTime associadoEm, String emissor) {
this.id = id;
this.email = email;
this.associadoEm = associadoEm;
this.emissor = emissor;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
public LocalDateTime getAssociadoEm() {
return associadoEm;
}
public String getEmissor() {
return emissor;
}
}
| 21.411765 | 106 | 0.653846 |
38f44c27d447ece4b79dd8be76e0f04ff4957764 | 4,549 | package org.narrative.network.customizations.narrative.reputation;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.narrative.common.persistence.DAOObject;
import org.narrative.common.persistence.OID;
import org.narrative.common.persistence.hibernate.HibernateInstantType;
import org.narrative.common.persistence.hibernate.IntegerEnumType;
import org.narrative.common.util.UnexpectedError;
import org.narrative.network.customizations.narrative.reputation.dao.EventMessageDAO;
import org.narrative.network.shared.daobase.NetworkDAOImpl;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Proxy;
import org.hibernate.annotations.Type;
import org.narrative.shared.event.Event;
import org.narrative.shared.event.reputation.ReputationEvent;
import org.narrative.shared.redisson.codec.FinalClassFriendlyJsonJacksonCodec;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
/**
* Date: 2018-12-11
* Time: 12:48
*
* @author jonmark
*/
@Entity
@Proxy
@Getter
@Setter
public class EventMessage implements DAOObject<EventMessageDAO> {
private static final ObjectMapper serializationMapper = new FinalClassFriendlyJsonJacksonCodec().getObjectMapper();
@Id
@Column(columnDefinition = "binary(16)")
private UUID eventId;
@NotNull
@Type(type = IntegerEnumType.TYPE)
private EventMessageStatus status;
@NotNull
@Column(columnDefinition = "mediumtext")
private String eventJson;
@NotNull
@Type(type = HibernateInstantType.TYPE)
private Instant creationDatetime;
@Type(type = HibernateInstantType.TYPE)
private Instant sendDatetime;
@Type(type = HibernateInstantType.TYPE)
private Instant lastSentDatetime;
private int sendCount;
private int failCount;
private int retryCount;
/**
* @deprecated for hibernate use only
*/
public EventMessage() {}
public EventMessage(Event event) {
// jw: let's use the same PK as the event.
this.eventId = event.getEventId();
// jw: easy enough, we just created this object.
this.creationDatetime = Instant.now();
// jw: let's queue this for sending right now.
this.status = EventMessageStatus.QUEUED;
this.sendDatetime = Instant.now();
// jw: let's serialize the event into a string so that it can be read out on the other side. After this point,
// we should have no reason to deserialize this object ourselves.
try {
// jw: using the JsonJacksonCodecs object mapper so that we are consistent with Redis
this.eventJson = serializationMapper.writeValueAsString(event);
} catch (IOException e) {
throw UnexpectedError.getRuntimeException("Failed creating json from event/" + event.getClass().getSimpleName(), e);
}
}
@Transient
@Override
@Deprecated
public OID getOid() {
throw UnexpectedError.getRuntimeException("Should never attempt to get OID for ReputationEvent!");
}
@Override
public void setOid(OID oid) {
throw UnexpectedError.getRuntimeException("Should never attempt to set OID for ReputationEvent!");
}
private transient Event event;
@Transient
public Event getEvent() {
if (event == null) {
try {
// jw: using the JsonJacksonCodecs object mapper so that we are consistent with Redis
event = serializationMapper.readValue(getEventJson(), ReputationEvent.class);
} catch (IOException e) {
throw UnexpectedError.getRuntimeException("Failed creating Event from json/" + getEventJson(), e);
}
}
return event;
}
public void requeueWithExponentialBackoff(int originalCount) {
// jw: if we shift with the original count then the multiplier will be accurate:
// First: 1 << 0 = 1
// Second: 1 << 1 = 2
// Third: 1 << 2 = 4
// and so on. at 10 this should max out at 512
int multiplier = 1 << originalCount;
setSendDatetime(Instant.now().plus(multiplier, ChronoUnit.MINUTES));
setStatus(EventMessageStatus.QUEUED);
}
public static EventMessageDAO dao() {
return NetworkDAOImpl.getDAO(EventMessage.class);
}
}
| 33.448529 | 128 | 0.701473 |
91b219e17de7808f51f3f22fa8876376b4fcae27 | 113 | public class CrashReport {
// Failed to decompile, took too long to decompile: net/minecraft/crash/CrashReport
} | 37.666667 | 84 | 0.787611 |
4679d6319b6861b2f3cff4f0a1c602677ef6cde7 | 9,834 | /*
* Copyright (c) 2015-2018, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software 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.cloudera.labs.envelope.validate;
import com.cloudera.labs.envelope.component.Component;
import com.cloudera.labs.envelope.component.InstantiatedComponent;
import com.cloudera.labs.envelope.component.InstantiatesComponents;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;
import com.typesafe.config.ConfigValueType;
import org.junit.Test;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import static com.cloudera.labs.envelope.validate.ValidationAssert.assertNoValidationFailures;
import static com.cloudera.labs.envelope.validate.ValidationAssert.assertValidationFailures;
public class TestValidator {
// Helps us build anonymous classes that implement multiple interfaces
private interface ValidatableInstantiator extends ProvidesValidations, InstantiatesComponents {}
private interface ValidatableComponent extends ProvidesValidations, Component {}
@Test
public void testValid() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello", ConfigValueType.STRING).build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "world");
Config config = ConfigFactory.parseProperties(configProps);
assertNoValidationFailures(validee, config);
}
@Test
public void testInvalid() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello", ConfigValueType.STRING).build();
}
};
assertValidationFailures(validee, ConfigFactory.empty());
}
@Test
public void testValidWithinInstantiation() {
Properties innerConfigProps = new Properties();
innerConfigProps.setProperty("hello", "world");
final Config innerConfig = ConfigFactory.parseProperties(innerConfigProps);
ProvidesValidations validee = new ValidatableInstantiator() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
@Override
public Set<InstantiatedComponent> getComponents(Config config, boolean configure) {
return Sets.newHashSet(new InstantiatedComponent(new ValidatableComponent() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").build();
}
}, innerConfig, "Inner"));
}
};
assertNoValidationFailures(validee, ConfigFactory.empty());
}
@Test
public void testInvalidWithinInstantiation() {
Properties innerConfigProps = new Properties();
final Config innerConfig = ConfigFactory.parseProperties(innerConfigProps);
ProvidesValidations validee = new ValidatableInstantiator() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
@Override
public Set<InstantiatedComponent> getComponents(Config config, boolean configure) {
return Sets.newHashSet(new InstantiatedComponent(new ValidatableComponent() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").build();
}
}, innerConfig, "Inner"));
}
};
assertValidationFailures(validee, ConfigFactory.empty());
}
@Test
public void testTypeNotSpecifiedAsValidationIsForgiven() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
};
Properties configProps = new Properties();
configProps.setProperty("type", "world");
Config config = ConfigFactory.parseProperties(configProps);
assertNoValidationFailures(validee, config);
}
@Test
public void testValidationThrowsException() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder()
.add(new Validation() {
@Override
public ValidationResult validate(Config config) {
throw new RuntimeException("oops");
}
@Override
public Set<String> getKnownPaths() {
return Sets.newHashSet();
}
})
.build();
}
};
assertNoValidationFailures(validee, ConfigFactory.empty());
}
@Test
public void testInstantiationThrowsException() {
ProvidesValidations validee = new ValidatableInstantiator() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
@Override
public Set<InstantiatedComponent> getComponents(Config config, boolean configure) {
throw new RuntimeException("oops");
}
};
assertValidationFailures(validee, ConfigFactory.empty());
}
@Test
public void testUnrecognizedPaths() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "world");
Config config = ConfigFactory.parseProperties(configProps);
assertValidationFailures(validee, config);
}
@Test
public void testAllowUnrecognizedPaths() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().allowUnrecognizedPaths().build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "world");
Config config = ConfigFactory.parseProperties(configProps);
assertNoValidationFailures(validee, config);
}
@Test
public void testHandlesOwnValidation() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().handlesOwnValidationPath("hello").build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "world");
Config config = ConfigFactory.parseProperties(configProps);
assertNoValidationFailures(validee, config);
}
@Test
public void testEmptyValue() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "");
Config config = ConfigFactory.parseProperties(configProps);
assertValidationFailures(validee, config);
config = config.withValue("hello", ConfigValueFactory.fromAnyRef(null));
assertValidationFailures(validee, config);
}
@Test
public void testAllowEmptyValue() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").allowEmptyValue("hello").build();
}
};
Properties configProps = new Properties();
configProps.setProperty("hello", "");
Config config = ConfigFactory.parseProperties(configProps);
assertNoValidationFailures(validee, config);
config = config.withValue("hello", ConfigValueFactory.fromIterable(
Lists.newArrayList("")));
assertNoValidationFailures(validee, config);
}
@Test
public void testDisabled() {
ProvidesValidations validee = new ProvidesValidations() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").build();
}
};
Map<String, Object> configMap = Maps.newHashMap();
configMap.put(Validator.CONFIGURATION_VALIDATION_ENABLED_PROPERTY, false);
Config config = ConfigFactory.parseMap(configMap);
assertNoValidationFailures(validee, config);
}
@Test
public void testDisabledWithinInstantiation() {
Map<String, Object> innerConfigMap = Maps.newHashMap();
innerConfigMap.put(Validator.CONFIGURATION_VALIDATION_ENABLED_PROPERTY, false);
final Config innerConfig = ConfigFactory.parseMap(innerConfigMap);
ProvidesValidations validee = new ValidatableInstantiator() {
@Override
public Validations getValidations() {
return Validations.builder().build();
}
@Override
public Set<InstantiatedComponent> getComponents(Config config, boolean configure) {
return Sets.newHashSet(new InstantiatedComponent(new ValidatableComponent() {
@Override
public Validations getValidations() {
return Validations.builder().mandatoryPath("hello").build();
}
}, innerConfig, "Inner"));
}
};
assertNoValidationFailures(validee, ConfigFactory.empty());
}
}
| 32.455446 | 98 | 0.701952 |
dec90ad0c56f523f5910e25f01b4449aee2de69e | 4,410 | package com.xyz.states;
import com.xyz.constants.CreditScoreDesc;
import com.xyz.contracts.CreditRatingCheckContract;
import com.xyz.states.schema.LoaningProcessSchemas;
import net.corda.core.contracts.BelongsToContract;
import net.corda.core.contracts.LinearState;
import net.corda.core.contracts.UniqueIdentifier;
import net.corda.core.identity.AbstractParty;
import net.corda.core.identity.Party;
import net.corda.core.schemas.MappedSchema;
import net.corda.core.schemas.PersistentState;
import net.corda.core.schemas.QueryableState;
import net.corda.core.serialization.ConstructorForDeserialization;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@BelongsToContract(CreditRatingCheckContract.class)
public class CreditRatingState implements LinearState, QueryableState {
private Party loaningAgency;
private Party creditAgencyNode;
private String companyName;
private String businessType;
private Long loanAmount;
private Double creditScoreCheckRating;
private CreditScoreDesc creditScoreDesc;
private UniqueIdentifier loanVerificationId;
@ConstructorForDeserialization
public CreditRatingState(Party loaningAgency, Party creditAgencyNode, String companyName, String businessType,
Long loanAmount, Double creditScoreCheckRating, CreditScoreDesc creditScoreDesc,
UniqueIdentifier loanVerificationId) {
this.loaningAgency = loaningAgency;
this.creditAgencyNode = creditAgencyNode;
this.companyName = companyName;
this.businessType = businessType;
this.loanAmount = loanAmount;
this.creditScoreCheckRating = creditScoreCheckRating;
this.creditScoreDesc = creditScoreDesc;
this.loanVerificationId = loanVerificationId;
}
public Party getLoaningAgency() {
return loaningAgency;
}
public void setLoaningAgency(Party loaningAgency) {
this.loaningAgency = loaningAgency;
}
public Party getCreditAgencyNode() {
return creditAgencyNode;
}
public void setCreditAgencyNode(Party creditAgencyNode) {
this.creditAgencyNode = creditAgencyNode;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public Long getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(Long loanAmount) {
this.loanAmount = loanAmount;
}
public Double getCreditScoreCheckRating() {
return creditScoreCheckRating;
}
public void setCreditScoreCheckRating(Double creditScoreCheckRating) {
this.creditScoreCheckRating = creditScoreCheckRating;
}
public CreditScoreDesc getCreditScoreDesc() {
return creditScoreDesc;
}
public void setApplicationStatus(CreditScoreDesc creditScoreDesc) {
this.creditScoreDesc = creditScoreDesc;
}
public UniqueIdentifier getLoanVerificationId() {
return loanVerificationId;
}
public void setLoanVerificationId(UniqueIdentifier loanVerificationId) {
this.loanVerificationId = loanVerificationId;
}
@NotNull
@Override
public UniqueIdentifier getLinearId() {
return loanVerificationId;
}
@NotNull
@Override
public List<AbstractParty> getParticipants() {
return Arrays.asList(loaningAgency, creditAgencyNode);
}
@Override
public PersistentState generateMappedObject(MappedSchema schema) {
if (schema instanceof LoaningProcessSchemas) {
return new LoaningProcessSchemas.PersistentCreditRatingSchema(getLoaningAgency().getName().toString(),
getCreditAgencyNode().getName().toString(), getCompanyName(), getBusinessType(), getLoanAmount(),
getCreditScoreCheckRating(), getCreditScoreDesc().toString(), getLoanVerificationId().getId());
} else {
throw new IllegalArgumentException("Unrecognised schema $schema");
}
}
@Override
public Iterable<MappedSchema> supportedSchemas() {
return Arrays.asList(new LoaningProcessSchemas());
}
}
| 31.726619 | 114 | 0.728118 |
24c857089f6095160a3d4faf0493416a561eaa8c | 13,012 | /****************************************************************
* 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.james.mpt.ant;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import org.apache.james.core.Username;
import org.apache.james.mpt.Runner;
import org.apache.james.mpt.api.ImapFeatures;
import org.apache.james.mpt.api.ImapFeatures.Feature;
import org.apache.james.mpt.api.Monitor;
import org.apache.james.mpt.host.ExternalHostSystem;
import org.apache.james.mpt.protocol.ProtocolSessionBuilder;
import org.apache.james.mpt.user.ScriptedUserAdder;
import org.apache.james.util.Port;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.resources.Union;
/**
* Task executes MPT scripts against a server
* running on a given port and host.
*/
public class MailProtocolTestTask extends Task implements Monitor {
private static final ImapFeatures SUPPORTED_FEATURES = ImapFeatures.of(Feature.NAMESPACE_SUPPORT);
private boolean quiet = false;
private File script;
private Union scripts;
private Optional<Port> port = Optional.empty();
private String host = "127.0.0.1";
private boolean skip = false;
private String shabang = null;
private final Collection<AddUser> users = new ArrayList<>();
private String errorProperty;
/**
* Gets the error property.
*
* @return name of the ant property to be set on error,
* null if the script should terminate on error
*/
public String getErrorProperty() {
return errorProperty;
}
/**
* Sets the error property.
* @param errorProperty name of the ant property to be set on error,
* nul if the script should terminate on error
*/
public void setErrorProperty(String errorProperty) {
this.errorProperty = errorProperty;
}
/**
* Should progress output be suppressed?
* @return true if progress information should be suppressed,
* false otherwise
*/
public boolean isQuiet() {
return quiet;
}
/**
* Sets whether progress output should be suppressed/
* @param quiet true if progress information should be suppressed,
* false otherwise
*/
public void setQuiet(boolean quiet) {
this.quiet = quiet;
}
/**
* Should the execution be skipped?
* @return true if exection should be skipped,
* otherwise false
*/
public boolean isSkip() {
return skip;
}
/**
* Sets execution skipping.
* @param skip true to skip excution
*/
public void setSkip(boolean skip) {
this.skip = skip;
}
/**
* Gets the host (either name or number) against which this
* test will run.
* @return host, not null
*/
public String getHost() {
return host;
}
/**
* Sets the host (either name or number) against which this
* test will run.
* @param host not null
*/
public void setHost(String host) {
this.host = host;
}
/**
* Gets the port against which this test will run.
* @return port number
*/
public int getPort() {
return port
.map(Port::getValue)
.orElseThrow(() -> new RuntimeException("Port must be set"));
}
/**
* Sets the port aginst which this test will run.
* @param port port number
*/
public void setPort(int port) {
this.port = Optional.of(new Port(port));
}
/**
* Gets the script to execute.
* @return file containing test script
*/
public File getScript() {
return script;
}
/**
* Sets the script to execute.
* @param script not null
*/
public void setScript(File script) {
this.script = script;
}
/**
* Gets script shabang.
* This will be substituted for the first server response.
* @return script shabang,
* or null for no shabang
*/
public String getShabang() {
return shabang;
}
/**
* Sets the script shabang.
* When not null, this value will be used to be substituted for the
* first server response.
* @param shabang script shabang,
* or null for no shabang.
*/
public void setShabang(String shabang) {
this.shabang = shabang;
}
@Override
public void execute() throws BuildException {
if (! port.isPresent()) {
throw new BuildException("Port must be set");
}
if (scripts == null && script == null) {
throw new BuildException("Scripts must be specified as an embedded resource collection");
}
if (scripts != null && script != null) {
throw new BuildException("Scripts can be specified either by the script attribute or as resource collections but not both.");
}
for (AddUser user: users) {
user.validate();
}
if (skip) {
log("Skipping excution");
} else if (errorProperty == null) {
doExecute();
} else {
try {
doExecute();
} catch (BuildException e) {
final Project project = getProject();
project.setProperty(errorProperty, e.getMessage());
log(e, Project.MSG_DEBUG);
}
}
}
public void add(ResourceCollection resources) {
if (scripts == null) {
scripts = new Union();
}
scripts.add(resources);
}
private void doExecute() throws BuildException {
for (AddUser userAdder: users) {
userAdder.execute();
}
final ExternalHostSystem host = new ExternalHostSystem(SUPPORTED_FEATURES, getHost(), port.get(), this, getShabang(), null);
final ProtocolSessionBuilder builder = new ProtocolSessionBuilder();
if (scripts == null) {
scripts = new Union();
scripts.add(new FileResource(script));
}
for (final Resource resource : scripts) {
try {
final Runner runner = new Runner();
try {
final InputStream inputStream = resource.getInputStream();
final String name = resource.getName();
builder.addProtocolLines(name == null ? "[Unknown]" : name, inputStream, runner.getTestElements());
runner.runSessions(host);
} catch (UnsupportedOperationException e) {
log("Resource cannot be read: " + resource.getName(), Project.MSG_WARN);
}
} catch (IOException e) {
throw new BuildException("Cannot load script " + resource.getName(), e);
} catch (Exception e) {
log(e.getMessage(), Project.MSG_ERR);
throw new BuildException("[FAILURE] in script " + resource.getName() + "\n" + e.getMessage(), e);
}
}
}
public AddUser createAddUser() {
final AddUser result = new AddUser();
users.add(result);
return result;
}
/**
* Adds a user.
*/
public class AddUser {
private Port port;
private String user;
private String passwd;
private File script;
private String scriptText;
/**
* Gets the port against which the user addition
* script should be executed.
* @return port number
*/
public int getPort() {
return port.getValue();
}
/**
* Sets the port against which the user addition
* script should be executed.
* @param port port number
*/
public void setPort(int port) {
this.port = new Port(port);
}
/**
* Gets the password for the user.
* @return password not null
*/
public String getPasswd() {
return passwd;
}
/**
* Sets the password for the user.
* This will be passed in the user creation script.
* @param passwd not null
*/
public void setPasswd(String passwd) {
this.passwd = passwd;
}
/**
* Gets the name of the user to be created.
* @return user name, not null
*/
public String getUser() {
return user;
}
/**
* Sets the name of the user to be created.
* @param user not null
*/
public void setUser(String user) {
this.user = user;
}
/**
* Sets user addition script.
* @param scriptText not null
*/
public void addText(String scriptText) {
this.scriptText = getProject().replaceProperties(scriptText);
}
/**
* Gets the file containing the user creation script.
* @return not null
*/
public File getScript() {
return script;
}
/**
* Sets the file containing the user creation script.
* @param script not null
*/
public void setScript(File script) {
this.script = script;
}
/**
* Validates mandatory fields have been filled.
*/
void validate() throws BuildException {
if (script == null && scriptText == null) {
throw new BuildException("Either the 'script' attribute must be set, or the body must contain the text of the script");
}
if (script != null && scriptText != null) {
throw new BuildException("Choose either script text or script attribute but not both.");
}
if (port == null) {
throw new BuildException("'port' attribute must be set on AddUser to the port against which the script should run.");
}
}
/**
* Creates a user.
* @throws BuildException
*/
void execute() throws BuildException {
validate();
try {
final File scriptFile = getScript();
final ScriptedUserAdder adder = new ScriptedUserAdder(getHost(), port, MailProtocolTestTask.this);
try (Reader reader = newReader(scriptFile)) {
adder.addUser(Username.of(getUser()), getPasswd(), reader);
}
} catch (Exception e) {
log(e.getMessage(), Project.MSG_ERR);
throw new BuildException("User addition failed: \n" + e.getMessage(), e);
}
}
private Reader newReader(File scriptFile) throws FileNotFoundException {
if (scriptFile == null) {
return new StringReader(scriptText);
}
return new FileReader(scriptFile);
}
}
@Override
public void note(String message) {
if (quiet) {
log(message, Project.MSG_DEBUG);
} else {
log(message, Project.MSG_INFO);
}
}
@Override
public void debug(char character) {
log("'" + character + "'", Project.MSG_DEBUG);
}
@Override
public void debug(String message) {
log(message, Project.MSG_DEBUG);
}
}
| 30.473068 | 138 | 0.562481 |
7e2116273066b6af96c03d48bff30829d5ff524f | 1,520 | package ru.otus.atm;
import ru.otus.atm.cash.Cash;
import ru.otus.atm.cashissuing.CashIssuing;
import ru.otus.atm.command.Command;
import ru.otus.atm.exception.IllegalAmountException;
import ru.otus.atm.storage.CashStorage;
import ru.otus.atm.storage.Storage;
import java.util.stream.Collectors;
public class Atm {
private Storage storage;
public Atm(CashIssuing cashIssuing) {
storage = new CashStorage(cashIssuing);
}
public void putCash(Cash cash) {
storage.put(cash.getBanknotes().collect(Collectors.toList()));
}
public Cash getCash(int amount) throws IllegalAmountException {
return new Cash(storage.get(amount));
}
public int getCashAmount() {
return storage.getBalance();
}
public Snapshot makeSnapshot() {
return new Snapshot(this, storage);
}
public <T> T executeCommand(Command<T> command) {
return command.execute(this);
}
public static class Snapshot {
private final Atm atm;
private final Storage storage;
private final CashStorage.Snapshot storageSnapshot;
public Snapshot(Atm atm, Storage storage) {
this.atm = atm;
storageSnapshot = ((CashStorage) storage).makeSnapshot();
this.storage = storage;
}
public void restore() {
storageSnapshot.restore();
atm.setStorage(storage);
}
}
private void setStorage(Storage storage) {
this.storage = storage;
}
}
| 25.333333 | 70 | 0.652632 |
267f5123224124feb87844e9206d4d50503f80e7 | 449 | package com.everis.alicante.courses.becajava.examples;
public class CursoBecaJavaException extends Exception{
/**
*
*/
private static final long serialVersionUID = 2369097624288196090L;
@Override
public void printStackTrace() {
System.out.println("Ha ocurrido un error por el motivo: " + super.getCause());
for (int i = 0; i < 10; i++) {
int j=0;
if(true){
}
}
}
}
| 14.966667 | 81 | 0.594655 |
698d5f356c8c88673a90e45bec099102f0847b11 | 7,473 | package de.piegames.blockmap.guistandalone;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import de.piegames.blockmap.MinecraftDimension;
import de.piegames.blockmap.renderer.RegionRenderer;
import de.piegames.blockmap.world.Region.LocalSavedRegion;
import de.piegames.blockmap.world.Region.SavedRegion;
import de.piegames.blockmap.world.RegionFolder;
import de.piegames.blockmap.world.RegionFolder.SavedRegionFolder;
import de.piegames.blockmap.world.RegionFolder.WorldRegionFolder;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.Node;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.util.StringConverter;
public abstract class RegionFolderProvider {
private static Log log = LogFactory.getLog(RegionFolderProvider.class);
protected ReadOnlyObjectWrapper<RegionFolder> folder = new ReadOnlyObjectWrapper<>();
public ReadOnlyObjectProperty<RegionFolder> folderProperty() {
return folder.getReadOnlyProperty();
}
public abstract boolean hideSettings();
public abstract List<Node> getGUI();
public abstract void reload();
public abstract String getLocation();
public static class RegionFolderProviderImpl extends RegionFolderProvider {
protected Path regionFolder;
protected RegionRenderer renderer;
protected List<Node> gui = new ArrayList<>();
public RegionFolderProviderImpl(Path regionFolder, RegionRenderer renderer) {
this.regionFolder = regionFolder;
this.renderer = Objects.requireNonNull(renderer);
reload();
}
@Override
public List<Node> getGUI() {
return gui;
}
@Override
public void reload() {
try {
folder.set(WorldRegionFolder.load(regionFolder, renderer));
} catch (IOException e) {
folder.set(null);
log.warn("Could not load world " + regionFolder, e);
}
}
@Override
public String getLocation() {
return regionFolder.toString();
}
@Override
public boolean hideSettings() {
return false;
}
}
public static abstract class SavedFolderProvider<T> extends RegionFolderProvider {
protected T file;
protected RegionRenderer renderer;
protected List<Node> gui = new ArrayList<>();
protected ChoiceBox<String> worldBox;
protected Map<String, JsonObject> worlds;
public SavedFolderProvider(T file) {
this.file = file;
worldBox = new ChoiceBox<>();
worldBox.valueProperty().addListener((o, old, val) -> {
if (old != val)
folder.set(load(val));
});
gui.add(worldBox);
reload();
}
@Override
public List<Node> getGUI() {
return gui;
}
@Override
public void reload() {
try {
worlds = SavedRegionFolder.parseSaved(load());
String selected = worldBox.getValue();
worldBox.setItems(FXCollections.observableList(new ArrayList<>(worlds.keySet())));
if (worlds.keySet().contains(selected))
worldBox.setValue(selected);
else if (!worlds.isEmpty())
worldBox.setValue(worldBox.getItems().get(0));
} catch (IOException e) {
folder.set(null);
log.warn("Could not load world " + file, e);
}
}
protected abstract JsonElement load() throws IOException;
protected abstract SavedRegionFolder<T, ?> load(String world);
@Override
public String getLocation() {
return file.toString();
}
@Override
public boolean hideSettings() {
return true;
}
}
public static class LocalFolderProvider extends SavedFolderProvider<Path> {
public LocalFolderProvider(Path file) {
super(file);
}
@Override
protected JsonElement load() throws IOException {
return new JsonParser().parse(new InputStreamReader(Files.newInputStream(file)));
}
@Override
protected SavedRegionFolder<Path, LocalSavedRegion> load(String world) {
try {
return new RegionFolder.LocalRegionFolder(file, world);
} catch (IOException e) {
log.warn("Could not load world " + world + " from file " + file);
return null;
}
}
}
public static class RemoteFolderProvider extends SavedFolderProvider<URI> {
public RemoteFolderProvider(URI file) {
super(file);
}
@Override
protected JsonElement load() throws IOException {
return new JsonParser().parse(new InputStreamReader(file.toURL().openStream()));
}
@Override
protected SavedRegionFolder<URI, SavedRegion> load(String world) {
try {
return new RegionFolder.RemoteRegionFolder(file, world);
} catch (IOException e) {
log.warn("Could not load world " + world + " from remote file " + file);
return null;
}
}
}
public static class WorldRegionFolderProvider extends RegionFolderProvider {
private static Log log = LogFactory.getLog(WorldRegionFolderProvider.class);
protected Path worldPath;
protected RegionRenderer renderer;
protected List<MinecraftDimension> available;
protected ChoiceBox<MinecraftDimension> dimensionBox;
protected List<Node> gui = new ArrayList<>();
public WorldRegionFolderProvider(Path worldPath, RegionRenderer renderer) {
this.worldPath = worldPath;
this.renderer = renderer;
available = new ArrayList<>(3);
for (MinecraftDimension d : MinecraftDimension.values())
if (Files.exists(worldPath.resolve(d.getRegionPath())) && Files.isDirectory(worldPath.resolve(d.getRegionPath())))
available.add(d);
if (available.isEmpty())
throw new IllegalArgumentException("Not a vaild world folder");
dimensionBox = new ChoiceBox<MinecraftDimension>();
dimensionBox.setItems(FXCollections.observableList(available));
dimensionBox.valueProperty().addListener((observable, oldValue, newValue) -> {
if (oldValue != newValue)
reload();
});
dimensionBox.setValue(available.get(0));
dimensionBox.setConverter(new StringConverter<MinecraftDimension>() {
@Override
public String toString(MinecraftDimension object) {
return object.displayName;
}
@Override
public MinecraftDimension fromString(String string) {
return null;
}
});
dimensionBox.setMaxWidth(Double.POSITIVE_INFINITY);
Label text = new Label("Dimension:");
GridPane.setColumnIndex(text, 0);
GridPane.setColumnIndex(dimensionBox, 1);
gui.add(text);
gui.add(dimensionBox);
reload();
}
@Override
public List<Node> getGUI() {
return gui;
}
@Override
public void reload() {
try {
folder.set(WorldRegionFolder.load(worldPath, dimensionBox.getValue(), renderer, true));
} catch (IOException e) {
folder.set(null);
log.warn("Could not load world " + worldPath, e);
}
}
@Override
public String getLocation() {
return worldPath.toString();
}
@Override
public boolean hideSettings() {
return false;
}
}
public static RegionFolderProvider byPath(Path path, RegionRenderer renderer) {
if (Files.isDirectory(path) && Files.exists(path.resolve("level.dat")))
return new WorldRegionFolderProvider(path, renderer);
else
return new RegionFolderProviderImpl(path, renderer);
}
} | 27.474265 | 118 | 0.728355 |
f014d7a555815119ab6b607522c88dc268a3258e | 88 | /**
* Some Utility classes for JavaFX.
*/
package it.unimore.s273693.deliveru.ui.util; | 22 | 44 | 0.727273 |
8409a6c6e24cd7483e83fde8821810bdf983501a | 1,400 | package com.wang.guava.collections;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.fail;
/**
* @description: Guava BiMap:Value不允许重复
* @author: wei·man cui
* @date: 2020/8/25 11:13
*/
public class BiMapTest {
/**
* BiMap特性:不允许Value重复
*/
@Test
public void testSpecial() {
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
assertThat(biMap.containsValue("2"), equalTo(true));
try {
biMap.put("3", "2");
fail("should not process here.");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 反转 Key-Value键值对
*/
@Test
public void testInverse() {
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
biMap.put("5", "7");
biMap.put("8", "12");
System.out.println(biMap);
BiMap<String, String> inverse = biMap.inverse();
System.out.println(inverse);
}
@Test
public void testCreateAndForcePut(){
HashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "2");
biMap.forcePut("2","2");
System.out.println(biMap);
}
}
| 25.454545 | 61 | 0.59 |
6ad677589b488ae487a38e819047afec1ada0d53 | 126 | public class B {
void foo(String s) {
switch (i) {
case A.ONE :
break;
}
}
} | 15.75 | 24 | 0.365079 |
eac69a85fe2ff3ef1f3e5ee75f5e7471aae187b5 | 1,249 | package se.icus.mag.modsettings.mixin;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.AbstractParentElement;
import net.minecraft.client.gui.Drawable;
import net.minecraft.client.gui.screen.GameMenuScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.TitleScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import se.icus.mag.modsettings.gui.MenuScreensChanger;
@Mixin(value = Screen.class, priority = 1100)
public abstract class ScreenMixin extends AbstractParentElement implements Drawable {
@Inject(method = "init(Lnet/minecraft/client/MinecraftClient;II)V", at = @At("RETURN"))
private void init(MinecraftClient client, int width, int height, CallbackInfo info) {
Screen screen = (Screen) (Object) this;
if (screen instanceof TitleScreen titleScreen) {
MenuScreensChanger.postTitleScreenInit(titleScreen);
} else if (screen instanceof GameMenuScreen gameMenuScreen) {
MenuScreensChanger.postGameMenuScreenInit(gameMenuScreen);
}
}
}
| 43.068966 | 91 | 0.778223 |
2c6fa76c45f99229cb4c32308b83f354dfc10f60 | 5,932 | package com.jeroenvanpienbroek.nativekeyboard.textvalidator;
import android.util.Log;
import com.jeroenvanpienbroek.nativekeyboard.Util;
import org.json.JSONObject;
public class CharacterCondition
{
public enum CharacterConditionOperator
{
VALUE_EQUALS,
VALUE_SMALLER_THAN,
VALUE_SMALLER_THAN_OR_EQUALS,
VALUE_GREATER_THAN,
VALUE_GREATER_THAN_OR_EQUALS,
VALUE_BETWEEN_INCLUSIVE,
VALUE_BETWEEN_EXCLUSIVE,
VALUE_IN_STRING,
INDEX_EQUALS,
INDEX_SMALLER_THAN,
INDEX_SMALLER_THAN_OR_EQUALS,
INDEX_GREATER_THAN,
INDEX_GREATER_THAN_OR_EQUALS,
INDEX_BETWEEN_INCLUSIVE,
INDEX_BETWEEN_EXCLUSIVE,
OCCURENCES_SMALLER_THAN,
OCCURENCES_SMALLER_THAN_OR_EQUALS,
OCCURENCES_GREATER_THAN,
OCCURENCES_GREATER_THAN_OR_EQUALS,
VALUE_SAME_AS_PREVIOUS
}
public static final CharacterConditionOperator[] CHARACTER_CONDITION_OPERATOR_VALUES = CharacterConditionOperator.values();
public CharacterConditionOperator conditionOperator;
public int conditionIntValue1;
public int conditionIntValue2;
public String conditionStringValue;
public CharacterCondition(JSONObject jsonObject)
{
parseJSON(jsonObject);
}
private void parseJSON(JSONObject jsonObject)
{
try
{
conditionOperator = CHARACTER_CONDITION_OPERATOR_VALUES[jsonObject.getInt("conditionOperator")];
conditionIntValue1 = jsonObject.getInt("conditionIntValue1");
conditionIntValue2 = jsonObject.getInt("conditionIntValue2");
conditionStringValue = jsonObject.getString("conditionStringValue");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean isConditionMet(char ch, char[] text, int textLength, int pos, int selectionStartPosition)
{
switch (conditionOperator)
{
case VALUE_EQUALS:
if ((int) ch == conditionIntValue1)
{
return true;
}
break;
case VALUE_SMALLER_THAN:
if ((int) ch < conditionIntValue1)
{
return true;
}
break;
case VALUE_SMALLER_THAN_OR_EQUALS:
if ((int) ch <= conditionIntValue1)
{
return true;
}
break;
case VALUE_GREATER_THAN:
if ((int) ch > conditionIntValue1)
{
return true;
}
break;
case VALUE_GREATER_THAN_OR_EQUALS:
if ((int) ch >= conditionIntValue1)
{
return true;
}
break;
case VALUE_BETWEEN_EXCLUSIVE:
if ((int) ch > conditionIntValue1 && (int) ch < conditionIntValue2)
{
return true;
}
break;
case VALUE_BETWEEN_INCLUSIVE:
if ((int) ch >= conditionIntValue1 && (int) ch <= conditionIntValue2)
{
return true;
}
break;
case VALUE_IN_STRING:
if (conditionStringValue.contains(ch + ""))
{
return true;
}
break;
case INDEX_EQUALS:
if (pos == conditionIntValue1)
{
return true;
}
break;
case INDEX_SMALLER_THAN:
if (pos < conditionIntValue1)
{
return true;
}
break;
case INDEX_SMALLER_THAN_OR_EQUALS:
if (pos <= conditionIntValue1)
{
return true;
}
break;
case INDEX_GREATER_THAN:
if (pos > conditionIntValue1)
{
return true;
}
break;
case INDEX_GREATER_THAN_OR_EQUALS:
if (pos >= conditionIntValue1)
{
return true;
}
break;
case INDEX_BETWEEN_EXCLUSIVE:
if (pos > conditionIntValue1 && pos < conditionIntValue2)
{
return true;
}
break;
case INDEX_BETWEEN_INCLUSIVE:
if (pos >= conditionIntValue1 && pos <= conditionIntValue2)
{
return true;
}
break;
case OCCURENCES_SMALLER_THAN:
if (Util.countOccurences(ch, text, textLength) < conditionIntValue2)
{
return true;
}
break;
case OCCURENCES_SMALLER_THAN_OR_EQUALS:
if (Util.countOccurences(ch, text, textLength) <= conditionIntValue2)
{
return true;
}
break;
case OCCURENCES_GREATER_THAN:
if (Util.countOccurences(ch, text, textLength) > conditionIntValue2)
{
return true;
}
break;
case OCCURENCES_GREATER_THAN_OR_EQUALS:
if (Util.countOccurences(ch, text, textLength) >= conditionIntValue2)
{
return true;
}
break;
case VALUE_SAME_AS_PREVIOUS:
if(pos == 0) { return false; }
if(ch == text[pos - 1]) { return true; }
break;
}
return false;
}
} | 31.553191 | 127 | 0.495617 |
81a126b5e8073f9a44f3fa2a99fdcd31c87765a7 | 16,282 | package com.example.noface.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.core.widget.NestedScrollView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.example.noface.Constants;
import com.example.noface.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class BitmapUtil {
private static final String TAG = "BitmapUtils";
public static byte[] bmpToByteArray(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public static byte[] bmpToByteArrayForWeChat(final Bitmap bmp, final boolean needRecycle) {
int i;
int j;
if (bmp.getHeight() > bmp.getWidth()) {
i = bmp.getWidth();
j = bmp.getWidth();
} else {
i = bmp.getHeight();
j = bmp.getHeight();
}
Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
Canvas localCanvas = new Canvas(localBitmap);
while ( true) {
localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0,i, j), null);
if (needRecycle)
bmp.recycle();
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
localBitmap.compress(CompressFormat.JPEG, 100,
localByteArrayOutputStream);
localBitmap.recycle();
byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
try {
localByteArrayOutputStream.close();
return arrayOfByte;
} catch (Exception e) {
// F.out(e);
}
i = bmp.getHeight();
j = bmp.getHeight();
}
}
private static String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
private Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public static Bitmap getBitmapByView(NestedScrollView scrollView) {
int h = 0;
Bitmap bitmap = null;
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
}
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
scrollView.draw(canvas);
return bitmap;
}
public static Bitmap loadBitmapFromView(View v) {
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
int w = v.getMeasuredWidth();
int h = v.getMeasuredHeight();
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
c.drawColor(Color.WHITE);
/** 如果不设置canvas画布为白色,则生成透明 */
v.layout(0, 0, w, h);
v.draw(c);
v.setDrawingCacheEnabled(false);
return bmp;
}
public static Bitmap loadBitmap(String path) {
Bitmap bm = null;
bm = BitmapFactory.decodeFile(path);
return bm;
}
public static Bitmap loadBitmap(byte[] data, int width, int height) {
Bitmap bm = null;
Options opts = new Options();
opts.inJustDecodeBounds = true;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
int x = opts.outWidth / width;
int y = opts.outHeight / height;
opts.inSampleSize = x > y ? x : y;
opts.inJustDecodeBounds = false;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
return bm;
}
public static void save(Bitmap bm, File file) throws Exception {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
bm.compress(CompressFormat.JPEG, 100, stream);
}
//dstWidth��dstHeight�ֱ�ΪĿ��ImageView�Ŀ��
public static int calSampleSize(Options options, int dstWidth, int dstHeight) {
int rawWidth = options.outWidth;
int rawHeight = options.outHeight;
int inSampleSize = 1;
if (rawWidth > dstWidth || rawHeight > dstHeight) {
float ratioHeight = (float) rawHeight / dstHeight;
float ratioWidth = (float) rawWidth / dstHeight;
inSampleSize = (int) Math.min(ratioWidth, ratioHeight);
}
return inSampleSize;
}
public static Bitmap get(int reqHeight, int reqWidth, String key) {
Options options = new Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = null;
try {
BitmapFactory.decodeStream(new URL(key).openStream(), null, options);
int width = options.outWidth, height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
Options opt = new Options();
opt.inSampleSize = inSampleSize;
opt.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(new URL(key).openStream(), null, opt);
} catch (IOException e) {
LogUtil.e(TAG, "get e = " + e.getMessage().toString());
} catch (OutOfMemoryError e) {
LogUtil.e(TAG, "get OutOfMemoryError e = " + e.getMessage().toString());
System.gc();
}
return bitmap;
}
public static Bitmap getBitmapFromFile(String filePath, int reqHeight, int reqWidth) {
Options options = new Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = null;
try {
FileInputStream fs = null;
fs = new FileInputStream(filePath);
BitmapFactory.decodeFileDescriptor(fs.getFD(), null, options);
Options opt = new Options();
opt.inSampleSize = calSampleSize(options, reqWidth, reqHeight);
LogUtil.i(TAG, "getBitmapFromFile inSampleSize = " + opt.inSampleSize);
opt.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, opt);
} catch (IOException e) {
LogUtil.e(TAG, "get IOException e = " + e.getMessage());
} catch (OutOfMemoryError e) {
LogUtil.e(TAG, "get OutOfMemoryError e = " + e.getMessage());
System.gc();
}
return bitmap;
}
public static Bitmap getBitmapFromRes(Context context, int resId, ImageView imageView) {
if (null == imageView) {
LogUtil.i(TAG, "getBitmapFromRes null==imageView ");
return null;
}
Options options = new Options();
options.inJustDecodeBounds = true;
Options opt = new Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inSampleSize = calSampleSize(options, imageView.getWidth(), imageView.getHeight());
LogUtil.i(TAG, "getBitmapFromRes inSampleSize = " + opt.inSampleSize);
//获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}
public static void loadBitmapToImage(Context mContext, String url, ImageView imageview) {
// LogUtil.i(TAG, "url:" + url);
if (TextUtils.isEmpty(url)) {
BitmapUtil.loadResourceBitmapToImage(mContext, R.drawable.myself, imageview);
} else {
if (!TextUtils.isEmpty(url) && !url.contains("sharingschool.com")) {
url = Constants.FILE_URL + url;
}
try {
Activity activity = (Activity) mContext;
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
Glide.with(mContext).load(url)
.asBitmap()
.placeholder(R.drawable.myself)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.error(R.drawable.myself)
.into(imageview);
} catch (Exception e) {
LogUtil.i(TAG, "loadBitmapToImage error:" + e.toString());
}
}
}
public static void loadResourceBitmapToImage(Context mContext, int Resource, ImageView imageview) {
Activity activity = (Activity) mContext;
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
Glide.with(mContext).load(Resource)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageview);
}
public static void loadPathBitmapToImage(Context mContext, String url, ImageView imageview) {
if (TextUtils.isEmpty(url)) {
return;
}
try {
Glide.with(mContext).load(url).asBitmap()
.placeholder(R.drawable.myself)
.error(R.drawable.myself)
.into(imageview);
} catch (Exception e) {
LogUtil.i(TAG, "loadPathBitmapToImage error:" + e.toString());
}
}
public static void loadRoundImage(final Context context, final int cornerRadius, String url, final ImageView imageView) {
if (!TextUtils.isEmpty(url) && !url.startsWith(Constants.FILE_URL)) {
url = Constants.FILE_URL + url;
}
try {
Glide.with(context)
.load(url)
.asBitmap()
.placeholder(R.drawable.myself)
.diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
.into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
super.setResource(resource);
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCornerRadius(cornerRadius); //设置圆角弧度
imageView.setImageDrawable(circularBitmapDrawable);
}
});
} catch (Exception e) {
LogUtil.i(TAG, "loadRoundImage error:" + e.toString());
}
}
public static Boolean loadRoundImage2(final Context context, final int cornerRadius, String url, final ImageView imageView) {
if(TextUtils.isEmpty(url)){
return false;
}
if (!TextUtils.isEmpty(url) && !url.startsWith(Constants.FILE_URL)) {
url = Constants.FILE_URL + url;
}
try {
Glide.with(context)
.load(url)
.asBitmap()
.placeholder(R.drawable.myself)
.diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
.into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
super.setResource(resource);
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCornerRadius(cornerRadius); //设置圆角弧度
imageView.setImageDrawable(circularBitmapDrawable);
}
});
return true;
} catch (Exception e) {
LogUtil.i(TAG, "loadRoundImage error:" + e.toString());
}
return false;
}
public static Bitmap getRoundCornerImage(Bitmap bitmap_bg, Bitmap bitmap_in) {
Bitmap roundConcerImage = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(roundConcerImage);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, 500, 500);
Rect rectF = new Rect(0, 0, bitmap_in.getWidth(), bitmap_in.getHeight());
paint.setAntiAlias(true);
NinePatch patch = new NinePatch(bitmap_bg, bitmap_bg.getNinePatchChunk(), null);
patch.draw(canvas, rect);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap_in, rectF, rect, paint);
return roundConcerImage;
}
public static Bitmap getShardImage(Bitmap bitmap_bg, Bitmap bitmap_in) {
Bitmap roundConcerImage = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(roundConcerImage);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, 500, 500);
paint.setAntiAlias(true);
NinePatch patch = new NinePatch(bitmap_bg, bitmap_bg.getNinePatchChunk(), null);
patch.draw(canvas, rect);
Rect rect2 = new Rect(2, 2, 498, 498);
canvas.drawBitmap(bitmap_in, rect, rect2, paint);
return roundConcerImage;
}
/**
* 连接网络获得相对应的图片
*
* @param imageUrl
* @return
*/
public static Drawable getImageNetwork(String imageUrl) {
URL myFileUrl = null;
Drawable drawable = null;
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
// 在这一步最好先将图片进行压缩,避免消耗内存过多
Bitmap bitmap = BitmapFactory.decodeStream(is);
drawable = new BitmapDrawable(bitmap);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return drawable;
}
}
| 38.766667 | 129 | 0.596303 |
787e4eb2848a03f4a4c7cece8124bccf7092a441 | 2,762 | package controller;
import java.io.IOException;
import java.util.LinkedList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.SQLDao;
import domain.User;
public class SubmitText extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sess = request.getSession();
RequestDispatcher dispatcher;
ServletContext context = getServletConfig().getServletContext();
ServletContext application = this.getServletContext();
if (sess.getAttribute("login") != null && sess.getAttribute("login").equals("1")) {
int many=(int)context.getAttribute("howmany");
User user=(User)sess.getAttribute("user");
int gread = 0;
int which = Integer.parseInt(request.getParameter("Text"));
String wh=request.getParameter("Text");
which=which-1;
SQLDao dao = new SQLDao();
domain.Text text = dao.GetText(wh);
LinkedList<String> result_list=new LinkedList<>();
LinkedList<String> submit_list=new LinkedList<>();
for(int j=0;j<text.getList().size();j++){
String result_str=text.getList().get(j).getResult();
result_str=result_str.replace(" ", "");
result_list.add(result_str);
}
for(int j=0;j<text.getList().size();j++){
String fir = request.getParameter(which + "pro"+j);
if(fir==null){
fir="E";
}
submit_list.add(fir);
}
double add=100/(text.getList().size());
for(int j=0;j<text.getList().size();j++){
if(submit_list.get(j)!=null&&submit_list.get(j).equals(result_list.get(j))){
gread+=add;
}
}
/*String one = text.getList().get(0).getResult();
one = one.replace(" ", "");
String two = text.getList().get(1).getResult();
two = two.replace(" ", "");
String fir = request.getParameter(which + "pro0");
String sec = request.getParameter(which + "pro1");
System.out.println(fir+"111\n"+sec+"111\n"+one+"111\n"+two+"111\n");
if (fir!=null&&fir.equals(one)) {
gread += 50;
}
if (sec.equals(two)) {
gread += 50;
}
if(fir==null){
}*/
dao.Updategread(user.getUsername(), wh, gread);
user=dao.Getgreads(user, many);
sess.setAttribute("user", user);
dispatcher = context.getRequestDispatcher("/Servlet/Text");
dispatcher.forward(request, response);
} else {
response.sendRedirect("../index.jsp");
}
}
}
| 31.386364 | 85 | 0.688631 |
10f8d177ef305cd3050507953d47fb3fc8ec1726 | 3,793 | package com.micmiu.framework.utils;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.springframework.context.MessageSource;
import com.micmiu.framework.web.v1.base.vo.OperationType;
import com.micmiu.framework.web.v1.system.entity.Menu;
import com.micmiu.framework.web.v1.system.entity.Permission;
import com.micmiu.framework.web.v1.system.vo.TreeNode;
import com.micmiu.modules.support.spring.I18nMessageParser;
/**
*
* @author <a href="http://www.micmiu.com">Michael Sun</a>
*/
public class MenuPermUtil {
/**
* 转化用户菜单为HTML格式
*
* @param allMenus
* @param userMenus
* @param ids
* @param contextPath
*/
public static void parseUserMenu(List<Menu> allMenus,
List<TreeNode> userMenus, Set<Long> ids, String contextPath,
MessageSource messageSource, Locale locale) {
for (Menu menu : allMenus) {
if (ids.contains(menu.getId())) {
userMenus.add(recParseMenu(ids, menu, contextPath,
messageSource, locale));
}
}
}
/**
* 递归菜单转化为HTML
*
* @param ids
* @param menu
* @param contextPath
* @param messageSource
* @param locale
* @return
*/
private static TreeNode recParseMenu(Set<Long> ids, Menu menu,
String contextPath, MessageSource messageSource, Locale locale) {
TreeNode vo = new TreeNode();
vo.setId(menu.getId() + "");
String text = "";
String menuName = messageSource.getMessage(menu.getMenuName(), null,
menu.getMenuName(), locale);
if (null != menu.getMenuURL() && !"".equals(menu.getMenuURL())) {
if (menu.getMenuURL().startsWith("/")) {
text = "<a href ='" + contextPath + menu.getMenuURL() + "'>"
+ menuName + "</a>";
} else {
text = "<a href ='" + contextPath + "/" + menu.getMenuURL()
+ "'>" + menuName + "</a>";
}
} else {
text = menuName;
}
vo.setText(text);
if (!menu.getChildren().isEmpty()) {
for (Menu childMenu : menu.getChildren()) {
if (ids.contains(childMenu.getId())) {
vo.getChildren().add(
recParseMenu(ids, childMenu, contextPath,
messageSource, locale));
}
}
}
return vo;
}
/**
* 转化已有的权限ID
*
* @param permssions
* @return
*/
public static Set<String> parsePermissionStrs(List<Permission> permssions) {
Set<String> permStrs = new HashSet<String>();
for (Permission permssion : permssions) {
permStrs.add("perm:" + permssion.getId());
}
return permStrs;
}
/**
* 转化已有角色的权限树形结构
*
* @param allMenus
* @param permTree
* @param hasPerms
*/
public static void parseMenuPermTree(List<Menu> allMenus,
List<TreeNode> permTree, Set<String> hasPerms) {
for (Menu menu : allMenus) {
permTree.add(recMenuPermTree(menu, hasPerms));
}
}
/**
* 递归解析权限树型
*
* @param menu
* @param hasPerms
* @return
*/
private static TreeNode recMenuPermTree(Menu menu, Set<String> hasPerms) {
TreeNode vo = new TreeNode();
vo.setId("menu:" + menu.getId());
vo.setText(I18nMessageParser.getInstance().getMessage(
menu.getMenuName()));
if (!menu.getChildren().isEmpty()) {
for (Menu childMenu : menu.getChildren()) {
vo.getChildren().add(recMenuPermTree(childMenu, hasPerms));
}
} else {
for (Permission perm : menu.getPermssionList()) {
TreeNode permNode = new TreeNode();
String nodeId = "perm:" + perm.getId();
permNode.setId(nodeId);
if (null != hasPerms && hasPerms.contains(nodeId)) {
permNode.setChecked(true);
}
permNode.setText(I18nMessageParser.getInstance().getMessage(
OperationType.parse(perm.getOperation()).getDisplay()));
vo.getChildren().add(permNode);
}
}
return vo;
}
}
| 26.158621 | 78 | 0.633272 |
377315f0216482cb1ff11d220cb10ede2e4782b6 | 272 | package edu.osu.romanach.one;
import java.util.*;
public class IntegerEntryHighToLowComparator<T> implements Comparator<Map.Entry<Integer, T>> {
@Override
public int compare(Map.Entry<Integer, T> o1, Map.Entry<Integer, T> o2) {
return o2.getKey() - o1.getKey();
}
}
| 27.2 | 94 | 0.731618 |
09c5c4dfa0f28e0f991139c8dcd9cad4a44e76de | 8,095 | /*
* Copyright 2017 jfxproperties contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.navatwo.jfxproperties;
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import javafx.beans.property.*;
import javax.annotation.CheckReturnValue;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Utility functions for use with reflection
*/
public abstract class MoreReflection {
private MoreReflection() {
// no instantiate
}
/**
* Unwraps a {@link Property} subtype and gets the underlying value type.
*
* @param propertyType Type of the property, used to extract the generic
* @return Underlying type or null if not found
*/
@CheckReturnValue
public static TypeToken<?> unwrapPropertyType(TypeToken<?> propertyType) {
checkNotNull(propertyType, "propertyType == null");
Class<?> rawType = propertyType.getRawType();
checkNotNull(rawType, "rawType == null");
// used to clean up the if statements
TypeToken<?> readOnlyPrim = new TypeToken<ReadOnlyProperty<Number>>(rawType) {
};
if (propertyType.isSubtypeOf(readOnlyPrim)) {
if (propertyType.isSubtypeOf(ReadOnlyIntegerProperty.class)) {
return TypeToken.of(int.class);
} else if (propertyType.isSubtypeOf(ReadOnlyLongProperty.class)) {
return TypeToken.of(long.class);
} else if (propertyType.isSubtypeOf(ReadOnlyDoubleProperty.class)) {
return TypeToken.of(double.class);
} else {
throw new IllegalArgumentException("Unknown primitive property: " + propertyType);
}
} else if (propertyType.isSubtypeOf(ReadOnlyStringProperty.class)) {
return TypeToken.of(String.class);
} else if (isReadOnlyProperty(propertyType)) {
// This checks for ReadOnlyProperty, both of which we can handle by
// Pulling out the first generic argument (thanks to Guava's TypeToken)
TypeToken<?> param = propertyType.resolveType(ReadOnlyProperty.class.getTypeParameters()[0]);
return param;
} else if (isOptional(propertyType)) {
TypeToken<?> param = propertyType.resolveType(Optional.class.getTypeParameters()[0]);
return param;
} else {
return propertyType;
}
}
/**
* Checks the arguments passed for validity with the invoked method.
*
* @param method Method invoked
* @param objectType Type of the instance
* @param valueType Value returned
* @param <O> Object type
* @param <R> Returned value
*/
// FIXME replace with TypeLiteral
public static <O, R> void checkMethodTypes(Method method,
Class<O> objectType,
Class<R> valueType,
Class<?>... parameters) {
checkNotNull(method, "method is null");
checkNotNull(objectType, "objectType == null");
checkNotNull(valueType, "valueType == null");
Class<?> declType = method.getDeclaringClass();
checkArgument(declType.isAssignableFrom(objectType),
"Can not call %s on object %s", declType, objectType);
Class<?> retType = method.getReturnType();
checkArgument(valueType.isAssignableFrom(retType),
"Can not convert %s to value %s", retType, valueType);
// Now check all the parameters
boolean paramsCorrect = (method.getParameterCount() == parameters.length);
Class<?>[] mparams = method.getParameterTypes();
for (int i = 0; paramsCorrect && i < parameters.length; ++i) {
paramsCorrect = mparams[i].isAssignableFrom(parameters[i]);
}
if (!paramsCorrect) {
throw new IllegalArgumentException(
String.format("Invalid parameters for method %s, expected: %s, actual: %s",
method, Arrays.asList(method.getParameterTypes()), Arrays.asList(parameters)));
}
}
public static boolean isReadOnlyProperty(Class<?> clazz) {
return isReadOnlyProperty(TypeToken.of(clazz));
}
public static boolean isReadOnlyProperty(TypeToken<?> type) {
return type.isSubtypeOf(ReadOnlyProperty.class);
}
public static boolean isProperty(Class<?> clazz) {
return isProperty(TypeToken.of(clazz));
}
public static boolean isProperty(TypeToken<?> type) {
return type.isSubtypeOf(Property.class);
}
public static boolean isOptional(Class<?> clazz) {
return isOptional(TypeToken.of(clazz));
}
public static boolean isOptional(TypeToken<?> type) {
return type.isSubtypeOf(Optional.class);
}
/**
* Checks if the passed type is an observable collection of the correct type.
*
* @param propType
* @return
*/
public static boolean isCollection(TypeToken<?> propType) {
return propType.isSubtypeOf(Map.class) || propType.isSubtypeOf(Collection.class);
}
private static <E> TypeToken<Collection<E>> collectionToken(TypeToken<E> elementType) {
return new TypeToken<Collection<E>>() {
}
.where(new TypeParameter<E>() {
}, elementType);
}
/**
* Resolves the {@code index}th type parameter from the token.
*
* @param token
* @param index
* @return
* @throws ArrayIndexOutOfBoundsException if the type parameter doesn't exist
*/
public static TypeToken<?> resolveTypeParameter(TypeToken<?> token, int index) {
return token.resolveType(token.getRawType().getTypeParameters()[index]);
}
/**
* Checks if the passed type is an observable collection of the correct type.
*
* @param propType
* @return
*/
public static <K, V> boolean isMap(TypeToken<?> propType, TypeToken<K> keyType, TypeToken<V> valueType) {
TypeToken<Map<K, V>> mapType = new TypeToken<Map<K, V>>() {
}
.where(new TypeParameter<K>() {
}, keyType)
.where(new TypeParameter<V>() {
}, valueType);
boolean result = propType.isSubtypeOf(mapType);
if (result) {
TypeToken<?> pKeyType = resolveTypeParameter(propType, 0);
TypeToken<?> pValueType = resolveTypeParameter(propType, 1);
result &= keyType.isSubtypeOf(pKeyType) && valueType.isSubtypeOf(pValueType);
}
return result;
}
/**
* Checks if the passed type is a collection of the correct type.
*
* @param propType
* @return
*/
public static <E> boolean isCollection(TypeToken<?> propType, TypeToken<E> elementType) {
TypeToken<Collection<E>> collType = collectionToken(elementType);
if (propType.isSubtypeOf(collType)) {
return true;
} else if (propType.isSubtypeOf(Map.class)) {
TypeToken<?> keyType = resolveTypeParameter(elementType, 0);
TypeToken<?> valueType = resolveTypeParameter(elementType, 1);
return isMap(propType, keyType, valueType);
}
return false;
}
}
| 36.138393 | 109 | 0.630389 |
ef82ea7347a920dcf842c99175d6969e15385bc0 | 11,144 | /*
* Copyright 2016 Amirhossein Vakili
*
* 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.
*/
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
/**
* Created by Amirhossein Vakili.
*/
public class FOF2Alloy extends FOFTPTPBaseVisitor<String> {
private Map<String, Integer> relSym, funSym;
private Set<String> constants, props, sets;
private Set<String> vars;
public static final String univ = "_UNIV";
private String filePath;
private Boolean errorDuringImport = false;
private Boolean builtinBoolean = false;
public FOF2Alloy(String filePath) {
relSym = new HashMap<>();
funSym = new HashMap<>();
constants = new TreeSet<>();
props = new TreeSet<>();
sets = new TreeSet<>();
vars = new TreeSet<>();
this.filePath = filePath;
}
public String declarationString() {
StringBuilder declarations = new StringBuilder("sig _UNIV{\n");
if (!relSym.isEmpty()) {
Iterator<Map.Entry<String, Integer>> it = relSym.entrySet().iterator();
Map.Entry<String, Integer> el = it.next();
declarations.append(" " + el.getKey() + " : " + predDec(el.getValue()));
while (it.hasNext()) {
el = it.next();
declarations.append(",\n " + el.getKey() + " : " + predDec(el.getValue()));
}
for (Map.Entry<String, Integer> e : funSym.entrySet()) {
declarations.append(",\n " + e.getKey() + " : " + funDec(e.getValue()));
}
} else {
if (!funSym.isEmpty()) {
Iterator<Map.Entry<String, Integer>> it = funSym.entrySet().iterator();
Map.Entry<String, Integer> el = it.next();
declarations.append(" " + el.getKey() + " : " + funDec(el.getValue()));
while (it.hasNext()) {
el = it.next();
declarations.append(",\n " + el.getKey() + " : " + funDec(el.getValue()));
}
}
}
declarations.append("\n}\n");
if (!constants.isEmpty()) {
declarations.append("one sig ");
Iterator<String> it = constants.iterator();
declarations.append(it.next());
while (it.hasNext())
declarations.append(", " + it.next());
declarations.append(" in _UNIV{}\n\n");
}
if (!sets.isEmpty()) {
declarations.append("sig ");
Iterator<String> it = sets.iterator();
declarations.append(it.next());
while (it.hasNext())
declarations.append(", " + it.next());
declarations.append(" in _UNIV{}\n");
}
declarations.append('\n');
if (!props.isEmpty()) {
declarations.append("one sig _BOOLEAN{}\nsig ");
Iterator<String> it = props.iterator();
declarations.append(it.next());
while (it.hasNext())
declarations.append(", " + it.next());
declarations.append(" in _BOOLEAN{}\n\n");
}
if (errorDuringImport) return "SyntaxError";
if (builtinBoolean) {
declarations.append("pred true {}\npred false { not true }\n\n");
}
return declarations.toString();
}
private String predDec(int n) {
StringBuilder sb = new StringBuilder("set _UNIV");
for (int i = 0; i < n - 2; i++)
sb.append(" -> set _UNIV");
return sb.toString();
}
private String funDec(int n) {
if (n == 1)
return "one _UNIV";
StringBuilder sb = new StringBuilder("set _UNIV");
for (int i = 0; i < n - 2; i++)
sb.append(" -> set _UNIV");
sb.append(" -> one _UNIV");
return sb.toString();
}
@Override
public String visitSpec(FOFTPTPParser.SpecContext ctx) {
StringBuilder includes = new StringBuilder("");
StringBuilder facts = new StringBuilder("fact{\n");
for (FOFTPTPParser.LineContext n : ctx.line())
if (n instanceof FOFTPTPParser.Fof_annotatedContext)
facts.append(" " + visit(n) + "\n\n");
else if (n instanceof FOFTPTPParser.IncludeContext)
includes.append(visit(n) + "\n");
facts.append("}\n");
return includes.toString() + facts.toString();
}
@Override
public String visitFof_annotated(FOFTPTPParser.Fof_annotatedContext ctx) {
vars.clear();
String f = visit(ctx.fof_formula());
if (ctx.ID().getText().equals("conjecture"))
return "(not " + f + ")";
return f;
}
@Override
public String visitInclude(FOFTPTPParser.IncludeContext ctx) {
String inputFilePath = ctx.SINGLE_QUOTED().getText();
// remove the surrounding single quotes
inputFilePath = inputFilePath.substring(1, inputFilePath.length() - 1);
// there is a danger here with infinite includes
// but let's assume that won't happen
String thy2;
try {
File f = new File(filePath);
String root_directory = f.getParentFile().getParentFile().getParent();
File f_include = new File(root_directory + "/" + inputFilePath);
InputStream inputStream = new FileInputStream(f_include);
CharStream stream = CharStreams.fromStream(inputStream);
FOFTPTPLexer lexer = new FOFTPTPLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
FOFTPTPParser parser = new FOFTPTPParser(tokens);
ParseTree tree = parser.spec();
if (parser.getNumberOfSyntaxErrors() >= 1) {
errorDuringImport = true;
return "SyntaxError";
}
return this.visit(tree);
} catch (Exception e) {
errorDuringImport = true;
return "SyntaxError: Something bad happened when parsing the imported file: " + inputFilePath;
}
}
@Override
public String visitNot(FOFTPTPParser.NotContext ctx) {
return "(not " + visit(ctx.fof_formula()) + ")";
}
@Override
public String visitForall(FOFTPTPParser.ForallContext ctx) {
StringBuilder sb = new StringBuilder("(all ");
sb.append(ctx.ID(0).getText() + "_");
vars.add(ctx.ID(0).getText() + "_");
final int len = ctx.ID().size();
for (int i = 1; i != len; i++) {
String name = ctx.ID(i).getText() + "_";
vars.add(name);
sb.append(", " + name);
}
sb.append(": " + univ + " | " + visit(ctx.fof_formula()) + ")");
return sb.toString();
}
@Override
public String visitExists(FOFTPTPParser.ExistsContext ctx) {
StringBuilder sb = new StringBuilder("(some ");
sb.append(ctx.ID(0).getText() + "_");
vars.add(ctx.ID(0).getText() + "_");
final int len = ctx.ID().size();
for (int i = 1; i != len; i++) {
String name = ctx.ID(i).getText() + "_";
vars.add(name);
sb.append(", " + name);
}
sb.append(": " + univ + " | " + visit(ctx.fof_formula()) + ")");
return sb.toString();
}
@Override
public String visitAnd(FOFTPTPParser.AndContext ctx) {
return "(" + visit(ctx.fof_formula(0)) + " and " + visit(ctx.fof_formula(1)) + ")";
}
@Override
public String visitOr(FOFTPTPParser.OrContext ctx) {
return "(" + visit(ctx.fof_formula(0)) + " or " + visit(ctx.fof_formula(1)) + ")";
}
@Override
public String visitImp(FOFTPTPParser.ImpContext ctx) {
return "(" + visit(ctx.fof_formula(0)) + " implies " + visit(ctx.fof_formula(1)) + ")";
}
@Override
public String visitIff(FOFTPTPParser.IffContext ctx) {
return "(" + visit(ctx.fof_formula(0)) + " iff " + visit(ctx.fof_formula(1)) + ")";
}
@Override
public String visitEq(FOFTPTPParser.EqContext ctx) {
return "(" + visit(ctx.term(0)) + " = " + visit(ctx.term(1)) + ")";
}
@Override
public String visitNeq(FOFTPTPParser.NeqContext ctx) {
return "(not (" + visit(ctx.term(0)) + " = " + visit(ctx.term(1)) + "))";
}
@Override
public String visitProp(FOFTPTPParser.PropContext ctx) {
String temp = ctx.ID().getText() + "_";
props.add(temp);
return "(some " + temp + ")";
}
@Override
public String visitDefined_prop(FOFTPTPParser.Defined_propContext ctx) {
String name = ctx.DEFINED_PROP().getText();
builtinBoolean = true;
if (name.equals("$true"))
return "true";
else if (name.equals("$false"))
return "false";
return "";
}
@Override
public String visitPred(FOFTPTPParser.PredContext ctx) {
String name = ctx.ID().getText() + "_";
final int len = ctx.term().size();
if (len == 1)
sets.add(name);
else
relSym.put(name, len);
StringBuilder sb = new StringBuilder("((");
sb.append(visit(ctx.term(0)));
for (int i = 1; i != len; i++) {
sb.append(' ');
sb.append('-');
sb.append('>');
sb.append(' ');
sb.append(visit(ctx.term(i)));
}
sb.append(") in " + name + ")");
return sb.toString();
}
@Override
public String visitParen(FOFTPTPParser.ParenContext ctx) {
return "(" + visit(ctx.fof_formula()) + ")";
}
@Override
public String visitConVar(FOFTPTPParser.ConVarContext ctx) {
String name = ctx.ID().getText() + "_";
if (!vars.contains(name)) {
constants.add(name);
//System.out.println("Adding " + name);
}
return name;
}
@Override
public String visitApply(FOFTPTPParser.ApplyContext ctx) {
String name = ctx.ID().getText() + "_";
final int len = ctx.term().size();
funSym.put(name, len);
StringBuilder sb = new StringBuilder(name);
sb.append('[');
sb.append(visit(ctx.term(0)));
for (int i = 1; i != len; i++) {
sb.append(' ');
sb.append(',');
sb.append(visit(ctx.term(i)));
}
sb.append(']');
return sb.toString();
}
} | 34.825 | 106 | 0.55411 |
c9d3a45682356f9cbec469a8276e151869c19451 | 603 | package cn.fulushan.fuhttp.fragment.base;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.leakcanary.RefWatcher;
import cn.fulushan.fuhttp.MainApplication;
import cn.fulushan.fuhttp.R;
/**
* A simple {@link Fragment} subclass.
*/
public class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MainApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
| 23.192308 | 77 | 0.742952 |
30ab60793a45d5cb8a5fa55a87275e3c0d7549d5 | 7,553 | package cn.te0.flutter.action;
import cn.te0.flutter.helper.TemplateHelper;
import cn.te0.flutter.helper.YamlHelper;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.google.gson.reflect.TypeToken;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.ruiyu.utils.ExtensionsKt;
import com.ruiyu.utils.GsonUtil;
import io.flutter.pub.PubRoot;
import io.flutter.utils.FlutterModuleUtils;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jsoup.internal.StringUtil;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author chaly
*/
public class AssetAction extends AnAction {
private static final String ASSETS_ROOT = "assets";
private static final Splitter SPLITTER = Splitter.on(File.separator).omitEmptyStrings().trimResults();
Project project;
String base, last, name;
Set<String> variant = new HashSet<>();
Multimap<String, String> assets = ArrayListMultimap.create();
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
project = e.getData(PlatformDataKeys.PROJECT);
Module[] modules = FlutterModuleUtils.getModules(project);
for (Module module : modules) {
if (FlutterModuleUtils.isFlutterModule(module)) {
VirtualFile parent = module.getModuleFile().getParent();
base = parent.getPath() + File.separator + ASSETS_ROOT;
if (PubRoot.forFile(parent.findChild("lib")).isFlutterPlugin()) {
name = YamlHelper.getName(project);
}
getAssets(new File(base));
updateYaml(module);
updateDart(module);
}
}
Objects.requireNonNull(ProjectUtil.guessProjectDir(project)).refresh(false, true);
}
public void getAssets(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
last = file.getAbsolutePath().replace(base, "");
// 2.0x 3.0x 等多分辨率变体目录不处理
if (file.getName().matches("^[1-9](\\.\\d)x$")) {
variant.add(last);
}
//处理下级目录
for (File f : Arrays.stream(Objects.requireNonNull(file.listFiles((f, n) -> {
// 忽略 MacOS 中的 .DS_Store 文件
return !".DS_Store".equals(n);
}))).sorted((f1, f2) -> {
// 重新排序,文件排在目录前面。先处理文件,然后处理下级目录,方便处理资源变体
if (f1.isFile() && f2.isDirectory()) {
return -1;
} else if (f1.isDirectory() && f2.isFile()) {
return 1;
}
return 0;
}).collect(Collectors.toList())) {
getAssets(f);
}
} else if (file.isFile() && !StringUtil.isBlank(last)) {
assets.put(file.getName(), last);
}
}
public void updateYaml(Module module) {
List<String> paths = assets.values().stream().distinct().filter(item -> !variant.contains(item)).sorted().map(s -> "assets" + s + "/").collect(Collectors.toList());
List<Map<String, Object>> fonts = assets.keys().stream().filter(item -> item.toLowerCase(Locale.ROOT).endsWith(".ttf")).sorted().map(s -> {
String family = s.replace(".ttf", "").split("-")[0];
List<String> directory = assets.get(s).stream().distinct().collect(Collectors.toList());
return new HashMap<String, Object>() {{
put("family", family);
put("fonts", Lists.newArrayList(
new HashMap<String, Object>() {{
for (String value : directory) {
put("asset", String.format("%s%s/%s", ASSETS_ROOT, value, s));
}
}}
));
}};
}).collect(Collectors.toList());
String yamlFile = module.getModuleFile().getParent().getPath() + "/pubspec.yaml";
YamlHelper.updateYaml(yamlFile, map -> {
Map flutter = ((Map) map.get("flutter"));
flutter.put("assets", paths);
flutter.put("fonts", fonts);
});
}
@SneakyThrows
public void updateDart(Module module) {
Table<String, String, String> tables = TreeBasedTable.create();
Set<String> files = assets.keySet();
for (String file : files) {
Collection<String> paths = assets.get(file);
for (String path : paths) {
List<String> list = Lists.newArrayList(SPLITTER.splitToList(path));
//如果是变体目录
if (variant.contains(path)) {
list.remove(list.size() - 1);
}
String row = list.remove(0);
list.add(file);
String value = Joiner.on("/").skipNulls().join("assets", row, list.toArray());
String column = Joiner.on("_").join(list).split("\\.")[0];
if (tables.get(row, column) == null) {
tables.put(row, column, value);
}
}
}
File file = new File(module.getModuleFile().getParent().getPath() + "/lib/gen/res/");
if (!file.exists()) {
file.mkdirs();
}
//处理iconfont图标
Map<String, Map<String, String>> res = tables.rowMap();
Map<String, String> icons = new HashMap<>();
Map<String, String> icon = res.remove("icon");
if (icon != null) {
for (Map.Entry<String, String> entry : icon.entrySet()) {
String json = FileUtils.readFileToString(new File(base.replace(ASSETS_ROOT, "") + entry.getValue()), Charset.defaultCharset());
Map<String, Object> map = GsonUtil.fromJson(json, new TypeToken<>() {
});
List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("glyphs");
for (Map<String, Object> m : list) {
icons.put(m.get("font_class").toString().replaceAll("-","_"), String.format("0x%s", m.get("unicode")));
}
}
}
res = Maps.newHashMap(res);
res.put("icon", icons);
//准备生成模板
Map<String, Object> map = new HashMap();
map.put("packageName", name);
map.put("res", res);
TemplateHelper.getInstance().generator(
"asset/resources.dart.ftl", file.getAbsolutePath() + "/resources.dart", map
);
Objects.requireNonNull(ProjectUtil.guessProjectDir(project)).refresh(false, true);
ExtensionsKt.showNotify(project, "Assets reference has been updated successfully.");
}
}
| 41.5 | 172 | 0.587052 |
4b363133a3a359547b2761dfd47c5d5b88090bf7 | 938 | /**
* Defines loader classes.
*
* Working with {@link org.osgl.inject.annotation genie annotations},
* loader provides extra facility for application to define how to
* inject values including collections, maps and scala type values
*/
package org.osgl.inject.loader;
/*-
* #%L
* OSGL Genie
* %%
* Copyright (C) 2017 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
| 32.344828 | 75 | 0.721748 |
5d90780cf5e2e451b0284c55d2fb4bdbe0727b16 | 2,692 | package no.nav.folketrygdloven.beregningsgrunnlag.regelmodell.ytelse.frisinn;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import no.nav.folketrygdloven.beregningsgrunnlag.regelmodell.Periode;
import no.nav.folketrygdloven.beregningsgrunnlag.regelmodell.ytelse.YtelsesSpesifiktGrunnlag;
public class FrisinnGrunnlag extends YtelsesSpesifiktGrunnlag {
private List<FrisinnPeriode> frisinnPerioder;
private List<Periode> søknadsperioder;
private LocalDate skjæringstidspunktOpptjening;
public FrisinnGrunnlag(List<FrisinnPeriode> frisinnPerioder, List<Periode> søknadsperioder, LocalDate skjæringstidspunktOpptjening) {
super("FRISINN");
Objects.requireNonNull(frisinnPerioder, "frisinnPerioder");
Objects.requireNonNull(skjæringstidspunktOpptjening, "skjæringstidspunktOpptjening");
Objects.requireNonNull(søknadsperioder, "søknadsperioder");
this.søknadsperioder = søknadsperioder;
this.frisinnPerioder = frisinnPerioder;
this.skjæringstidspunktOpptjening = skjæringstidspunktOpptjening;
}
public LocalDate getSkjæringstidspunktOpptjening() {
return skjæringstidspunktOpptjening;
}
public List<FrisinnPeriode> getFrisinnPerioder() {
return frisinnPerioder;
}
public boolean søkerFrilansISøknadsperiode(LocalDate dato) {
Optional<Periode> søknadsperiode = søknadsperioder.stream().filter(s -> s.inneholder(dato)).findFirst();
return søknadsperiode.map(sp -> frisinnPerioder.stream().filter(fp -> sp.overlapper(fp.getPeriode()))
.anyMatch(FrisinnPeriode::getSøkerYtelseFrilans)).orElse(false);
}
public boolean søkerNæringISøknadsperiode(LocalDate dato) {
Optional<Periode> søknadsperiode = søknadsperioder.stream().filter(s -> s.inneholder(dato)).findFirst();
return søknadsperiode.map(sp -> frisinnPerioder.stream().filter(fp -> sp.overlapper(fp.getPeriode()))
.anyMatch(FrisinnPeriode::getSøkerYtelseNæring)).orElse(false);
}
public boolean søkerYtelseFrilans(LocalDate dato) {
return frisinnPerioder.stream().anyMatch(p -> p.inneholderDato(dato) && p.getSøkerYtelseFrilans());
}
public boolean søkerYtelseNæring(LocalDate dato) {
return frisinnPerioder.stream().anyMatch(p -> p.inneholderDato(dato) && p.getSøkerYtelseNæring());
}
public boolean søkerYtelseFrilans() {
return frisinnPerioder.stream().anyMatch(FrisinnPeriode::getSøkerYtelseFrilans);
}
public boolean søkerYtelseNæring() {
return frisinnPerioder.stream().anyMatch(FrisinnPeriode::getSøkerYtelseNæring);
}
}
| 42.0625 | 137 | 0.751486 |
eae951ad5ce0ca7c9b9f1428388a598a5e55c80a | 11,801 | /*
* CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for
* Modeling and Simulation of Cloud Computing Infrastructures and Services.
* http://cloudsimplus.org
*
* Copyright (C) 2015-2016 Universidade da Beira Interior (UBI, Portugal) and
* the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil).
*
* This file is part of CloudSim Plus.
*
* CloudSim Plus 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.
*
* CloudSim Plus 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 CloudSim Plus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cloudbus.cloudsim.utilizationmodels;
import org.cloudbus.cloudsim.util.Conversion;
import java.util.Objects;
import java.util.function.Function;
/**
* A Cloudlet {@link UtilizationModel} that allows to increases the utilization of the related resource along
* the simulation time. It accepts a Lambda Expression that defines how the utilization increment must behave.
* By this way, the class enables the developer to define such a behaviour when instantiating objects
* of this class.
*
* <p>For instance, it is possible to use the class to arithmetically or geometrically increment resource usage,
* but any kind of increment as logarithmic or exponential is possible.
* For more details, see the {@link #setUtilizationUpdateFunction(Function)}.</p>
*
* @author Manoel Campos da Silva Filho
* @since CloudSim Plus 1.0
*/
public class UtilizationModelDynamic extends UtilizationModelAbstract {
private boolean readOnly;
private double currentUtilization = 0;
/** @see #getMaxResourceUtilization() */
private double maxResourceUtilization;
/**
* @see #setUtilizationUpdateFunction(Function)
*/
private Function<UtilizationModelDynamic, Double> utilizationUpdateFunction;
/**
* The last time the utilization was updated.
*/
private double previousUtilizationTime;
/**
* The time that the utilization is being currently requested.
*/
private double currentUtilizationTime;
/**
* Creates a UtilizationModelDynamic with no initial utilization and resource utilization
* unit defined in {@link Unit#PERCENTAGE}.
*
* <p><b>The utilization will not be dynamically incremented
* until an increment function is defined by the {@link #setUtilizationUpdateFunction(Function)}.</b></p>
* @see #setUtilizationUpdateFunction(Function)
*/
public UtilizationModelDynamic() {
this(Unit.PERCENTAGE, 0);
}
/**
* Creates a UtilizationModelDynamic with no initial utilization and resource utilization
* {@link Unit} be defined according to the given parameter.
*
* <p><b>The utilization will not be dynamically incremented
* until that an increment function is defined by the {@link #setUtilizationUpdateFunction(Function)}.</b></p>
* @param unit the {@link Unit} that determines how the resource is used (for instance, if
* resource usage is defined in percentage of the Vm resource or in absolute values)
*/
public UtilizationModelDynamic(Unit unit) {
this(unit, 0);
}
/**
* Creates a UtilizationModelDynamic that the initial resource utilization
* will be defined according to the given parameter and the {@link Unit}
* will be set as {@link Unit#PERCENTAGE}.
*
* <p><b>The utilization will not be dynamically incremented
* until that an increment function is defined by the {@link #setUtilizationUpdateFunction(Function)}.</b></p>
* @param initialUtilizationPercent the initial percentage of resource utilization
*/
public UtilizationModelDynamic(final double initialUtilizationPercent) {
this(Unit.PERCENTAGE, initialUtilizationPercent);
}
/**
* Creates a UtilizationModelDynamic that the initial resource utilization
* and the {@link Unit} will be defined according to the given parameters.
*
* <p><b>The utilization will not be dynamically incremented
* until that an increment function is defined by the {@link #setUtilizationUpdateFunction(Function)}.</b></p>
* @param unit the {@link Unit} that determines how the resource is used (for instance, if
* resource usage is defined in percentage of the Vm resource or in absolute values)
* @param initialUtilization the initial of resource utilization, that the unit depends
* on the {@code unit} parameter
*/
public UtilizationModelDynamic(Unit unit, final double initialUtilization) {
super(unit);
this.readOnly = false;
this.maxResourceUtilization = (unit == Unit.PERCENTAGE ? Conversion.HUNDRED_PERCENT : 0);
this.previousUtilizationTime = 0;
this.currentUtilizationTime = 0;
this.setCurrentUtilization(initialUtilization);
/**
* Creates a default lambda function that doesn't increment the utilization along the time.
* The {@link #setUtilizationUpdateFunction(Function)} should be used to defined
* a different increment function.
*/
utilizationUpdateFunction = um -> um.currentUtilization;
}
/**
* A copy constructor that creates a read-only UtilizationModelDynamic based on a source object
* @param source the source UtilizationModelDynamic to create an instance from
*/
protected UtilizationModelDynamic(UtilizationModelDynamic source){
this(source.getUnit(), source.currentUtilization);
this.currentUtilizationTime = source.currentUtilizationTime;
this.previousUtilizationTime = source.previousUtilizationTime;
this.maxResourceUtilization = source.maxResourceUtilization;
this.readOnly = true;
}
/**
* {@inheritDoc}
*
* <p>It will automatically increment the {@link #getUtilization()}
* by applying the {@link #setUtilizationUpdateFunction(Function) increment function}.</p>
* @param time {@inheritDoc}
* @return {@inheritDoc}
*/
@Override
public double getUtilization(double time) {
currentUtilizationTime = time;
if(previousUtilizationTime != time) {
/*Pass a copy of this current UtilizationModel to avoid it to be changed
and also to enable the developer to call the getUtilization() method from
his/her given utilizationUpdateFunction on such an instance,
without causing infinity loop. Without passing a UtilizationModel clone,
since the utilizationUpdateFunction function usually will call this current one, that in turns
calls the utilizationUpdateFunction to update the utilization progress, the infinity
loop condition would be set.*/
currentUtilization = utilizationUpdateFunction.apply(new UtilizationModelDynamic(this));
previousUtilizationTime = time;
if (currentUtilization <= 0) {
currentUtilization = 0;
}
if (currentUtilization > maxResourceUtilization && maxResourceUtilization > 0) {
currentUtilization = maxResourceUtilization;
}
}
return currentUtilization;
}
@Override
public double getUtilization() {
return (readOnly ? currentUtilization : super.getUtilization());
}
/**
* Gets the time difference from the current simulation time to the
* last time the resource utilization was updated.
* @return
*/
public double getTimeSpan(){
return currentUtilizationTime - previousUtilizationTime;
}
/**
* Sets the current resource utilization.
*
* <p>Such a value can be a percentage in scale from [0 to 1] or an absolute value,
* depending on the {@link #getUnit()}.</p>
*
* @param currentUtilization current resource utilization
*/
private void setCurrentUtilization(double currentUtilization) {
validateUtilizationField("currentUtilization", currentUtilization);
this.currentUtilization = currentUtilization;
}
/**
* Gets the maximum amount of resource that will be used.
*
* <p>Such a value can be a percentage in scale from [0 to 1] or an absolute value,
* depending on the {@link #getUnit()}.</p>
*
* @return the maximum resource utilization
*/
public double getMaxResourceUtilization() {
return maxResourceUtilization;
}
/**
* Sets the maximum amount of resource of resource that will be used.
*
* <p>Such a value can be a percentage in scale from [0 to 1] or an absolute value,
* depending on the {@link #getUnit()}.</p>
*
* @param maxResourceUsagePercentage the maximum resource usage
* @return
*/
public final UtilizationModelDynamic setMaxResourceUtilization(double maxResourceUsagePercentage) {
validateUtilizationField("maxResourceUtilization", maxResourceUsagePercentage, ALMOST_ZERO);
this.maxResourceUtilization = maxResourceUsagePercentage;
return this;
}
/**
* Sets the function that defines how the resource utilization will be incremented or decremented along the time.
*
* <p>Such a function must require one {@link UtilizationModelDynamic} parameter and returns the new resource utilization.
* When this function is called internally by this {@code UtilizationModel},
* it receives a read-only {@link UtilizationModelDynamic} instance and allow the developer using this {@code UtilizationModel} to
* define how the utilization must be updated. For instance, to define an arithmetic increment, a Lambda function
* to be given to this setter could be defined as below:
* </p>
*
* <p>{@code um -> um.getUtilization() + um.getTimeSpan()*0.1}</p>
*
* <p>Considering the {@code UtilizationModel} {@link Unit} was defined in {@link Unit#PERCENTAGE},
* such a Lambda Expression will increment the usage in 10% for each second that has passed
* since the last time the utilization was computed.</p>
*
* <p>The value returned by the given Lambda Expression will be automatically validated
* to avoid negative utilization or utilization over 100% (when the {@code UtilizationModel} {@link #getUnit() unit}
* is defined in percentage). The function would be defined to decrement the utilization along the time,
* by just changing the plus to a minus signal.</p>
*
* <p>Defining a geometric progression for the resource utilization is as simple as changing the plus signal
* to a multiplication signal.</p>
*
* @param utilizationUpdateFunction the utilization increment function to set, that will receive the
* UtilizationModel instance and must return the new utilization value
* based on the previous utilization.
* @return
*/
public final UtilizationModelDynamic setUtilizationUpdateFunction(Function<UtilizationModelDynamic, Double> utilizationUpdateFunction) {
Objects.requireNonNull(utilizationUpdateFunction);
this.utilizationUpdateFunction = utilizationUpdateFunction;
return this;
}
}
| 44.532075 | 140 | 0.694772 |
3da26fbb76e48e0e61aba4dc57c9e076aa4f7eaa | 69 | package io.renren.modules.hotel.vo;
public class OrderDetailVo {
}
| 11.5 | 35 | 0.768116 |
c7ee6925bd694844010c339796452249e143a94b | 163 | package com.example.generic;
/**
* @Description
* @Date: 2020/9/13 16:04
* @Create by external_ll@163.com
**/
public interface ListP3<A> extends ListP2<A>{
}
| 16.3 | 45 | 0.680982 |
30fdae9d6767b7107dd6f8a0a8f425a5d0f1daed | 1,524 | package gov.noaa.pmel.sgt.beans;
import java.beans.*;
/**
* BeanInfo object for <code>DataModel</code>.
* @author Donald Denbo
* @version $Revision: 1.1 $, $Date: 2004/12/27 16:15:20 $
* @since 3.0
**/
public class DataModelBeanInfo extends SimpleBeanInfo {
private Class beanClass = DataModel.class;
private String iconColor16x16Filename = "DataModelIcon16.gif";
private String iconColor32x32Filename = "DataModelIcon32.gif";
private String iconMono16x16Filename;
private String iconMono32x32Filename;
public DataModelBeanInfo() {
}
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor _page = new PropertyDescriptor("page", beanClass, "getPage", "setPage");
PropertyDescriptor[] pds = new PropertyDescriptor[] {
_page};
return pds;
}
catch(IntrospectionException ex) {
ex.printStackTrace();
return null;
}
}
public java.awt.Image getIcon(int iconKind) {
switch (iconKind) {
case BeanInfo.ICON_COLOR_16x16:
return iconColor16x16Filename != null ? loadImage(iconColor16x16Filename) : null;
case BeanInfo.ICON_COLOR_32x32:
return iconColor32x32Filename != null ? loadImage(iconColor32x32Filename) : null;
case BeanInfo.ICON_MONO_16x16:
return iconMono16x16Filename != null ? loadImage(iconMono16x16Filename) : null;
case BeanInfo.ICON_MONO_32x32:
return iconMono32x32Filename != null ? loadImage(iconMono32x32Filename) : null;
}
return null;
}
}
| 33.130435 | 97 | 0.709318 |
4d6df59a0580618c7cfb15b6f8f453efdc1c45c2 | 13,500 | package inz.maptest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import inz.agents.MobileAgent;
import inz.agents.MobileAgentInterface;
import inz.util.AgentPos;
import inz.util.PopUpWindow;
import jade.android.AndroidHelper;
import jade.android.MicroRuntimeService;
import jade.android.MicroRuntimeServiceBinder;
import jade.android.RuntimeCallback;
import jade.core.MicroRuntime;
import jade.core.Profile;
import jade.util.Logger;
import jade.util.leap.Properties;
import jade.wrapper.AgentController;
import jade.wrapper.ControllerException;
public class Menu extends AppCompatActivity {
private final String SERVER_PORT = "1099";
private Logger logger = Logger.getJADELogger(this.getClass().getName());
private boolean isAgentRunning;
private MobileAgentInterface agentInterface;
private MicroRuntimeServiceBinder microRuntimeServiceBinder;
private ServiceConnection serviceConnection;
private MyReceiver myReceiver;
private String nickname; // name of this Agent
private String mainHost; // IP address of the main container
private String mainPort = SERVER_PORT; // port of the main container
private String groupHostName; // name of the host
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isAgentRunning = false;
setContentView(R.layout.activity_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myReceiver = new MyReceiver();
IntentFilter mobileAgentFilter = new IntentFilter();
mobileAgentFilter.addAction("inz.agents.MobileAgent.SETUP_COMPLETE");
mobileAgentFilter.addAction("inz.agents.MobileAgent.GROUP_UPDATE");
mobileAgentFilter.addAction("inz.agents.MobileAgent.HOST_LEFT");
mobileAgentFilter.addAction("inz.agents.MobileAgent.HOST_NOT_FOUND");
registerReceiver(myReceiver, mobileAgentFilter);
IntentFilter nameTakenFilter = new IntentFilter();
nameTakenFilter.addAction("NAME_TAKEN");
registerReceiver(myReceiver, nameTakenFilter);
IntentFilter connectionErrorFilter = new IntentFilter();
connectionErrorFilter.addAction("CONNECTION_ERROR");
registerReceiver(myReceiver, connectionErrorFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
if (microRuntimeServiceBinder != null)
microRuntimeServiceBinder.stopAgentContainer(containerShutdownCallback);
if (serviceConnection != null)
unbindService(serviceConnection);
logger.log(Level.INFO, "Destroy activity!");
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if(agentInterface == null)
findViewById(R.id.button_map).setVisibility(View.INVISIBLE);
else
findViewById(R.id.button_map).setVisibility(View.VISIBLE);
}
private void disableEditTexts() {
findViewById(R.id.edit_host_name).setEnabled(false);
findViewById(R.id.edit_ip).setEnabled(false);
findViewById(R.id.edit_name).setEnabled(false);
findViewById(R.id.button_start).setVisibility(View.INVISIBLE);
findViewById(R.id.showGroup).setVisibility(View.VISIBLE);
findViewById(R.id.showGroup).setFocusableInTouchMode(false);
findViewById(R.id.showGroup).setFocusable(false);
}
private RuntimeCallback<AgentController> agentStartupCallback = new RuntimeCallback<AgentController>() {
@Override
public void onSuccess(AgentController newAgent) {
isAgentRunning = true;
}
@Override
public void onFailure(Throwable throwable) {
logger.log(Level.INFO, "Nickname already in use!");
Intent broadcast = new Intent();
broadcast.setAction("NAME_TAKEN");
getApplicationContext().sendBroadcast(broadcast);
microRuntimeServiceBinder.stopAgentContainer(containerShutdownCallback);
}
};
private RuntimeCallback<Void> containerShutdownCallback = new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void var1) {
}
@Override
public void onFailure(Throwable throwable) {
logger.log(Level.INFO, "Nickname already in use!");
}
};
public void onMapClick(View view) {
Intent intent = new Intent(this, MapsActivity.class);
intent.putExtra("AGENT_NICKNAME", nickname);
startActivity(intent);
}
public void onSettingsClick(View view) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
public void onStartClick(View view) {
if (isAgentRunning) {
new PopUpWindow(this, "Error", "The agent is already running on this device!");
return;
}
EditText groupHost = (EditText) findViewById(R.id.edit_host_name);
EditText editName = (EditText) findViewById(R.id.edit_name);
EditText editIp = (EditText) findViewById(R.id.edit_ip);
groupHostName = groupHost.getText().toString();
nickname = editName.getText().toString();
mainHost = editIp.getText().toString();
if (mainPort.length() != 0 && mainHost.length() != 0 && nickname.length() != 0) {
final Properties profile = new Properties();
//profile.setProperty(Profile.CONTAINER_NAME, "TestContainer");
profile.setProperty(Profile.MAIN_HOST, mainHost); //10.0.2.2 - emulator; 192.168.1.134 - moj komputer na wifi
profile.setProperty(Profile.MAIN_PORT, mainPort);
profile.setProperty(Profile.MAIN, Boolean.FALSE.toString());
profile.setProperty(Profile.JVM, Profile.ANDROID);
if (AndroidHelper.isEmulator()) {
// Emulator: this is needed to work with emulated devices
profile.setProperty(Profile.LOCAL_HOST, AndroidHelper.LOOPBACK);
profile.setProperty(Profile.LOCAL_PORT, "8777"); // potrzebne jesli na emulatorze robie (adb forward)
} else {
profile.setProperty(Profile.LOCAL_HOST,
AndroidHelper.getLocalIPAddress());
}
if (microRuntimeServiceBinder == null) {
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
microRuntimeServiceBinder = (MicroRuntimeServiceBinder) service;
logger.log(Level.INFO, "Gateway successfully bound to MicroRuntimeService");
startContainer(nickname, profile, agentStartupCallback);
}
public void onServiceDisconnected(ComponentName className) {
microRuntimeServiceBinder = null;
logger.log(Level.INFO, "Gateway unbound from MicroRuntimeService");
}
};
logger.log(Level.INFO, "Binding Gateway to MicroRuntimeService...");
bindService(new Intent(getApplicationContext(),
MicroRuntimeService.class), serviceConnection,
Context.BIND_AUTO_CREATE);
} else {
logger.log(Level.INFO, "MicroRumtimeGateway already binded to service");
startContainer(nickname, profile, agentStartupCallback);
}
} else {
if (nickname.length() == 0)
editName.setHint("Fill!");
if (mainHost.length() == 0)
editIp.setHint("Fill!");
}
}
private void startContainer(final String nickname, Properties profile,
final RuntimeCallback<AgentController> agentStartupCallback) {
if (!MicroRuntime.isRunning()) {
microRuntimeServiceBinder.startAgentContainer(profile,
new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void thisIsNull) {
logger.log(Level.INFO, "Successfully start of the container...");
startAgent(nickname, agentStartupCallback);
}
@Override
public void onFailure(Throwable throwable) {
logger.log(Level.SEVERE, "Failed to start the container...");
Intent broadcast = new Intent();
broadcast.setAction("CONNECTION_ERROR");
getApplicationContext().sendBroadcast(broadcast);
}
});
} else {
startAgent(nickname, agentStartupCallback);
}
}
private void startAgent(final String nickname,
final RuntimeCallback<AgentController> agentStartupCallback) {
String agentName = MobileAgent.class.getName();
Object[] params;
if (groupHostName.length() != 0) {
params = new Object[]{this, "Client", groupHostName};
} else {
params = new Object[]{this, "Host"};
}
microRuntimeServiceBinder.startAgent(nickname,
agentName,
params,
new RuntimeCallback<Void>() {
@Override
public void onSuccess(Void thisIsNull) {
try {
agentStartupCallback.onSuccess(MicroRuntime.getAgent(nickname));
} catch (ControllerException e) {
// Should never happen
agentStartupCallback.onFailure(e);
}
}
@Override
public void onFailure(Throwable throwable) {
agentStartupCallback.onFailure(throwable);
}
});
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
logger.log(Level.INFO, "Received intent " + action);
if(action.equals("inz.agents.MobileAgent.SETUP_COMPLETE")) {
try {
agentInterface = MicroRuntime.getAgent(nickname).getO2AInterface(MobileAgentInterface.class);
disableEditTexts();
((TextView) findViewById(R.id.showGroup)).setText("- " + nickname);
} catch (ControllerException e) {
findViewById(R.id.button_map).setVisibility(View.INVISIBLE);
e.printStackTrace();
}
if (agentInterface != null)
findViewById(R.id.button_map).setVisibility(View.VISIBLE);
}
else if(action.equals("NAME_TAKEN")){
new PopUpWindow(context,"Error", "The agent with this name already exists!" );
}
else if(action.equals("CONNECTION_ERROR")) {
new PopUpWindow(context,"Error", "Couldn't establish connection to server!" );
}
else if(action.equals("inz.agents.MobileAgent.GROUP_UPDATE")) {
ArrayList<AgentPos> group = agentInterface.getGroup();
String groupNames = new String();
groupNames += "- " + nickname;
for(AgentPos anAgent: group) {
if(groupNames.isEmpty())
groupNames += "- " + anAgent.getName();
else
groupNames += "\n" + "- " + anAgent.getName();
}
((TextView) findViewById(R.id.showGroup)).setText(groupNames);
}
else if(action.equals("inz.agents.MobileAgent.HOST_LEFT")) {
new PopUpWindow(context, "Host left", "Host has left the group.");
agentInterface = null;
findViewById(R.id.button_map).setVisibility(View.INVISIBLE);
}
else if(action.equals("inz.agents.MobileAgent.HOST_NOT_FOUND")) {
new PopUpWindow(context, "Host not found", "Host with given name does not exist.");
agentInterface = null;
findViewById(R.id.button_map).setVisibility(View.INVISIBLE);
microRuntimeServiceBinder.stopAgentContainer(containerShutdownCallback);
isAgentRunning = false;
}
}
}
} | 39.823009 | 122 | 0.60963 |
31b74b9d088e0fdf77843d70f6f95de5d00465e5 | 2,769 | package com.senseidb.jmx;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.log4j.Logger;
import com.sun.jmx.mbeanserver.SunJmxMBeanServer;
/**
* Registers a custom platformMBeanServer, that is tolerable to registering severl MBeans with the same name. Instead of throwing the InstanceAlreadyExistsException
* it will try to add the numeric suffix to the ObjectName prior to registration
* @author vzhabiuk
*
*/
public class JmxSenseiMBeanServer {
private static Logger logger = Logger.getLogger(JmxSenseiMBeanServer.class);
private static boolean registered = false;
public synchronized static void registerCustomMBeanServer() {
try {
if (!registered) {
MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
Field platformMBeanServerField = ManagementFactory.class.getDeclaredField("platformMBeanServer");
platformMBeanServerField.setAccessible(true);
Object modifiedMbeanServer = Proxy.newProxyInstance(platformMBeanServer.getClass().getClassLoader(),
new Class[] { MBeanServer.class, SunJmxMBeanServer.class }, new MBeanServerInvocationHandler(
platformMBeanServer));
platformMBeanServerField.set(null, modifiedMbeanServer);
registered = true;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static class MBeanServerInvocationHandler implements InvocationHandler {
final MBeanServer mBeanServer;
public MBeanServerInvocationHandler(MBeanServer underlying) {
this.mBeanServer = underlying;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!method.getName().equals("registerMBean")) {
return method.invoke(mBeanServer, args);
}
ObjectName objectName = (ObjectName) args[1];
String canonicalName = objectName.getCanonicalName();
if (!canonicalName.contains(".sensei") && !canonicalName.contains(".linkedin") && !canonicalName.contains(".zoie") && !canonicalName.contains(".bobo")) {
return method.invoke(mBeanServer, args);
}
for (int i = 0; i < 200; i++) {
if (!mBeanServer.isRegistered(objectName)) {
break;
}
logger.warn("The JMX bean with name [" + canonicalName + "] is already registered. Trying to add a numeric suffix to register the another one");
objectName = new ObjectName(canonicalName + i);
}
args[1] = objectName;
return method.invoke(mBeanServer, args);
}
}
} | 39 | 165 | 0.719393 |
fe30c16013b081d1d3f606000394a9c79a11c88f | 5,995 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections.primitives;
import org.apache.commons.collections.primitives.decorators.UnmodifiableByteIterator;
import org.apache.commons.collections.primitives.decorators.UnmodifiableByteList;
import org.apache.commons.collections.primitives.decorators.UnmodifiableByteListIterator;
/**
* This class consists exclusively of static methods that operate on or
* return ByteCollections.
* <p>
* The methods of this class all throw a NullPoByteerException if the
* provided collection is null.
*
* @version $Revision$ $Date$
*
* @author Rodney Waldhoff
*/
public final class ByteCollections {
/**
* Returns an unmodifiable ByteList containing only the specified element.
* @param value the single value
* @return an unmodifiable ByteList containing only the specified element.
*/
public static ByteList singletonByteList(byte value) {
// TODO: a specialized implementation of ByteList may be more performant
ByteList list = new ArrayByteList(1);
list.add(value);
return UnmodifiableByteList.wrap(list);
}
/**
* Returns an unmodifiable ByteIterator containing only the specified element.
* @param value the single value
* @return an unmodifiable ByteIterator containing only the specified element.
*/
public static ByteIterator singletonByteIterator(byte value) {
return singletonByteList(value).iterator();
}
/**
* Returns an unmodifiable ByteListIterator containing only the specified element.
* @param value the single value
* @return an unmodifiable ByteListIterator containing only the specified element.
*/
public static ByteListIterator singletonByteListIterator(byte value) {
return singletonByteList(value).listIterator();
}
/**
* Returns an unmodifiable version of the given non-null ByteList.
* @param list the non-null ByteList to wrap in an unmodifiable decorator
* @return an unmodifiable version of the given non-null ByteList
* @throws NullPointerException if the given ByteList is null
* @see org.apache.commons.collections.primitives.decorators.UnmodifiableByteList#wrap
*/
public static ByteList unmodifiableByteList(ByteList list) throws NullPointerException {
if(null == list) {
throw new NullPointerException();
}
return UnmodifiableByteList.wrap(list);
}
/**
* Returns an unmodifiable version of the given non-null ByteIterator.
* @param iter the non-null ByteIterator to wrap in an unmodifiable decorator
* @return an unmodifiable version of the given non-null ByteIterator
* @throws NullPointerException if the given ByteIterator is null
* @see org.apache.commons.collections.primitives.decorators.UnmodifiableByteIterator#wrap
*/
public static ByteIterator unmodifiableByteIterator(ByteIterator iter) {
if(null == iter) {
throw new NullPointerException();
}
return UnmodifiableByteIterator.wrap(iter);
}
/**
* Returns an unmodifiable version of the given non-null ByteListIterator.
* @param iter the non-null ByteListIterator to wrap in an unmodifiable decorator
* @return an unmodifiable version of the given non-null ByteListIterator
* @throws NullPointerException if the given ByteListIterator is null
* @see org.apache.commons.collections.primitives.decorators.UnmodifiableByteListIterator#wrap
*/
public static ByteListIterator unmodifiableByteListIterator(ByteListIterator iter) {
if(null == iter) {
throw new NullPointerException();
}
return UnmodifiableByteListIterator.wrap(iter);
}
/**
* Returns an unmodifiable, empty ByteList.
* @return an unmodifiable, empty ByteList.
* @see #EMPTY_BYTE_LIST
*/
public static ByteList getEmptyByteList() {
return EMPTY_BYTE_LIST;
}
/**
* Returns an unmodifiable, empty ByteIterator
* @return an unmodifiable, empty ByteIterator.
* @see #EMPTY_BYTE_ITERATOR
*/
public static ByteIterator getEmptyByteIterator() {
return EMPTY_BYTE_ITERATOR;
}
/**
* Returns an unmodifiable, empty ByteListIterator
* @return an unmodifiable, empty ByteListIterator.
* @see #EMPTY_BYTE_LIST_ITERATOR
*/
public static ByteListIterator getEmptyByteListIterator() {
return EMPTY_BYTE_LIST_ITERATOR;
}
/**
* An unmodifiable, empty ByteList
* @see #getEmptyByteList
*/
public static final ByteList EMPTY_BYTE_LIST = unmodifiableByteList(new ArrayByteList(0));
/**
* An unmodifiable, empty ByteIterator
* @see #getEmptyByteIterator
*/
public static final ByteIterator EMPTY_BYTE_ITERATOR = unmodifiableByteIterator(EMPTY_BYTE_LIST.iterator());
/**
* An unmodifiable, empty ByteListIterator
* @see #getEmptyByteListIterator
*/
public static final ByteListIterator EMPTY_BYTE_LIST_ITERATOR = unmodifiableByteListIterator(EMPTY_BYTE_LIST.listIterator());
}
| 39.183007 | 129 | 0.710926 |
082df5ec7217de6a1128861fb17a69669faa3731 | 4,134 | package mapreduce1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.elasticsearch.hadoop.mr.EsInputFormat;
import org.elasticsearch.hadoop.mr.WritableArrayWritable;
import org.apache.hadoop.conf.Configuration;
public class mapred6 {
/**
* The mapper reads one line at the time, splits it into an array of single words and emits every
* word to the reducers with the value of 1.
*/
public static class WordCountMapper extends Mapper<Text, MapWritable, Text, LongWritable> {
private final static LongWritable one = new LongWritable(1);
private Text word = new Text();
public void map(Text docId, MapWritable doc, Context context) throws IOException, InterruptedException {
WritableArrayWritable fields = (WritableArrayWritable) doc.get(new Text("text_content"));
Writable text = fields.get()[0];
String cleanLine = text.toString().toLowerCase().replaceAll("[_|$#<>\\^=\\[\\]\\*/\\\\,;,.\\-:()?!\"']", " ");
StringTokenizer tokenizer = new StringTokenizer(cleanLine);
int size1 = tokenizer.countTokens();
fields = (WritableArrayWritable) doc.get(new Text("article_dc_title"));
text = fields.get()[0];
cleanLine = text.toString().toLowerCase().replaceAll("[_|$#<>\\^=\\[\\]\\*/\\\\,;,.\\-:()?!\"']", " ");
tokenizer = new StringTokenizer(cleanLine);
int size2 = tokenizer.countTokens();
context.write(new Text("nrWords"), new LongWritable(size1 + size2));
context.write(new Text("nrDocs"), one);
}
}
/**
* The reducer retrieves every word and puts it into a Map: if the word already exists in the
* map, increments its value, otherwise sets it to 1.
*/
public static class WordCountReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (LongWritable val : values) {
sum += val.get();
}
context.write(new Text(key), new LongWritable(sum));
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
if (args.length != 3) {
System.err.println("Usage: mapred3 outputpath nodeip jsonquery");
System.exit(0);
}
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJobName("mapred5 - " + args[0]);
job.setJarByClass(mapred6.class);;
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
String ip = args[1]; //TODO check validity
String query = args[2];
Configuration c = job.getConfiguration();
c.set("es.nodes", ip + ":9200");
job.setInputFormatClass(EsInputFormat.class);
c.set("es.resource", "kb/doc");
c.set("es.query", query);
FileOutputFormat.setOutputPath(job, new Path(args[0]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
//JobClient.runJob(conf);
}
}
| 37.243243 | 128 | 0.691098 |
8bf0f56cf10f3f603aa28b6c81f9f030fe4bb9ee | 1,171 | package com.codepreplabs.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.BasicConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
static {
BasicConfigurator.configure();
}
@SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
ArrayList<String> skills = (ArrayList<String>) applicationContext
.getBean("skills");
for (String skill : skills)
System.out.println(skill);
HashMap<String, String> addresses = (HashMap<String, String>) applicationContext
.getBean("addresses");
System.out.println(addresses.get("permanentAddress"));
System.out.println(addresses.get("temporaryAddress"));
Properties properties = (Properties) applicationContext.getBean("credentials");
System.out.println(properties.getProperty("username"));
System.out.println(properties.getProperty("password"));
}
}
| 27.232558 | 82 | 0.770282 |
25c548c4b904b2d2fc44badee357516c89e4b16b | 510 | package net.fabricmc.end;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.item.FoodComponent;
public class FoodComponents {
public static final FoodComponent FLUORESCENT_APPLE = (new FoodComponent.Builder()).hunger(4).saturationModifier((float) 0.3).alwaysEdible().statusEffect(new StatusEffectInstance(StatusEffects.GLOWING,400,0), 1F).statusEffect(new StatusEffectInstance(StatusEffects.SLOW_FALLING,400,0), 1F).build();
}
| 51 | 301 | 0.823529 |
d3e9cf7b19a40865aea0bb003ce90564204d1bb4 | 4,701 | /**
* *************************************************************************************************
* <p>
* <p>
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* <p>
* Copyright (c) 2002 - 20014 Bruce Mayhew
* <p>
* 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.
* <p>
* 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.
* <p>
* 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., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* <p>
* Getting Source ==============
* <p>
* Source for this application is maintained at
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.service;
import lombok.AllArgsConstructor;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonMenuItem;
import org.owasp.webgoat.lessons.LessonMenuItemType;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.LessonTracker;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <p>LessonMenuService class.</p>
*
* @author rlawson
* @version $Id: $Id
*/
@Controller
@AllArgsConstructor
public class LessonMenuService {
public static final String URL_LESSONMENU_MVC = "/service/lessonmenu.mvc";
private final Course course;
private final WebSession webSession;
private UserTrackerRepository userTrackerRepository;
/**
* Returns the lesson menu which is used to build the left nav
*
* @return a {@link java.util.List} object.
*/
@RequestMapping(path = URL_LESSONMENU_MVC, produces = "application/json")
public
@ResponseBody
List<LessonMenuItem> showLeftNav() {
List<LessonMenuItem> menu = new ArrayList<>();
List<Category> categories = course.getCategories();
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
for (Category category : categories) {
LessonMenuItem categoryItem = new LessonMenuItem();
categoryItem.setName(category.getName());
categoryItem.setType(LessonMenuItemType.CATEGORY);
// check for any lessons for this category
List<Lesson> lessons = course.getLessons(category);
lessons = lessons.stream().sorted(Comparator.comparing(l -> l.getTitle())).collect(Collectors.toList());
for (Lesson lesson : lessons) {
LessonMenuItem lessonItem = new LessonMenuItem();
lessonItem.setName(lesson.getTitle());
lessonItem.setLink(lesson.getLink());
lessonItem.setType(LessonMenuItemType.LESSON);
LessonTracker lessonTracker = userTracker.getLessonTracker(lesson);
boolean lessonSolved = lessonCompleted(lessonTracker.getLessonOverview(), lesson);
lessonItem.setComplete(lessonSolved);
categoryItem.addChild(lessonItem);
}
categoryItem.getChildren().sort((o1, o2) -> o1.getRanking() - o2.getRanking());
menu.add(categoryItem);
}
return menu;
}
private boolean lessonCompleted(Map<Assignment, Boolean> map, Lesson currentLesson) {
boolean result = true;
for (Map.Entry<Assignment, Boolean> entry : map.entrySet()) {
Assignment storedAssignment = entry.getKey();
for (Assignment lessonAssignment: currentLesson.getAssignments()) {
if (lessonAssignment.getName().equals(storedAssignment.getName())) {
result = result && entry.getValue();
break;
}
}
}
return result;
}
}
| 39.175 | 116 | 0.674112 |
144fd1bc1af793d28d7be653ae8b6934aefc4c03 | 19,859 | /*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.lmu.ifi.dbs.elki.visualization.svg;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.data.spatial.Polygon;
import de.lmu.ifi.dbs.elki.utilities.datastructures.iterator.ArrayListIter;
/**
* Element used for building an SVG path using a string buffer.
*
* @author Erich Schubert
* @since 0.3
*
* @navassoc - create - Element
*/
public class SVGPath {
/**
* String buffer for building the path.
*/
private StringBuilder buf = new StringBuilder(200);
/**
* The last action we did, to not add unnecessary commands
*/
private char lastaction = 0;
/**
* Close path command.
*/
public static final char PATH_CLOSE = 'Z';
/**
* Absolute line to command.
*/
public static final char PATH_LINE_TO = 'L';
/**
* Relative line to command.
*/
public static final char PATH_LINE_TO_RELATIVE = 'l';
/**
* Absolute move command.
*/
public static final char PATH_MOVE = 'M';
/**
* Relative move command.
*/
public static final char PATH_MOVE_RELATIVE = 'm';
/**
* Absolute horizontal line to command.
*/
public static final char PATH_HORIZONTAL_LINE_TO = 'H';
/**
* Relative horizontal line to command.
*/
public static final char PATH_HORIZONTAL_LINE_TO_RELATIVE = 'h';
/**
* Absolute vertical line to command.
*/
public static final char PATH_VERTICAL_LINE_TO = 'V';
/**
* Relative vertical line to command.
*/
public static final char PATH_VERTICAL_LINE_TO_RELATIVE = 'v';
/**
* Absolute cubic line to command.
*/
public static final char PATH_CUBIC_TO = 'C';
/**
* Relative cubic line to command.
*/
public static final char PATH_CUBIC_TO_RELATIVE = 'c';
/**
* Absolute "smooth cubic to" SVG path command.
*/
public static final char PATH_SMOOTH_CUBIC_TO = 'S';
/**
* Relative smooth cubic to command.
*/
public static final char PATH_SMOOTH_CUBIC_TO_RELATIVE = 's';
/**
* Absolute quadratic interpolation to command.
*/
public static final char PATH_QUAD_TO = 'Q';
/**
* Relative quadratic interpolation to command.
*/
public static final char PATH_QUAD_TO_RELATIVE = 'q';
/**
* Absolute smooth quadratic interpolation to
* command.
*/
public static final char PATH_SMOOTH_QUAD_TO = 'T';
/**
* Relative smooth quadratic interpolation to
* command.
*/
public static final char PATH_SMOOTH_QUAD_TO_RELATIVE = 't';
/**
* Absolute path arc command.
*/
public static final char PATH_ARC = 'A';
/**
* Relative path arc command.
*/
public static final char PATH_ARC_RELATIVE = 'a';
/**
* Empty path constructor.
*/
public SVGPath() {
// Nothing to do.
}
/**
* Constructor with initial point.
*
* @param x initial coordinates
* @param y initial coordinates
*/
public SVGPath(double x, double y) {
this();
this.moveTo(x, y);
}
/**
* Constructor with initial point.
*
* @param xy initial coordinates
*/
public SVGPath(double[] xy) {
this();
this.moveTo(xy[0], xy[1]);
}
/**
* Constructor from a double[] collection (e.g. a polygon)
*
* @param vectors vectors
*/
public SVGPath(Polygon vectors) {
this();
for(ArrayListIter<double[]> it = vectors.iter(); it.valid(); it.advance()) {
this.drawTo(it.get());
}
this.close();
}
/**
* Draw a line given a series of coordinates.
*
* Helper function that will use "move" for the first point, "lineto" for the
* remaining.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath drawTo(double x, double y) {
return !isStarted() ? moveTo(x, y) : lineTo(x, y);
}
/**
* Draw a line given a series of coordinates.
*
* Helper function that will use "move" for the first point, "lineto" for the
* remaining.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath drawTo(double[] xy) {
return !isStarted() ? moveTo(xy[0], xy[1]) : lineTo(xy[0], xy[1]);
}
/**
* Test whether the path drawing has already started.
*
* @return Path freshness
*/
public boolean isStarted() {
return lastaction != 0;
}
/**
* Draw a line to the given coordinates.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath lineTo(double x, double y) {
return append(PATH_LINE_TO).append(x).append(y);
}
/**
* Draw a line to the given coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath lineTo(double[] xy) {
return lineTo(xy[0], xy[1]);
}
/**
* Draw a line to the given relative coordinates.
*
* @param x relative coordinates
* @param y relative coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeLineTo(double x, double y) {
return append(PATH_LINE_TO_RELATIVE).append(x).append(y);
}
/**
* Draw a line to the given relative coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeLineTo(double[] xy) {
return relativeLineTo(xy[0], xy[1]);
}
/**
* Draw a horizontal line to the given x coordinate.
*
* @param x new coordinates
* @return path object, for compact syntax.
*/
public SVGPath horizontalLineTo(double x) {
return append(PATH_HORIZONTAL_LINE_TO).append(x);
}
/**
* Draw a horizontal line to the given relative x coordinate.
*
* @param x new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeHorizontalLineTo(double x) {
return append(PATH_HORIZONTAL_LINE_TO_RELATIVE).append(x);
}
/**
* Draw a vertical line to the given y coordinate.
*
* @param y new coordinate
* @return path object, for compact syntax.
*/
public SVGPath verticalLineTo(double y) {
return append(PATH_VERTICAL_LINE_TO).append(y);
}
/**
* Draw a vertical line to the given relative y coordinate.
*
* @param y new coordinate
* @return path object, for compact syntax.
*/
public SVGPath relativeVerticalLineTo(double y) {
return append(PATH_VERTICAL_LINE_TO_RELATIVE).append(y);
}
/**
* Move to the given coordinates.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath moveTo(double x, double y) {
return append(PATH_MOVE).append(x).append(y);
}
/**
* Move to the given coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath moveTo(double[] xy) {
return moveTo(xy[0], xy[1]);
}
/**
* Move to the given relative coordinates.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeMoveTo(double x, double y) {
return append(PATH_MOVE_RELATIVE).append(x).append(y);
}
/**
* Move to the given relative coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeMoveTo(double[] xy) {
return relativeMoveTo(xy[0], xy[1]);
}
/**
* Cubic Bezier line to the given coordinates.
*
* @param c1x first control point x
* @param c1y first control point y
* @param c2x second control point x
* @param c2y second control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath cubicTo(double c1x, double c1y, double c2x, double c2y, double x, double y) {
return append(PATH_CUBIC_TO).append(c1x).append(c1y).append(c2x).append(c2y).append(x).append(y);
}
/**
* Cubic Bezier line to the given coordinates.
*
* @param c1xy first control point
* @param c2xy second control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath cubicTo(double[] c1xy, double[] c2xy, double[] xy) {
return append(PATH_CUBIC_TO).append(c1xy[0]).append(c1xy[1]).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Cubic Bezier line to the given relative coordinates.
*
* @param c1x first control point x
* @param c1y first control point y
* @param c2x second control point x
* @param c2y second control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeCubicTo(double c1x, double c1y, double c2x, double c2y, double x, double y) {
return append(PATH_CUBIC_TO_RELATIVE).append(c1x).append(c1y).append(c2x).append(c2y).append(x).append(y);
}
/**
* Cubic Bezier line to the given relative coordinates.
*
* @param c1xy first control point
* @param c2xy second control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeCubicTo(double[] c1xy, double[] c2xy, double[] xy) {
return append(PATH_CUBIC_TO_RELATIVE).append(c1xy[0]).append(c1xy[1]).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Smooth Cubic Bezier line to the given coordinates.
*
* @param c2x second control point x
* @param c2y second control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath smoothCubicTo(double c2x, double c2y, double x, double y) {
return append(PATH_SMOOTH_CUBIC_TO).append(c2x).append(c2y).append(x).append(y);
}
/**
* Smooth Cubic Bezier line to the given coordinates.
*
* @param c2xy second control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath smoothCubicTo(double[] c2xy, double[] xy) {
return append(PATH_SMOOTH_CUBIC_TO).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Smooth Cubic Bezier line to the given relative coordinates.
*
* @param c2x second control point x
* @param c2y second control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeSmoothCubicTo(double c2x, double c2y, double x, double y) {
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2x).append(c2y).append(x).append(y);
}
/**
* Smooth Cubic Bezier line to the given relative coordinates.
*
* @param c2xy second control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeSmoothCubicTo(double[] c2xy, double[] xy) {
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Quadratic Bezier line to the given coordinates.
*
* @param c1x first control point x
* @param c1y first control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath quadTo(double c1x, double c1y, double x, double y) {
return append(PATH_QUAD_TO).append(c1x).append(c1y).append(x).append(y);
}
/**
* Quadratic Bezier line to the given coordinates.
*
* @param c1xy first control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath quadTo(double[] c1xy, double[] xy) {
return append(PATH_QUAD_TO).append(c1xy[0]).append(c1xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Quadratic Bezier line to the given relative coordinates.
*
* @param c1x first control point x
* @param c1y first control point y
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeQuadTo(double c1x, double c1y, double x, double y) {
return append(PATH_QUAD_TO_RELATIVE).append(c1x).append(c1y).append(x).append(y);
}
/**
* Quadratic Bezier line to the given relative coordinates.
*
* @param c1xy first control point
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeQuadTo(double[] c1xy, double[] xy) {
return append(PATH_QUAD_TO_RELATIVE).append(c1xy[0]).append(c1xy[1]).append(xy[0]).append(xy[1]);
}
/**
* Smooth quadratic Bezier line to the given coordinates.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath smoothQuadTo(double x, double y) {
return append(PATH_SMOOTH_QUAD_TO).append(x).append(y);
}
/**
* Smooth quadratic Bezier line to the given coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath smoothQuadTo(double[] xy) {
return append(PATH_SMOOTH_QUAD_TO).append(xy[0]).append(xy[1]);
}
/**
* Smooth quadratic Bezier line to the given relative coordinates.
*
* @param x new coordinates
* @param y new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeSmoothQuadTo(double x, double y) {
return append(PATH_SMOOTH_QUAD_TO_RELATIVE).append(x).append(y);
}
/**
* Smooth quadratic Bezier line to the given relative coordinates.
*
* @param xy new coordinates
* @return path object, for compact syntax.
*/
public SVGPath relativeSmoothQuadTo(double[] xy) {
return append(PATH_SMOOTH_QUAD_TO_RELATIVE).append(xy[0]).append(xy[1]);
}
/**
* Elliptical arc curve to the given coordinates.
*
* @param rx x radius
* @param ry y radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param x new coordinates
* @param y new coordinates
*/
public SVGPath ellipticalArc(double rx, double ry, double ar, double la, double sp, double x, double y) {
return append(PATH_ARC).append(rx).append(ry).append(ar).append(la).append(sp).append(x).append(y);
}
/**
* Elliptical arc curve to the given coordinates.
*
* @param rx x radius
* @param ry y radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param xy new coordinates
*/
public SVGPath ellipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
}
/**
* Elliptical arc curve to the given coordinates.
*
* @param rxy radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param xy new coordinates
*/
public SVGPath ellipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
}
/**
* Elliptical arc curve to the given relative coordinates.
*
* @param rx x radius
* @param ry y radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param x new coordinates
* @param y new coordinates
*/
public SVGPath relativeEllipticalArc(double rx, double ry, double ar, double la, double sp, double x, double y) {
return append(PATH_ARC_RELATIVE).append(rx).append(ry).append(ar).append(la).append(sp).append(x).append(y);
}
/**
* Elliptical arc curve to the given relative coordinates.
*
* @param rx x radius
* @param ry y radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param xy new coordinates
*/
public SVGPath relativeEllipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC_RELATIVE).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
}
/**
* Elliptical arc curve to the given relative coordinates.
*
* @param rxy radius
* @param ar x-axis-rotation
* @param la large arc flag, if angle >= 180 deg
* @param sp sweep flag, if arc will be drawn in positive-angle direction
* @param xy new coordinates
*/
public SVGPath relativeEllipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC_RELATIVE).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
}
/**
* Append an action to the current path.
*
* @param action Current action
*/
private SVGPath append(char action) {
assert lastaction != 0 || action == PATH_MOVE : "Paths must begin with a move to the initial position!";
if(lastaction != action) {
buf.append(action);
lastaction = action;
}
return this;
}
/**
* Append a value to the current path.
*
* @param x coordinate.
*/
private SVGPath append(double x) {
if(!Double.isFinite(x)) {
throw new IllegalArgumentException("Cannot draw an infinite/NaN position.");
}
if(x >= 0) {
final int l = buf.length();
if(l > 0) {
char c = buf.charAt(l - 1);
assert c != 'e' && c != 'E' : "Invalid exponential in path";
if(c >= '0' && c <= '9')
buf.append(' ');
}
}
buf.append(SVGUtil.FMT.format(x));
return this;
}
/**
* Close the path.
*
* @return path object, for compact syntax.
*/
public SVGPath close() {
assert lastaction != 0 : "Paths must begin with a move to the initial position!";
if(lastaction != PATH_CLOSE) {
buf.append(' ').append(PATH_CLOSE);
lastaction = PATH_CLOSE;
}
return this;
}
/**
* Turn the path buffer into an SVG element.
*
* @param plot Plot context (= element factory)
* @return SVG Element
*/
public Element makeElement(SVGPlot plot) {
Element elem = plot.svgElement(SVGConstants.SVG_PATH_TAG);
elem.setAttribute(SVGConstants.SVG_D_ATTRIBUTE, buf.toString());
return elem;
}
/**
* Turn the path buffer into an SVG element.
* O
*
* @param plot Plot context (= element factory)
* @param cssclass CSS class
* @return SVG Element
*/
public Element makeElement(SVGPlot plot, String cssclass) {
Element elem = plot.svgElement(SVGConstants.SVG_PATH_TAG, cssclass);
elem.setAttribute(SVGConstants.SVG_D_ATTRIBUTE, buf.toString());
return elem;
}
/**
* Return the SVG serialization of the path.
*/
@Override
public String toString() {
return buf.toString();
}
}
| 28.128895 | 134 | 0.660607 |
87ea83c8c963b7f59b7dd79e68704423206f4e75 | 2,399 | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui;
import java.io.Serializable;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.server.StreamVariable;
/**
* {@link DragAndDropWrapper} can receive also files from client computer if
* appropriate HTML 5 features are supported on client side. This class wraps
* information about dragged file on server side.
*/
public class Html5File implements Serializable {
private String name;
private long size;
private StreamVariable streamVariable;
private String type;
Html5File(String name, long size, String mimeType) {
this.name = name;
this.size = size;
type = mimeType;
}
public String getFileName() {
return name;
}
public long getFileSize() {
return size;
}
public String getType() {
return type;
}
/**
* Sets the {@link StreamVariable} that into which the file contents will be
* written. Usage of StreamVariable is similar to {@link Upload} component.
* <p>
* If the {@link StreamVariable} is not set in the {@link DropHandler} the
* file contents will not be sent to server.
* <p>
* <em>Note!</em> receiving file contents is experimental feature depending
* on HTML 5 API's. It is supported only by modern web browsers like Firefox
* 3.6 and above and recent webkit based browsers (Safari 5, Chrome 6) at
* this time.
*
* @param streamVariable
* the callback that returns stream where the implementation
* writes the file contents as it arrives.
*/
public void setStreamVariable(StreamVariable streamVariable) {
this.streamVariable = streamVariable;
}
public StreamVariable getStreamVariable() {
return streamVariable;
}
}
| 30.75641 | 80 | 0.683618 |
6599255e4c3e6d6edd44b87e3a72552d73b975d9 | 219 | package org.onetwo.ext.poi.excel.generator;
import org.apache.poi.ss.usermodel.Cell;
public class CellListenerAdapter implements CellListener {
@Override
public void beforeSetValue(Cell cell, Object value) {
}
}
| 18.25 | 58 | 0.785388 |
2e3ddb50ae79fe04b7df097409fabbb421a2a350 | 4,484 | package com.stacksimus;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
private static final int SCENE_WIDTH = 300;
private static final int SCENE_HEIGHT = 200;
private static final int GRIDPANE_GAP = 10;
private static final int GRIDPANE_PADDING = 25;
private GridPane gridPane;
//GUI Components
private TextField urlTextField = new TextField();
private TextField titleTextField = new TextField();
private TextField artistTextField = new TextField();
CheckBox audioCheckbox = new CheckBox("Audio");
CheckBox videoCheckbox = new CheckBox("Video");
private Label downloadStatusLabel = new Label();
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Youtube Downloader");
gridPane = createGridPane();
createControls();
Scene scene = new Scene(gridPane, SCENE_WIDTH, SCENE_HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
}
private GridPane createGridPane() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.TOP_CENTER);
gridPane.setHgap(GRIDPANE_GAP);
gridPane.setVgap(GRIDPANE_GAP);
gridPane.setPadding(new Insets(GRIDPANE_PADDING, GRIDPANE_PADDING, GRIDPANE_PADDING, GRIDPANE_PADDING));
return gridPane;
}
private void createControls() {
int rowIndex = 0;
gridPane.add(new Label("URL:"), 0, rowIndex);
gridPane.add(urlTextField, 1, rowIndex);
rowIndex++;
gridPane.add(new Label("Title:"), 0, rowIndex);
gridPane.add(titleTextField, 1, rowIndex);
rowIndex++;
gridPane.add(new Label("Artist:"), 0, rowIndex);
gridPane.add(artistTextField, 1, rowIndex);
rowIndex++;
gridPane.add(new Label("Format"), 0, rowIndex);
audioCheckbox.setSelected(true);
videoCheckbox.setSelected(true);
HBox checkboxHBox = new HBox(10, audioCheckbox,videoCheckbox);
gridPane.add(checkboxHBox, 1, rowIndex);
rowIndex++;
Button button = new Button("Download");
button.setOnAction((event) -> {
try {
String url = urlTextField.getText();
boolean extractAudio = audioCheckbox.isSelected();
boolean extractVideo = videoCheckbox.isSelected();
String artist = artistTextField.getText();
String title = titleTextField.getText();
if (!validateInputs(url,title,extractAudio,extractVideo)) {
return;
}
downloadStatusLabel.setText("");
button.setDisable(true);
YoutubeDLTask runner = new YoutubeDLTask(url,artist, title, extractAudio, extractVideo, downloadStatusLabel, button);
Thread youtubeDlThread = new Thread(runner);
youtubeDlThread.setDaemon(true);
youtubeDlThread.start();
} catch (Exception e) {
e.printStackTrace();
}
});
gridPane.add(button, 0, rowIndex);
gridPane.add(downloadStatusLabel, 1,rowIndex);
}
private boolean validateInputs(String url, String title, boolean extractAudio, boolean extractVideo) {
if (url.isEmpty()) {
showAlert("Missing URL", "Please enter a URL");
return false;
}
if (title.isEmpty()) {
showAlert("Missing Title", "Please enter a Title");
return false;
}
if (!extractAudio && !extractVideo) {
showAlert("Missing Format", "Please enter a Format");
return false;
}
return true;
}
private void showAlert(String title, String message) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(gridPane.getScene().getWindow());
alert.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 31.577465 | 134 | 0.604594 |
c7f69dd10058f05da10f7f00a03aa1b450dc4d65 | 616 | package com.github.jonathonrichardson.java2ts.type;
import com.github.jonathonrichardson.java2ts.Type;
import java.util.HashSet;
import java.util.Set;
/**
* Created by jon on 3/24/17.
*/
public class TSString implements Type {
@Override
public Set<Class> getJavaClasses() {
Set<Class> classes = new HashSet<>();
classes.add(String.class);
classes.add(char.class);
return classes;
}
@Override
public String getCastString(String input) {
return input;
}
@Override
public String getTypescriptTypeName() {
return "string";
}
}
| 19.25 | 51 | 0.650974 |
702c52837f789b1ea8665774216fe4db5e0d969b | 3,787 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.common.tracer.test;
import com.alipay.common.tracer.core.appender.self.SelfLog;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author luoguimu123
* @version $Id: MDCTest.java, v 0.1 2017年06月19日 下午6:14 luoguimu123 Exp $
*/
public class MDCTest {
//private static final Logger logger = LoggerFactory.getLogger("traceLog");
@Test
public void test() throws IOException {
Logger logger = LoggerFactory.getLogger("traceLog");
MDC.clear();
MDC.put("sessionId", "f9e287fad9e84cff8b2c2f2ed92adbe6");
MDC.put("cityId", "1");
MDC.put("siteName", "北京");
MDC.put("userName", "userwyh");
logger.info("测试MDC打印一");
MDC.put("mobile", "110");
logger.info("测试MDC打印二");
MDC.put("mchId", "12");
MDC.put("mchName", "商户名称");
logger.info("测试MDC打印三");
BufferedReader reader = new BufferedReader(new FileReader("../logs/trace.log"));
List<String> content = new ArrayList<String>();
while (true) {
String s = reader.readLine();
if (s == null || s.equals("")) {
break;
}
content.add(s);
}
String line1 = content.get(content.size() - 3);
line1 = line1.substring(line1.indexOf(",") + 1);
for (String s : line1.split(",", -1)) {
SelfLog.info(s);
}
String[] array = line1.split(",");
Assert.assertEquals(array[0], "北京");
Assert.assertEquals(array[3], "f9e287fad9e84cff8b2c2f2ed92adbe6");
Assert.assertEquals(array[4], "1");
Assert.assertEquals(array[5], "userwyh");
Assert.assertEquals(array[7], "测试MDC打印一");
String line2 = content.get(content.size() - 2);
line2 = line2.substring(line2.indexOf(",") + 1);
String[] array2 = line2.split(",");
Assert.assertEquals(array2[0], "北京");
Assert.assertEquals(array2[3], "f9e287fad9e84cff8b2c2f2ed92adbe6");
Assert.assertEquals(array2[4], "1");
Assert.assertEquals(array2[5], "userwyh");
Assert.assertEquals(array2[6], "110");
Assert.assertEquals(array2[7], "测试MDC打印二");
String line3 = content.get(content.size() - 1);
line3 = line3.substring(line3.indexOf(",") + 1);
String[] array3 = line3.split(",");
Assert.assertEquals(array3[0], "北京");
Assert.assertEquals(array3[1], "12");
Assert.assertEquals(array3[2], "商户名称");
Assert.assertEquals(array3[3], "f9e287fad9e84cff8b2c2f2ed92adbe6");
Assert.assertEquals(array3[4], "1");
Assert.assertEquals(array3[5], "userwyh");
Assert.assertEquals(array3[6], "110");
Assert.assertEquals(array3[7], "测试MDC打印三");
}
}
| 36.066667 | 88 | 0.637444 |
dc7685b30a7457de1325c0335ae1dcb375b2246a | 335 | package com.sen.myshop.web.ui.dto;
import lombok.Data;
/**
* @Auther: Sen
* @Date: 2019/8/12 02:41
* @Description:
*/
@Data
public class Content {
private Long id;
private String title;
private String subTitle;
private String titleDesc;
private String url;
private String pic;
private String pic2;
}
| 15.952381 | 34 | 0.665672 |
27f4b732a29974b213ae2d9958ee35fe2eeff635 | 249 | package xyz.e3ndr.eventapi.events;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public abstract class AbstractEvent<T extends Enum<?>> {
private final @NonNull T type;
}
| 19.153846 | 56 | 0.795181 |
1a8be70d5f9cb671f827f3bdf50452f0b9216ead | 2,394 | package cz.maku.friday.util;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
public class SpigotUtil {
public static double[] getTPS() {
String version = Bukkit.getServer().getClass().getPackage().getName();
version = version.substring(version.lastIndexOf(".") + 1);
try {
Class<?> serverClass = Class.forName(
"net.minecraft.server." + version + ".MinecraftServer"
);
Object serverObject = serverClass
.getDeclaredMethod("getServer")
.invoke(serverClass);
Field field = serverClass.getDeclaredField("recentTps");
Object tpsObj = field.get(serverObject);
double[] result = (double[]) tpsObj;
return result;
} catch (
NoSuchMethodException
| IllegalAccessException
| InvocationTargetException
| NoSuchFieldException
| ClassNotFoundException var6
) {
var6.printStackTrace();
return null;
}
}
public static String centerTitle(String title) {
StringBuilder result = new StringBuilder();
int spaces = (27 - ChatColor.stripColor(title).length());
for (int i = 0; i < spaces; i++) {
result.append(" ");
}
return result.append(title).toString();
}
public static ItemStack createHead(String value) {
ItemStack head = new ItemStack(Material.PLAYER_HEAD, 1, (short) 3);
SkullMeta meta = (SkullMeta) head.getItemMeta();
GameProfile profile = new GameProfile(UUID.randomUUID(), "");
profile.getProperties().put("textures", new Property("textures", value));
Field profileField = null;
try {
profileField = meta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(meta, profile);
} catch (
IllegalArgumentException
| IllegalAccessException
| NoSuchFieldException
| SecurityException e
) {
e.printStackTrace();
}
head.setItemMeta(meta);
return head;
}
}
| 29.925 | 77 | 0.687552 |
8e48f00933c1636c638be2b98b412e17417a3a53 | 283 | package com.yyxnb.common_res.service;
import com.yyxnb.common_res.bean.UserVo;
/**
* 用户模块对外提供的所有功能
*/
public interface UserService extends IARouterService{
/**
* 用户信息
*/
UserVo getUserInfo();
/**
* 更新信息
*/
void updateUserInfo(UserVo vo);
}
| 13.47619 | 53 | 0.628975 |
5b1b0b62669fb4a726d2b7de70769fc566e1475a | 1,434 | /*
* Copyright 2005-2014 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/ecl1.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.kra.budget.core;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
/**
* This class is for associating common Budget properties to the extended Budget children BOs
*/
public abstract class BudgetAssociate extends KcPersistableBusinessObjectBase implements BudgetAssociateInterface {
private static final long serialVersionUID = 3219654486879418421L;
// private Budget budget;
private Long budgetId;
/**
* Gets the budgetId attribute.
* @return Returns the budgetId.
*/
public Long getBudgetId() {
return budgetId;
}
/**
* Sets the budgetId attribute value.
* @param budgetId The budgetId to set.
*/
public void setBudgetId(Long budgetId) {
this.budgetId = budgetId;
}
}
| 30.510638 | 115 | 0.721757 |
4afcae8c60126041729511b699153c763661496d | 3,391 | package de.kunee.divelog;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.joda.time.LocalDate;
import static de.kunee.divelog.data.DiveLogContract.Dives;
public class DiveDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static final int DIVE_DETAIL_LOADER_ID = 0;
private static final String[] DETAIL_COLUMNS = {
Dives._ID,
Dives.DIVE_NO,
Dives.DIVE_DATE,
Dives.LOCATION,
Dives.TIME_IN,
Dives.DURATION_BOTTOM_TIME,
Dives.DURATION_SAFETY_STOP,
Dives.TANK_PRESSURE_BEFORE,
Dives.TANK_PRESSURE_AFTER,
Dives.DEPTH_MAX,
Dives.TEMPERATURE_AIR,
Dives.TEMPERATURE_SURFACE,
Dives.TEMPERATURE_BOTTOM,
Dives.VISIBILITY,
Dives.WEIGHT,
Dives.DIVE_SKIN,
Dives.WET_SUIT,
Dives.DRY_SUIT,
Dives.HOODED_VEST,
Dives.GLOVES,
Dives.BOOTS,
Dives.COMMENTS,
};
private TextView diveNoView;
private TextView diveDateView;
private TextView locationView;
public DiveDetailFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dive_detail_fragment, container, false);
diveNoView = (TextView) rootView.findViewById(R.id.dive_detail_dive_no);
diveDateView = (TextView) rootView.findViewById(R.id.dive_detail_dive_date);
locationView = (TextView) rootView.findViewById(R.id.dive_detail_location);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DIVE_DETAIL_LOADER_ID, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Intent intent = getActivity().getIntent();
if (intent != null && intent.getData() != null) {
return new CursorLoader(
getActivity(),
intent.getData(),
DETAIL_COLUMNS,
null,
null,
null
);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || !cursor.moveToFirst()) {
return;
}
int diveNo = cursor.getInt(cursor.getColumnIndex(Dives.DIVE_NO));
diveNoView.setText("#" + diveNo);
long diveDate = cursor.getLong(cursor.getColumnIndex(Dives.DIVE_DATE));
LocalDate localDate = new LocalDate(diveDate);
diveDateView.setText(localDate.toString());
String location = cursor.getString(cursor.getColumnIndex(Dives.LOCATION));
locationView.setText(location);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| 31.398148 | 99 | 0.640224 |
4b688a9cb32cc03f9c04bbc199ddc895edbcbdac | 47,896 | package com.skcc.cloudz.zcp.api.iam.service.impl;
import java.io.IOException;
import java.util.HashMap;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.skcc.cloudz.zcp.api.iam.domain.vo.ApiResponseVo;
import com.skcc.cloudz.zcp.api.iam.domain.vo.ZcpNodeListVo;
import com.skcc.cloudz.zcp.api.iam.domain.vo.ZcpUserListVo;
import com.skcc.cloudz.zcp.api.iam.domain.vo.ZcpUserResVo;
import com.skcc.cloudz.zcp.api.iam.service.IamApiService;
@Service
public class IamApiServiceImpl implements IamApiService {
private static final Logger log = LoggerFactory.getLogger(IamApiServiceImpl.class);
@Value("${props.iam.baseUrl}")
private String iamBaseUrl;
@Autowired
private RestTemplate restTemplate;
@Override
public ZcpUserResVo getUser(String id) {
ZcpUserResVo zcpUserResVo = new ZcpUserResVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ZcpUserResVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ZcpUserResVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
zcpUserResVo.setCode(responseEntity.getBody().getCode());
zcpUserResVo.setMsg(responseEntity.getBody().getMsg());
zcpUserResVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return zcpUserResVo;
}
@Override
public ApiResponseVo setUser(HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user")
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updateUser(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo deleteUser(String id) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updatePassword(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/password")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo logout(String userId) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/logout")
.buildAndExpand(userId)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo kubeconfig(String id, String namespace) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/kubeconfig")
.queryParam("namespace", namespace)
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo serviceAccount(String userId) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/serviceAccount")
.buildAndExpand(userId)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ZcpUserListVo getUsers(String keyword) {
ZcpUserListVo zcpUserListVo = new ZcpUserListVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/users")
.queryParam("keyword", keyword)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ZcpUserListVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ZcpUserListVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
zcpUserListVo.setCode(responseEntity.getBody().getCode());
zcpUserListVo.setMsg(responseEntity.getBody().getMsg());
zcpUserListVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return zcpUserListVo;
}
@Override
public ApiResponseVo resetPassword(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/resetPassword")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo resetCredentials(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/resetCredentials")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getClusterRoles(String type) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/rbac/clusterRoles")
.queryParam("type", type)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updateClusterRoleBinding(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/clusterRoleBinding")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getRoleBindings(String id) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/roleBindings")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getNamespaceRoleBinding(String namespace, String id) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/rbac/rolebinding/{namespace}/{id}")
.buildAndExpand(namespace, id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getNamespaces() {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/namespaces")
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo createRoleBinding(String namespace, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/namespace/{namespace}/roleBinding")
.buildAndExpand(namespace)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updateRoleBinding(String namespace, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/namespace/{namespace}/roleBinding")
.buildAndExpand(namespace)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo deleteRoleBinding(String namespace, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/namespace/{namespace}/roleBinding")
.buildAndExpand(namespace)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updateOtpPassword(String id) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/otpPassword")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo deleteOtpPassword(String id) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/otpPassword")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ZcpNodeListVo getNodes() {
ZcpNodeListVo zcpNodeListVo = new ZcpNodeListVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/nodes")
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ZcpNodeListVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ZcpNodeListVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
zcpNodeListVo.setCode(responseEntity.getBody().getCode());
zcpNodeListVo.setMsg(responseEntity.getBody().getMsg());
zcpNodeListVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return zcpNodeListVo;
}
@Override
public ApiResponseVo getDeploymentsStatus(String namespace) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/deployments/status")
.queryParam("namespace", namespace)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getNodesStatus(String namespace) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/nodes/status")
.queryParam("namespace", namespace)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getPodsStatus(String namespace) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/pods/status")
.queryParam("namespace", namespace)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getClusterStatus(String type) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/cluster/{type}/status/")
.buildAndExpand(type)
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo getUsersStatus(String namespace) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/metrics/users/status")
.queryParam("namespace", namespace)
.buildAndExpand()
.toString();
log.info("===> Request Url : {}", url);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
if (responseEntity!= null && responseEntity.getStatusCode() == HttpStatus.OK) {
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
}
} catch (RestClientException e) {
e.printStackTrace();
}
return apiResponseVo;
}
@Override
public ApiResponseVo updateUserAttribute(String id, HashMap<String, Object> reqMap) {
ApiResponseVo apiResponseVo = new ApiResponseVo();
try {
String url = UriComponentsBuilder.fromUriString(iamBaseUrl)
.path("/iam/user/{id}/attributes")
.buildAndExpand(id)
.toString();
log.info("===> Request Url : {}", url);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(reqMap);
log.info("===> Request Body : {}", requestBody);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<ApiResponseVo> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ApiResponseVo.class);
log.info("===> Response status : {}", responseEntity.getStatusCode().value());
log.info("===> Response body msg : {}", responseEntity.getBody().getMsg());
log.info("===> Response body code : {}", responseEntity.getBody().getCode());
log.info("===> Response body data : {}", responseEntity.getBody().getData());
apiResponseVo.setCode(responseEntity.getBody().getCode());
apiResponseVo.setMsg(responseEntity.getBody().getMsg());
apiResponseVo.setData(responseEntity.getBody().getData());
} catch (RestClientException | IOException e) {
e.printStackTrace();
}
return apiResponseVo;
}
}
| 46.864971 | 141 | 0.575643 |
2f6f805bd28332922c7266dd4785d36e83e10783 | 1,808 | package com.liyongquan.dp;
/**
* 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入: coins = [1, 2, 5], amount = 11
* 输出: 3
* 解释: 11 = 5 + 5 + 1
* 示例 2:
* <p>
* 输入: coins = [2], amount = 3
* 输出: -1
*
* <p>
* 说明:
* 你可以认为每种硬币的数量是无限的。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/coin-change
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class CoinChange {
/**
* dp方程
* f(n)=min(f(n-c1),f(n-c2),...,f(n-cn))+1,其中c1~cn为硬币的种类
* 若n<cn,返回0
* <p>
*
* @param coins
* @param amount
* @return
*/
public int coinChange(int[] coins, int amount) {
//边界情况处理
if (amount == 0) {
return 0;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < coins.length; i++) {
if (coins[i] < min) {
min = coins[i];
}
}
if (amount < min) {
return -1;
}
//边界值初始化
int[] fn = new int[amount + 1];
for (int i = 0; i < min; i++) {
fn[i] = -1;
}
//dp表达式
for (int i = min; i <= amount; i++) {
fn[i] = dp(fn, i, coins);
}
return fn[amount];
}
private int dp(int[] fn, int index, int[] coins) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < coins.length; i++) {
if (index == coins[i]) {
return 1;
}
//子问题无解
if (index < coins[i]) {
continue;
}
if (fn[index - coins[i]] > 0 && fn[index - coins[i]] < min) {
min = fn[index - coins[i]];
}
}
return min == Integer.MAX_VALUE ? -1 : (min + 1);
}
}
| 22.320988 | 85 | 0.426991 |
4c89729510dd9d9dac78fda4f689a15695554d24 | 301 | module io.github.alttpj.emu2api.event.api {
exports io.github.alttpj.emu2api.event.api;
requires static org.immutables.value.annotations;
requires static java.compiler;
requires static jakarta.inject;
requires /* non-static */ jakarta.cdi;
requires io.github.alttpj.emu2api.utils.ulid;
}
| 30.1 | 51 | 0.770764 |
1d750a24f270072aef05e52a40175cff0e4b2a53 | 736 | package exprest.test.unit.resource;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import test.exprest.module.system.resources.SystemResource;
import exprest.test.core.TestResourceFactory;
public class SystemResourceTest {
@Test
public void testUser() {
// SystemResource r = TestResourceFactory.getResource(SystemResource.class);
// Assert.assertEquals(r.user().getName(), "joel");
//
// Reporter.log("The logged in user is " + r.user().getName());
}
@Test
public void testAuthorities() {
// SystemResource r = TestResourceFactory.getResource(SystemResource.class);
// Assert.assertEquals(r.user().getAuthorities().size(), 1);
}
}
| 27.259259 | 81 | 0.706522 |
d2b5628c96295081f7abf956df30655f99dbdac0 | 40,459 | /**
* <copyright> </copyright>
*
* $Id$
*/
package orgomg.cwm.objectmodel.behavioral.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import orgomg.cwm.analysis.businessnomenclature.BusinessnomenclaturePackage;
import orgomg.cwm.analysis.businessnomenclature.impl.BusinessnomenclaturePackageImpl;
import orgomg.cwm.analysis.datamining.DataminingPackage;
import orgomg.cwm.analysis.datamining.impl.DataminingPackageImpl;
import orgomg.cwm.analysis.informationvisualization.InformationvisualizationPackage;
import orgomg.cwm.analysis.informationvisualization.impl.InformationvisualizationPackageImpl;
import orgomg.cwm.analysis.olap.OlapPackage;
import orgomg.cwm.analysis.olap.impl.OlapPackageImpl;
import orgomg.cwm.analysis.transformation.TransformationPackage;
import orgomg.cwm.analysis.transformation.impl.TransformationPackageImpl;
import orgomg.cwm.foundation.businessinformation.BusinessinformationPackage;
import orgomg.cwm.foundation.businessinformation.impl.BusinessinformationPackageImpl;
import orgomg.cwm.foundation.datatypes.DatatypesPackage;
import orgomg.cwm.foundation.datatypes.impl.DatatypesPackageImpl;
import orgomg.cwm.foundation.expressions.ExpressionsPackage;
import orgomg.cwm.foundation.expressions.impl.ExpressionsPackageImpl;
import orgomg.cwm.foundation.keysindexes.KeysindexesPackage;
import orgomg.cwm.foundation.keysindexes.impl.KeysindexesPackageImpl;
import orgomg.cwm.foundation.softwaredeployment.SoftwaredeploymentPackage;
import orgomg.cwm.foundation.softwaredeployment.impl.SoftwaredeploymentPackageImpl;
import orgomg.cwm.foundation.typemapping.TypemappingPackage;
import orgomg.cwm.foundation.typemapping.impl.TypemappingPackageImpl;
import orgomg.cwm.management.warehouseoperation.WarehouseoperationPackage;
import orgomg.cwm.management.warehouseoperation.impl.WarehouseoperationPackageImpl;
import orgomg.cwm.management.warehouseprocess.WarehouseprocessPackage;
import orgomg.cwm.management.warehouseprocess.datatype.DatatypePackage;
import orgomg.cwm.management.warehouseprocess.datatype.impl.DatatypePackageImpl;
import orgomg.cwm.management.warehouseprocess.events.EventsPackage;
import orgomg.cwm.management.warehouseprocess.events.impl.EventsPackageImpl;
import orgomg.cwm.management.warehouseprocess.impl.WarehouseprocessPackageImpl;
import orgomg.cwm.objectmodel.behavioral.Argument;
import orgomg.cwm.objectmodel.behavioral.BehavioralFactory;
import orgomg.cwm.objectmodel.behavioral.BehavioralFeature;
import orgomg.cwm.objectmodel.behavioral.BehavioralPackage;
import orgomg.cwm.objectmodel.behavioral.CallAction;
import orgomg.cwm.objectmodel.behavioral.Event;
import orgomg.cwm.objectmodel.behavioral.Interface;
import orgomg.cwm.objectmodel.behavioral.Method;
import orgomg.cwm.objectmodel.behavioral.Operation;
import orgomg.cwm.objectmodel.behavioral.Parameter;
import orgomg.cwm.objectmodel.behavioral.ParameterDirectionKind;
import orgomg.cwm.objectmodel.core.CorePackage;
import orgomg.cwm.objectmodel.core.impl.CorePackageImpl;
import orgomg.cwm.objectmodel.instance.InstancePackage;
import orgomg.cwm.objectmodel.instance.impl.InstancePackageImpl;
import orgomg.cwm.objectmodel.relationships.RelationshipsPackage;
import orgomg.cwm.objectmodel.relationships.impl.RelationshipsPackageImpl;
import orgomg.cwm.resource.multidimensional.MultidimensionalPackage;
import orgomg.cwm.resource.multidimensional.impl.MultidimensionalPackageImpl;
import orgomg.cwm.resource.record.RecordPackage;
import orgomg.cwm.resource.record.impl.RecordPackageImpl;
import orgomg.cwm.resource.relational.RelationalPackage;
import orgomg.cwm.resource.relational.enumerations.EnumerationsPackage;
import orgomg.cwm.resource.relational.enumerations.impl.EnumerationsPackageImpl;
import orgomg.cwm.resource.relational.impl.RelationalPackageImpl;
import orgomg.cwm.resource.xml.XmlPackage;
import orgomg.cwm.resource.xml.impl.XmlPackageImpl;
import orgomg.cwmmip.CwmmipPackage;
import orgomg.cwmmip.impl.CwmmipPackageImpl;
import orgomg.cwmx.analysis.informationreporting.InformationreportingPackage;
import orgomg.cwmx.analysis.informationreporting.impl.InformationreportingPackageImpl;
import orgomg.cwmx.analysis.informationset.InformationsetPackage;
import orgomg.cwmx.analysis.informationset.impl.InformationsetPackageImpl;
import orgomg.cwmx.foundation.er.ErPackage;
import orgomg.cwmx.foundation.er.impl.ErPackageImpl;
import orgomg.cwmx.resource.coboldata.CoboldataPackage;
import orgomg.cwmx.resource.coboldata.impl.CoboldataPackageImpl;
import orgomg.cwmx.resource.dmsii.DmsiiPackage;
import orgomg.cwmx.resource.dmsii.impl.DmsiiPackageImpl;
import orgomg.cwmx.resource.essbase.EssbasePackage;
import orgomg.cwmx.resource.essbase.impl.EssbasePackageImpl;
import orgomg.cwmx.resource.express.ExpressPackage;
import orgomg.cwmx.resource.express.impl.ExpressPackageImpl;
import orgomg.cwmx.resource.imsdatabase.ImsdatabasePackage;
import orgomg.cwmx.resource.imsdatabase.impl.ImsdatabasePackageImpl;
import orgomg.cwmx.resource.imsdatabase.imstypes.ImstypesPackage;
import orgomg.cwmx.resource.imsdatabase.imstypes.impl.ImstypesPackageImpl;
import orgomg.mof.model.ModelPackage;
import orgomg.mof.model.impl.ModelPackageImpl;
/**
* <!-- begin-user-doc --> An implementation of the model <b>Package</b>. <!--
* end-user-doc -->
* @generated
*/
public class BehavioralPackageImpl extends EPackageImpl implements BehavioralPackage {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass argumentEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass behavioralFeatureEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass callActionEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass eventEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass interfaceEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass methodEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass operationEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EClass parameterEClass = null;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private EEnum parameterDirectionKindEEnum = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the
* package package URI value.
* <p>
* Note: the correct way to create the package is via the static factory
* method {@link #init init()}, which also performs initialization of the
* package, or returns the registered package, if one already exists. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see orgomg.cwm.objectmodel.behavioral.BehavioralPackage#eNS_URI
* @see #init()
* @generated
*/
private BehavioralPackageImpl() {
super(eNS_URI, BehavioralFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model,
* and for any others upon which it depends.
*
* <p>
* This method is used to initialize {@link BehavioralPackage#eINSTANCE}
* when that field is accessed. Clients should not invoke it directly.
* Instead, they should simply access that field to obtain the package. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static BehavioralPackage init() {
if (isInited)
return (BehavioralPackage) EPackage.Registry.INSTANCE.getEPackage(BehavioralPackage.eNS_URI);
// Obtain or create and register package
BehavioralPackageImpl theBehavioralPackage = (BehavioralPackageImpl) (EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BehavioralPackageImpl ? EPackage.Registry.INSTANCE
.get(eNS_URI) : new BehavioralPackageImpl());
isInited = true;
// Obtain or create and register interdependencies
CorePackageImpl theCorePackage = (CorePackageImpl) (EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI) instanceof CorePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(CorePackage.eNS_URI) : CorePackage.eINSTANCE);
RelationshipsPackageImpl theRelationshipsPackage = (RelationshipsPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(RelationshipsPackage.eNS_URI) instanceof RelationshipsPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(RelationshipsPackage.eNS_URI) : RelationshipsPackage.eINSTANCE);
InstancePackageImpl theInstancePackage = (InstancePackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(InstancePackage.eNS_URI) instanceof InstancePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(InstancePackage.eNS_URI) : InstancePackage.eINSTANCE);
BusinessinformationPackageImpl theBusinessinformationPackage = (BusinessinformationPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(BusinessinformationPackage.eNS_URI) instanceof BusinessinformationPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(BusinessinformationPackage.eNS_URI) : BusinessinformationPackage.eINSTANCE);
DatatypesPackageImpl theDatatypesPackage = (DatatypesPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(DatatypesPackage.eNS_URI) instanceof DatatypesPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(DatatypesPackage.eNS_URI) : DatatypesPackage.eINSTANCE);
ExpressionsPackageImpl theExpressionsPackage = (ExpressionsPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(ExpressionsPackage.eNS_URI) instanceof ExpressionsPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ExpressionsPackage.eNS_URI) : ExpressionsPackage.eINSTANCE);
KeysindexesPackageImpl theKeysindexesPackage = (KeysindexesPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(KeysindexesPackage.eNS_URI) instanceof KeysindexesPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(KeysindexesPackage.eNS_URI) : KeysindexesPackage.eINSTANCE);
SoftwaredeploymentPackageImpl theSoftwaredeploymentPackage = (SoftwaredeploymentPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(SoftwaredeploymentPackage.eNS_URI) instanceof SoftwaredeploymentPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(SoftwaredeploymentPackage.eNS_URI) : SoftwaredeploymentPackage.eINSTANCE);
TypemappingPackageImpl theTypemappingPackage = (TypemappingPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(TypemappingPackage.eNS_URI) instanceof TypemappingPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(TypemappingPackage.eNS_URI) : TypemappingPackage.eINSTANCE);
RelationalPackageImpl theRelationalPackage = (RelationalPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(RelationalPackage.eNS_URI) instanceof RelationalPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(RelationalPackage.eNS_URI) : RelationalPackage.eINSTANCE);
EnumerationsPackageImpl theEnumerationsPackage = (EnumerationsPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(EnumerationsPackage.eNS_URI) instanceof EnumerationsPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(EnumerationsPackage.eNS_URI) : EnumerationsPackage.eINSTANCE);
RecordPackageImpl theRecordPackage = (RecordPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(RecordPackage.eNS_URI) instanceof RecordPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(RecordPackage.eNS_URI) : RecordPackage.eINSTANCE);
MultidimensionalPackageImpl theMultidimensionalPackage = (MultidimensionalPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(MultidimensionalPackage.eNS_URI) instanceof MultidimensionalPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(MultidimensionalPackage.eNS_URI) : MultidimensionalPackage.eINSTANCE);
XmlPackageImpl theXmlPackage = (XmlPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(XmlPackage.eNS_URI) instanceof XmlPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(XmlPackage.eNS_URI) : XmlPackage.eINSTANCE);
TransformationPackageImpl theTransformationPackage = (TransformationPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(TransformationPackage.eNS_URI) instanceof TransformationPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(TransformationPackage.eNS_URI) : TransformationPackage.eINSTANCE);
OlapPackageImpl theOlapPackage = (OlapPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(OlapPackage.eNS_URI) instanceof OlapPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(OlapPackage.eNS_URI) : OlapPackage.eINSTANCE);
DataminingPackageImpl theDataminingPackage = (DataminingPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(DataminingPackage.eNS_URI) instanceof DataminingPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(DataminingPackage.eNS_URI) : DataminingPackage.eINSTANCE);
InformationvisualizationPackageImpl theInformationvisualizationPackage = (InformationvisualizationPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(InformationvisualizationPackage.eNS_URI) instanceof InformationvisualizationPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(InformationvisualizationPackage.eNS_URI) : InformationvisualizationPackage.eINSTANCE);
BusinessnomenclaturePackageImpl theBusinessnomenclaturePackage = (BusinessnomenclaturePackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(BusinessnomenclaturePackage.eNS_URI) instanceof BusinessnomenclaturePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(BusinessnomenclaturePackage.eNS_URI) : BusinessnomenclaturePackage.eINSTANCE);
WarehouseprocessPackageImpl theWarehouseprocessPackage = (WarehouseprocessPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(WarehouseprocessPackage.eNS_URI) instanceof WarehouseprocessPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(WarehouseprocessPackage.eNS_URI) : WarehouseprocessPackage.eINSTANCE);
DatatypePackageImpl theDatatypePackage = (DatatypePackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(DatatypePackage.eNS_URI) instanceof DatatypePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(DatatypePackage.eNS_URI) : DatatypePackage.eINSTANCE);
EventsPackageImpl theEventsPackage = (EventsPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(EventsPackage.eNS_URI) instanceof EventsPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(EventsPackage.eNS_URI) : EventsPackage.eINSTANCE);
WarehouseoperationPackageImpl theWarehouseoperationPackage = (WarehouseoperationPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(WarehouseoperationPackage.eNS_URI) instanceof WarehouseoperationPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(WarehouseoperationPackage.eNS_URI) : WarehouseoperationPackage.eINSTANCE);
ErPackageImpl theErPackage = (ErPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(ErPackage.eNS_URI) instanceof ErPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ErPackage.eNS_URI) : ErPackage.eINSTANCE);
CoboldataPackageImpl theCoboldataPackage = (CoboldataPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(CoboldataPackage.eNS_URI) instanceof CoboldataPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(CoboldataPackage.eNS_URI) : CoboldataPackage.eINSTANCE);
DmsiiPackageImpl theDmsiiPackage = (DmsiiPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(DmsiiPackage.eNS_URI) instanceof DmsiiPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(DmsiiPackage.eNS_URI) : DmsiiPackage.eINSTANCE);
ImsdatabasePackageImpl theImsdatabasePackage = (ImsdatabasePackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(ImsdatabasePackage.eNS_URI) instanceof ImsdatabasePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ImsdatabasePackage.eNS_URI) : ImsdatabasePackage.eINSTANCE);
ImstypesPackageImpl theImstypesPackage = (ImstypesPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(ImstypesPackage.eNS_URI) instanceof ImstypesPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ImstypesPackage.eNS_URI) : ImstypesPackage.eINSTANCE);
EssbasePackageImpl theEssbasePackage = (EssbasePackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(EssbasePackage.eNS_URI) instanceof EssbasePackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(EssbasePackage.eNS_URI) : EssbasePackage.eINSTANCE);
ExpressPackageImpl theExpressPackage = (ExpressPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(ExpressPackage.eNS_URI) instanceof ExpressPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ExpressPackage.eNS_URI) : ExpressPackage.eINSTANCE);
InformationsetPackageImpl theInformationsetPackage = (InformationsetPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(InformationsetPackage.eNS_URI) instanceof InformationsetPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(InformationsetPackage.eNS_URI) : InformationsetPackage.eINSTANCE);
InformationreportingPackageImpl theInformationreportingPackage = (InformationreportingPackageImpl) (EPackage.Registry.INSTANCE
.getEPackage(InformationreportingPackage.eNS_URI) instanceof InformationreportingPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(InformationreportingPackage.eNS_URI) : InformationreportingPackage.eINSTANCE);
CwmmipPackageImpl theCwmmipPackage = (CwmmipPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(CwmmipPackage.eNS_URI) instanceof CwmmipPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(CwmmipPackage.eNS_URI) : CwmmipPackage.eINSTANCE);
ModelPackageImpl theModelPackage = (ModelPackageImpl) (EPackage.Registry.INSTANCE.getEPackage(ModelPackage.eNS_URI) instanceof ModelPackageImpl ? EPackage.Registry.INSTANCE
.getEPackage(ModelPackage.eNS_URI) : ModelPackage.eINSTANCE);
// Create package meta-data objects
theBehavioralPackage.createPackageContents();
theCorePackage.createPackageContents();
theRelationshipsPackage.createPackageContents();
theInstancePackage.createPackageContents();
theBusinessinformationPackage.createPackageContents();
theDatatypesPackage.createPackageContents();
theExpressionsPackage.createPackageContents();
theKeysindexesPackage.createPackageContents();
theSoftwaredeploymentPackage.createPackageContents();
theTypemappingPackage.createPackageContents();
theRelationalPackage.createPackageContents();
theEnumerationsPackage.createPackageContents();
theRecordPackage.createPackageContents();
theMultidimensionalPackage.createPackageContents();
theXmlPackage.createPackageContents();
theTransformationPackage.createPackageContents();
theOlapPackage.createPackageContents();
theDataminingPackage.createPackageContents();
theInformationvisualizationPackage.createPackageContents();
theBusinessnomenclaturePackage.createPackageContents();
theWarehouseprocessPackage.createPackageContents();
theDatatypePackage.createPackageContents();
theEventsPackage.createPackageContents();
theWarehouseoperationPackage.createPackageContents();
theErPackage.createPackageContents();
theCoboldataPackage.createPackageContents();
theDmsiiPackage.createPackageContents();
theImsdatabasePackage.createPackageContents();
theImstypesPackage.createPackageContents();
theEssbasePackage.createPackageContents();
theExpressPackage.createPackageContents();
theInformationsetPackage.createPackageContents();
theInformationreportingPackage.createPackageContents();
theCwmmipPackage.createPackageContents();
theModelPackage.createPackageContents();
// Initialize created meta-data
theBehavioralPackage.initializePackageContents();
theCorePackage.initializePackageContents();
theRelationshipsPackage.initializePackageContents();
theInstancePackage.initializePackageContents();
theBusinessinformationPackage.initializePackageContents();
theDatatypesPackage.initializePackageContents();
theExpressionsPackage.initializePackageContents();
theKeysindexesPackage.initializePackageContents();
theSoftwaredeploymentPackage.initializePackageContents();
theTypemappingPackage.initializePackageContents();
theRelationalPackage.initializePackageContents();
theEnumerationsPackage.initializePackageContents();
theRecordPackage.initializePackageContents();
theMultidimensionalPackage.initializePackageContents();
theXmlPackage.initializePackageContents();
theTransformationPackage.initializePackageContents();
theOlapPackage.initializePackageContents();
theDataminingPackage.initializePackageContents();
theInformationvisualizationPackage.initializePackageContents();
theBusinessnomenclaturePackage.initializePackageContents();
theWarehouseprocessPackage.initializePackageContents();
theDatatypePackage.initializePackageContents();
theEventsPackage.initializePackageContents();
theWarehouseoperationPackage.initializePackageContents();
theErPackage.initializePackageContents();
theCoboldataPackage.initializePackageContents();
theDmsiiPackage.initializePackageContents();
theImsdatabasePackage.initializePackageContents();
theImstypesPackage.initializePackageContents();
theEssbasePackage.initializePackageContents();
theExpressPackage.initializePackageContents();
theInformationsetPackage.initializePackageContents();
theInformationreportingPackage.initializePackageContents();
theCwmmipPackage.initializePackageContents();
theModelPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theBehavioralPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(BehavioralPackage.eNS_URI, theBehavioralPackage);
return theBehavioralPackage;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getArgument() {
return argumentEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getArgument_Value() {
return (EReference) argumentEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getArgument_CallAction() {
return (EReference) argumentEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getBehavioralFeature() {
return behavioralFeatureEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EAttribute getBehavioralFeature_IsQuery() {
return (EAttribute) behavioralFeatureEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getBehavioralFeature_Parameter() {
return (EReference) behavioralFeatureEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getCallAction() {
return callActionEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getCallAction_ActualArgument() {
return (EReference) callActionEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getCallAction_Operation() {
return (EReference) callActionEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getCallAction_StepExecution() {
return (EReference) callActionEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getEvent() {
return eventEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getEvent_Parameter() {
return (EReference) eventEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getInterface() {
return interfaceEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getMethod() {
return methodEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getMethod_Body() {
return (EReference) methodEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getMethod_Specification() {
return (EReference) methodEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getOperation() {
return operationEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EAttribute getOperation_IsAbstract() {
return (EAttribute) operationEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getOperation_CallAction() {
return (EReference) operationEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getOperation_Method() {
return (EReference) operationEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EClass getParameter() {
return parameterEClass;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getParameter_DefaultValue() {
return (EReference) parameterEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EAttribute getParameter_Kind() {
return (EAttribute) parameterEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getParameter_BehavioralFeature() {
return (EReference) parameterEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getParameter_Event() {
return (EReference) parameterEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EReference getParameter_Type() {
return (EReference) parameterEClass.getEStructuralFeatures().get(4);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EEnum getParameterDirectionKind() {
return parameterDirectionKindEEnum;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public BehavioralFactory getBehavioralFactory() {
return (BehavioralFactory) getEFactoryInstance();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated)
return;
isCreated = true;
// Create classes and their features
argumentEClass = createEClass(ARGUMENT);
createEReference(argumentEClass, ARGUMENT__VALUE);
createEReference(argumentEClass, ARGUMENT__CALL_ACTION);
behavioralFeatureEClass = createEClass(BEHAVIORAL_FEATURE);
createEAttribute(behavioralFeatureEClass, BEHAVIORAL_FEATURE__IS_QUERY);
createEReference(behavioralFeatureEClass, BEHAVIORAL_FEATURE__PARAMETER);
callActionEClass = createEClass(CALL_ACTION);
createEReference(callActionEClass, CALL_ACTION__ACTUAL_ARGUMENT);
createEReference(callActionEClass, CALL_ACTION__OPERATION);
createEReference(callActionEClass, CALL_ACTION__STEP_EXECUTION);
eventEClass = createEClass(EVENT);
createEReference(eventEClass, EVENT__PARAMETER);
interfaceEClass = createEClass(INTERFACE);
methodEClass = createEClass(METHOD);
createEReference(methodEClass, METHOD__BODY);
createEReference(methodEClass, METHOD__SPECIFICATION);
operationEClass = createEClass(OPERATION);
createEAttribute(operationEClass, OPERATION__IS_ABSTRACT);
createEReference(operationEClass, OPERATION__CALL_ACTION);
createEReference(operationEClass, OPERATION__METHOD);
parameterEClass = createEClass(PARAMETER);
createEReference(parameterEClass, PARAMETER__DEFAULT_VALUE);
createEAttribute(parameterEClass, PARAMETER__KIND);
createEReference(parameterEClass, PARAMETER__BEHAVIORAL_FEATURE);
createEReference(parameterEClass, PARAMETER__EVENT);
createEReference(parameterEClass, PARAMETER__TYPE);
// Create enums
parameterDirectionKindEEnum = createEEnum(PARAMETER_DIRECTION_KIND);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void initializePackageContents() {
if (isInitialized)
return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Obtain other dependent packages
CorePackage theCorePackage = (CorePackage) EPackage.Registry.INSTANCE.getEPackage(CorePackage.eNS_URI);
WarehouseoperationPackage theWarehouseoperationPackage = (WarehouseoperationPackage) EPackage.Registry.INSTANCE
.getEPackage(WarehouseoperationPackage.eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
argumentEClass.getESuperTypes().add(theCorePackage.getModelElement());
behavioralFeatureEClass.getESuperTypes().add(theCorePackage.getFeature());
callActionEClass.getESuperTypes().add(theCorePackage.getModelElement());
eventEClass.getESuperTypes().add(theCorePackage.getModelElement());
interfaceEClass.getESuperTypes().add(theCorePackage.getClassifier());
methodEClass.getESuperTypes().add(this.getBehavioralFeature());
operationEClass.getESuperTypes().add(this.getBehavioralFeature());
parameterEClass.getESuperTypes().add(theCorePackage.getModelElement());
// Initialize classes and features; add operations and parameters
initEClass(argumentEClass, Argument.class, "Argument", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getArgument_Value(), theCorePackage.getExpression(), null, "value", null, 0, 1, Argument.class,
!IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE,
!IS_DERIVED, IS_ORDERED);
initEReference(getArgument_CallAction(), this.getCallAction(), this.getCallAction_ActualArgument(), "callAction", null,
0, 1, Argument.class, IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, !IS_RESOLVE_PROXIES,
!IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(behavioralFeatureEClass, BehavioralFeature.class, "BehavioralFeature", IS_ABSTRACT, !IS_INTERFACE,
IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getBehavioralFeature_IsQuery(), theCorePackage.getBoolean(), "isQuery", null, 0, 1,
BehavioralFeature.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE,
!IS_DERIVED, IS_ORDERED);
initEReference(getBehavioralFeature_Parameter(), this.getParameter(), this.getParameter_BehavioralFeature(), "parameter",
null, 0, -1, BehavioralFeature.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE,
!IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(callActionEClass, CallAction.class, "CallAction", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getCallAction_ActualArgument(), this.getArgument(), this.getArgument_CallAction(), "actualArgument", null,
0, -1, CallAction.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES,
!IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getCallAction_Operation(), this.getOperation(), this.getOperation_CallAction(), "operation", null, 1, 1,
CallAction.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE,
IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getCallAction_StepExecution(), theWarehouseoperationPackage.getStepExecution(),
theWarehouseoperationPackage.getStepExecution_CallAction(), "stepExecution", null, 0, -1, CallAction.class,
!IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE,
!IS_DERIVED, IS_ORDERED);
initEClass(eventEClass, Event.class, "Event", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getEvent_Parameter(), this.getParameter(), this.getParameter_Event(), "parameter", null, 0, -1,
Event.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE,
IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(interfaceEClass, Interface.class, "Interface", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEClass(methodEClass, Method.class, "Method", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getMethod_Body(), theCorePackage.getProcedureExpression(), null, "body", null, 0, 1, Method.class,
!IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE,
!IS_DERIVED, IS_ORDERED);
initEReference(getMethod_Specification(), this.getOperation(), this.getOperation_Method(), "specification", null, 1, 1,
Method.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE,
IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(operationEClass, Operation.class, "Operation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getOperation_IsAbstract(), theCorePackage.getBoolean(), "isAbstract", null, 0, 1, Operation.class,
!IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getOperation_CallAction(), this.getCallAction(), this.getCallAction_Operation(), "callAction", null, 0,
-1, Operation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES,
!IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getOperation_Method(), this.getMethod(), this.getMethod_Specification(), "method", null, 0, -1,
Operation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE,
IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(parameterEClass, Parameter.class, "Parameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getParameter_DefaultValue(), theCorePackage.getExpression(), null, "defaultValue", null, 0, 1,
Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE,
IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getParameter_Kind(), this.getParameterDirectionKind(), "kind", null, 0, 1, Parameter.class, !IS_TRANSIENT,
!IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getParameter_BehavioralFeature(), this.getBehavioralFeature(), this.getBehavioralFeature_Parameter(),
"behavioralFeature", null, 0, 1, Parameter.class, IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE,
!IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getParameter_Event(), this.getEvent(), this.getEvent_Parameter(), "event", null, 0, 1, Parameter.class,
IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE,
!IS_DERIVED, IS_ORDERED);
initEReference(getParameter_Type(), theCorePackage.getClassifier(), theCorePackage.getClassifier_Parameter(), "type",
null, 1, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES,
!IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Initialize enums and add enum literals
initEEnum(parameterDirectionKindEEnum, ParameterDirectionKind.class, "ParameterDirectionKind");
addEEnumLiteral(parameterDirectionKindEEnum, ParameterDirectionKind.PDK_IN);
addEEnumLiteral(parameterDirectionKindEEnum, ParameterDirectionKind.PDK_INOUT);
addEEnumLiteral(parameterDirectionKindEEnum, ParameterDirectionKind.PDK_OUT);
addEEnumLiteral(parameterDirectionKindEEnum, ParameterDirectionKind.PDK_RETURN);
// Create resource
createResource(eNS_URI);
}
} // BehavioralPackageImpl
| 51.343909 | 185 | 0.722831 |
a2d040ac15fa9aa01376683770cb421a7cf06619 | 751 | package cn.udslance.leetcode.mainofleetcode0;
/**
* @author H
* @create 2021-07-13 15:42
*/
public class Solution055 {
public void test() {
int[] nums = {3,2,1,0,4};
System.out.println(canJump(nums));
}
public boolean canJump(int[] nums) {
int length = nums.length;
int start = 0;
int end = 1;
int step = 0;
while (end < length) {
if (step > length) {
return false;
}
int max = 0;
for (int i = start; i < end; i++) {
max = Math.max(i + nums[i], max);
}
start = end;
end = max + 1;
step++;
}
return true;
}
}
| 14.72549 | 49 | 0.424767 |
71a0d40167a61f540af1bb80d8cda922b7eb9238 | 65 | package org.pathirage.fdbench.automation;
public class Main {
}
| 13 | 41 | 0.784615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.