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
|
---|---|---|---|---|---|
98bd455dcd3b6e5e75514765a374d34f7f351a2f | 780 | package view.gui;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
public abstract class StackPaneGUIContainer extends GUIContainer {
@FXML
protected StackPane stackPane;
@FXML
protected Button sizedButton;
protected void setFront (Node child) {
stackPane.getChildren().remove(sizedButton);
stackPane.getChildren().add(sizedButton);
stackPane.getChildren().remove(child);
stackPane.getChildren().add(child);
}
protected void bindPaneSize(Pane pane) {
pane.prefHeightProperty().bind(sizedButton.heightProperty());
pane.prefWidthProperty().bind(sizedButton.widthProperty());
}
}
| 26.896552 | 69 | 0.714103 |
71dd1b1837a31ac9d3db96599d5da28756638a10 | 1,041 | package org.trebol.converters.topojo;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.trebol.pojo.AddressPojo;
import org.trebol.jpa.entities.Address;
/**
*
* @author Benjamin La Madrid <bg.lamadrid at gmail.com>
*/
@Component
public class Address2Pojo
implements Converter<Address, AddressPojo> {
@Override
public AddressPojo convert(Address source) {
AddressPojo target = new AddressPojo();
target.setCity(source.getCity());
target.setMunicipality(source.getMunicipality());
target.setFirstLine(source.getFirstLine());
if (source.getSecondLine() != null && !source.getSecondLine().isBlank()) {
target.setSecondLine(source.getSecondLine());
}
if (source.getPostalCode() != null && !source.getPostalCode().isBlank()) {
target.setPostalCode(source.getPostalCode());
}
if (source.getNotes() != null && !source.getNotes().isBlank()) {
target.setNotes(source.getNotes());
}
return target;
}
}
| 29.742857 | 78 | 0.711816 |
0ca35713d2d3d83ae39fe440adf5ffbb0c837446 | 1,746 | //package com.liangtengyu.markdown;
//
//import com.liangtengyu.markdown.service.SaveFileService;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import java.io.IOException;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest(classes = MarkDownApplication.class)
//public class MarkDownApplicationTests {
//
// @Autowired
// SaveFileService saveFileService;
//
// @Test
// public void testsave() throws IOException {
// String testsavefile = saveFileService.saveToFile("4:56:19.834 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]\n" +
// "14:56:19.839 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]\n" +
// "14:56:19.853 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.liangtengyu.markdown.MarkDownApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]\n" +
// "14:56:19.861 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.liangtengyu.markdown.MarkDownApplicationTests], using SpringBootContextLoader\n");
// }
//
//}
| 62.357143 | 292 | 0.810997 |
43b445f069df661b8d3f4c94391bf95ec74db7fb | 689 | package com.jordanluyke.azores.util;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import org.apache.logging.log4j.LogManager;
public class ErrorHandlingSingleObserver<T extends Object> implements SingleObserver<T> {
private Class<?> loggerClass;
public ErrorHandlingSingleObserver() {
loggerClass = getClass();
}
@Override
public void onSuccess(T t) {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
LogManager.getLogger(loggerClass).error("Error: {}", e.getMessage());
}
@Override
public void onSubscribe(Disposable disposable) {
}
}
| 24.607143 | 89 | 0.706821 |
42a454e3e770c2512519c9a8bc71c42484fa8e82 | 1,449 | // package 16-bulletin-board;
// package bulletin;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class SIXTEEN{
public static void main(String[] args) {
String filePath="";
// Check the number of parameters.
//args[0] = "../pride-and-prejudice";
if (args.length == 1) {
filePath = args[0];
} else {
System.out.println("Please provide the file path.");
}
// Check if input files exists.
if (!new File(filePath).exists()) {
System.err.println("Could not find " + filePath);
System.exit(1);
}
// Initialize event bus.
EventManager.initialize();
Map<String, Object> map = new HashMap<>();
map.put("path", filePath);
DataStorage dataStorage = new DataStorage(map, EventManager.DATA_STORAGE, EventManager.WORD_FREQUENCY_COUNTER);
WordFrequencyCounter wordFrequencyCounter_top = new WordFrequencyCounter(map,
EventManager.WORD_FREQUENCY_COUNTER, EventManager.TOP_25);
// Top25 wordFrequencyCounter_z = new Top25(map, EventManager.WORD_FREQUENCY_COUNTER,
// EventManager.WORD_WITH_Z);
Top25 wordFrequencyCounter_z = new Top25(map, EventManager.TOP_25,
EventManager.WORD_WITH_Z);
EventManager.announce(EventManager.DATA_STORAGE, map);
// EventManager.announce(EventManager.WORD_FREQUENCY_COUNTER, map);
// EventManager.announce(EventManager.TOP_25, map);
}
}
| 30.829787 | 119 | 0.68185 |
c4d6508c69fc302cb980ac491b57c9788e85ad16 | 796 | package io.graversen.twaddle;
import io.graversen.twaddle.lib.Utils;
import org.junit.Test;
import java.util.List;
public class UtilsTest
{
@Test
public void testExtractHashtags()
{
final List<String> hashtags1 = Utils.extractHashTags("Hello");
assert hashtags1.isEmpty();
final List<String> hashtags2 = Utils.extractHashTags("Hello #World");
assert !hashtags2.isEmpty();
assert hashtags2.size() == 1;
assert hashtags2.get(0).equals("World");
final List<String> hashtags3 = Utils.extractHashTags("Hello #World, it is nice and #sunny today");
assert !hashtags3.isEmpty();
assert hashtags3.size() == 2;
assert hashtags3.get(0).equals("World");
assert hashtags3.get(1).equals("sunny");
}
}
| 28.428571 | 106 | 0.653266 |
078b9587ada77798526831cfe9bc55b102637623 | 3,886 | //| Copyright - The University of Edinburgh 2015 |
//| |
//| 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 uk.ac.ed.epcc.webapp.tags;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import uk.ac.ed.epcc.webapp.AppContext;
import uk.ac.ed.epcc.webapp.forms.result.FormResult;
import uk.ac.ed.epcc.webapp.servlet.ErrorFilter;
import uk.ac.ed.epcc.webapp.servlet.ServletFormResultVisitor;
import uk.ac.ed.epcc.webapp.servlet.ServletService;
import uk.ac.ed.epcc.webapp.servlet.navigation.NavigationMenuService;
import uk.ac.ed.epcc.webapp.servlet.session.ServletSessionService;
import uk.ac.ed.epcc.webapp.session.AppUserFactory;
import uk.ac.ed.epcc.webapp.session.RequiredPage;
import uk.ac.ed.epcc.webapp.session.SessionService;
/** A custom {@link Tag} that ensures that a current session exists for the user viewing the page
*
* @author spb
*
*/
public class SessionTag extends BasicSessionTag {
@Override
public int doEndTag() throws JspException {
int res = super.doEndTag();
try {
if( res == EVAL_PAGE) {
PageContext page = pageContext;
HttpServletRequest request = (HttpServletRequest) page.getRequest();
HttpServletResponse response = (HttpServletResponse) page.getResponse();
HttpSession session = page.getSession();
AppContext conn = ErrorFilter.retrieveAppContext(request, response);
SessionService<?> session_service = conn.getService(SessionService.class);
if( request.getAttribute(RequiredPage.AM_REQUIRED_PAGE_ATTR) == null){
Object skip=session.getAttribute(RequiredPage.REQUIRED_PAGES_ATTR);
if( session_service != null && session_service.haveCurrentUser() && skip==null && ! ((ServletSessionService) session_service).isSU() ){
AppUserFactory<?> fac = session_service.getLoginFactory();
for(RequiredPage p : fac.getRequiredPages() ){
if( p.required(session_service) ){
ServletFormResultVisitor vis = new ServletFormResultVisitor(conn, request, response);
FormResult form_result = p.getPage(session_service);
// we are displaying a required page.
session_service.setAttribute(RequiredPage.REQUIRED_PAGE_RETURN_ATTR, conn.getService(ServletService.class).encodePage());
request.setAttribute(NavigationMenuService.DISABLE_NAVIGATION_ATTR, Boolean.TRUE);
request.setAttribute(RequiredPage.AM_REQUIRED_PAGE_ATTR,Boolean.TRUE);
form_result.accept(vis);
return SKIP_PAGE;
}
}
// all checks passed cache for session
session.setAttribute(RequiredPage.REQUIRED_PAGES_ATTR,"done");
}
}
}
}catch(Exception e){
throw new JspException(e);
}
return res;
}
@Override
public int doStartTag() throws JspException {
return SKIP_BODY;
}
} | 43.177778 | 142 | 0.664694 |
981acba98312d38b785b5e91c7072ada8a0b1f2b | 99 | package com.liuyun.doubao.io;
public interface Stopable {
void stop(boolean waitCompleted);
}
| 12.375 | 34 | 0.757576 |
219d93ca09aa791cb482bd2f447ab93d0c2ce20f | 4,691 | package breadth_first_search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
*
* @author exponential-e
* 백준 5465번: 곰돌이
*
* @see https://www.acmicpc.net/problem/5465/
*
*/
public class Boj5465 {
private static final char TREE = 'T';
private static final char HIVE = 'H';
private static final char START = 'M';
private static final char END = 'D';
private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
private static final int ROW = 0, COL = 1;
private static int N, S;
private static Point start, end;
private static int[][] beeVisit;
private static ArrayList<Point> hives = new ArrayList<>();
private static class Point {
int row;
int col;
int cnt;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
public Point(int row, int col, int cnt) {
this.row = row;
this.col = col;
this.cnt = cnt;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
char[][] map = new char[N][N];
beeVisit = new int[N][N];
for (int i = 0; i < N; i++) {
Arrays.fill(beeVisit[i], -1);
}
for (int i = 0; i < N; i++) {
String line = br.readLine();
for (int j = 0; j < N; j++) {
map[i][j] = line.charAt(j);
if (map[i][j] == HIVE) {
hives.add(new Point(i, j));
beeVisit[i][j] = 0;
}
if (map[i][j] == START) start = new Point(i, j);
if (map[i][j] == END) end = new Point(i, j);
}
}
spread(map);
System.out.println(binarySearch(map));
}
private static int binarySearch(char[][] map) {
int start = 0, end = N * N * 2;
int result = -1;
while (start <= end) { // 0 ~ 2N^2
int mid = (start + end) / 2;
if (bfs(map, mid)) {
start = mid + 1;
result = mid;
}
else {
end = mid - 1;
}
}
return result;
}
private static boolean bfs(char[][] map, int delay) {
int value = delay * S;
if(value >= beeVisit[start.row][start.col]) return false; // blocked
boolean[][] visit = new boolean[N][N];
Queue<Point> q = new LinkedList<>();
q.offer(new Point(start.row, start.col, value));
visit[start.row][start.col] = true;
while (!q.isEmpty()) {
Point current = q.poll();
for (final int[] DIRECTION : DIRECTIONS) {
int nextRow = current.row + DIRECTION[ROW];
int nextCol = current.col + DIRECTION[COL];
int nextCount = current.cnt + 1;
if (outOfRange(nextRow, nextCol) || map[nextRow][nextCol] == TREE) continue;
if (nextCount >= beeVisit[nextRow][nextCol] || visit[nextRow][nextCol]) continue;
visit[nextRow][nextCol] = true;
if (end.row == nextRow && end.col == nextCol) return true; // safe
q.offer(new Point(nextRow, nextCol, nextCount));
}
}
return false;
}
private static void spread(char[][] map) {
Queue<Point> q = new LinkedList<>();
for (Point start : hives) {
q.offer(start);
}
while (!q.isEmpty()) { // bee moves
Point current = q.poll();
for (final int[] DIRECTION : DIRECTIONS) {
int nextRow = current.row + DIRECTION[ROW];
int nextCol = current.col + DIRECTION[COL];
if (outOfRange(nextRow, nextCol)) continue;
if (map[nextRow][nextCol] == TREE || map[nextRow][nextCol] == END) continue;
if (beeVisit[nextRow][nextCol] != -1) continue;
beeVisit[nextRow][nextCol] = beeVisit[current.row][current.col] + S;
q.offer(new Point(nextRow, nextCol));
}
}
beeVisit[end.row][end.col] = Integer.MAX_VALUE; // can not reach
}
private static boolean outOfRange(int row, int col) {
return row < 0 || row >= N || col < 0 || col >= N;
}
}
| 29.689873 | 97 | 0.492859 |
e5700ee24b530f18365a414a27b200a284e0a7c2 | 332 | package com.didi.tms.duduorder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DuduOrderApplication {
public static void main(String[] args) {
SpringApplication.run(DuduOrderApplication.class, args);
}
}
| 25.538462 | 68 | 0.795181 |
96cd34ba2f4d572c8abb7753d6b8b96cc45cf213 | 249 | package test.priority;
import org.testng.annotations.Test;
public class Priority2SampleTest {
@Test(priority = 1)
public void cOne() {
}
@Test(priority = 2)
public void bTwo() {
}
@Test(priority = 3)
public void aThree() {
}
}
| 13.833333 | 35 | 0.650602 |
eaaceb09ff7e37d72c9d96adf9a75deaabcfb66d | 651 | /**
* Towers of Hanoi
* <p>
* The Towers of Hanoi is a game played with three poles and a number of discs of different sizes which can slide onto any pole. The game starts with all the
* discs stacked in ascending order of size on one pole, the smallest at the top. The aim of the game is to move the entire stack to another pole, obeying the
* following rules:
* <ul>
* <li>Only one disc may be moved at a time.</li>
* <li>Each move consists of taking the upper disc from one of the poles and sliding it onto another pole.</li>
* <li>No disc may be placed on top of a smaller one.</li>
* </ul>
* </p>
*/
package org.oakgp.examples.hanoi;
| 43.4 | 158 | 0.708141 |
c1be8d670205a9ef76ee5dbed97a258617e24560 | 654 | /*
* Developed by Softeq Development Corporation
* http://www.softeq.com
*/
package com.softeq.amilosh.edu.dto;
/**
* Represents Employee transfer object to create Employee.
* <p/>
* Created on 2021-03-24
* <p/>
*
* @author Alexander Milosh
*/
public class EmployeeCreateDto {
private String name;
private Integer placeNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPlaceNumber() {
return placeNumber;
}
public void setPlaceNumber(Integer placeNumber) {
this.placeNumber = placeNumber;
}
}
| 17.675676 | 58 | 0.64526 |
b84489a93f9b1e5068ea652fa243236dbc9fa0dd | 1,616 | //
// Decompiled by Procyon v0.5.36
//
package ch.ethz.ssh2.packets;
import java.io.IOException;
public class PacketOpenSessionChannel
{
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
public PacketOpenSessionChannel(final int channelID, final int initialWindowSize, final int maxPacketSize) {
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
}
public PacketOpenSessionChannel(final byte[] payload, final int off, final int len) throws IOException {
System.arraycopy(payload, off, this.payload = new byte[len], 0, len);
final TypesReader tr = new TypesReader(payload);
final int packet_type = tr.readByte();
if (packet_type != 90) {
throw new IOException("This is not a SSH_MSG_CHANNEL_OPEN! (" + packet_type + ")");
}
this.channelID = tr.readUINT32();
this.initialWindowSize = tr.readUINT32();
this.maxPacketSize = tr.readUINT32();
if (tr.remain() != 0) {
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN packet!");
}
}
public byte[] getPayload() {
if (this.payload == null) {
final TypesWriter tw = new TypesWriter();
tw.writeByte(90);
tw.writeString("session");
tw.writeUINT32(this.channelID);
tw.writeUINT32(this.initialWindowSize);
tw.writeUINT32(this.maxPacketSize);
this.payload = tw.getBytes();
}
return this.payload;
}
}
| 32.32 | 112 | 0.623762 |
16969c42327b33942cb95c78b89844e411e58f0a | 1,824 | package de.metas.vendor.gateway.api;
import de.metas.vendor.gateway.api.availability.AvailabilityRequest;
import de.metas.vendor.gateway.api.availability.AvailabilityResponse;
import de.metas.vendor.gateway.api.order.LocalPurchaseOrderForRemoteOrderCreated;
import de.metas.vendor.gateway.api.order.PurchaseOrderRequest;
import de.metas.vendor.gateway.api.order.RemotePurchaseOrderCreated;
/*
* #%L
* de.metas.vendor.gateway.api
* %%
* Copyright (C) 2018 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%
*/
/**
* Hint: obtain your instance(s) for a given vendor (if any!) via {@link VendorGatewayRegistry#getVendorGatewayServices(int)}.
*
*/
public interface VendorGatewayService
{
boolean isProvidedForVendor(int vendorId);
String testConnection(int configId);
AvailabilityResponse retrieveAvailability(AvailabilityRequest request);
/**
* <b>IMPORTANT: </b> shall not throw an exception. If an exception occurs, it shall be included in the return value.
*/
RemotePurchaseOrderCreated placePurchaseOrder(PurchaseOrderRequest request);
void associateLocalWithRemotePurchaseOrderId(LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated);
}
| 35.764706 | 127 | 0.782346 |
6659deb3bfa5e22ca8d235b0c72c573f355252c9 | 2,254 | package java;
import org.bitcoinj.core.Peer;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Transaction;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
/**
* Created by snakecharmer1024 on 7/19/16.
*/
public class PermutationManager
{
private static PermutationManager singleton; // declares that there can only ever be one PermutationManager instance at a time?
private static Integer lock; // declared for the purposes for the synchronized block later?
public List<Peer> peers; //array of peer objects
public HashMap<Peer, Integer> peerIndexHashMap; //hashmap of peer to index relationship
public HashMap<Sha256Hash, TransactionPermutation> transactionPermutationHashMap; //hashmap of the transaction's hash and a permutation object
// which contains a list of integers corresponding to the peer/index relationship in peerIndexHashMap
public PermutationManager(List<Peer> peers)
{
//constructor
this.peers = peers;
this.peerIndexHashMap = new HashMap<Peer, Integer>();
this.transactionPermutationHashMap = new HashMap<Sha256Hash, TransactionPermutation>();
int i = 0;
for (Peer peer : peers)
{
peerIndexHashMap.put(peer, i++); // establishes the peer/index relationship in the peerIndexHashMap
}
}
public static PermutationManager getPermutationManager()
{
return singleton; //calls the constructor as a singleton?
}
public void addPeerToTransaction(Peer peer, Sha256Hash txHash)
{
synchronized (lock) //thread-safe zone in order not to overwrite or collide in the transactionPermutation mappings
{
TransactionPermutation perm = transactionPermutationHashMap.get(txHash); //loads permutation array for the correct transaction
int index = peerIndexHashMap.get(peer); //loads index of peer argument from the peerIndexHashMap
assert perm.permutation.contains(index) == false; //makes sure that the transactionPermutationHashMap for the tx does not already contain the peer's index
perm.permutation.add(index); // if pass, then add the index to the permutation map
}
}
}
| 40.25 | 166 | 0.723159 |
166c34f2740d6e52425f17ace86e53472e30d832 | 728 | package ca.crimsonglow.simmer;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
/**
* A job object.
*/
public abstract class Job {
/**
* Creates a new job and collects arguments into a properties object.
*
* @param args
* The job arguments.
*/
public Job(String[] args) {
Properties p = new JobProperties(args);
PropertyConfigurator.configure(p);
System.setProperty("aws.accessKeyId", p.getProperty("aws.accessKeyId"));
System.setProperty("aws.secretKey", p.getProperty("aws.secretKey"));
run(p);
}
/**
* The entry point for the job.
*
* @param p
* The job arguments.
*/
protected abstract void run(Properties p);
}
| 22.060606 | 76 | 0.649725 |
08ac94726024eba7d9d91feafe6df5adb7ad6e2f | 5,043 | package org.ftc9974.thorcore.robot.drivetrains.swerve;
import com.qualcomm.robotcore.hardware.AnalogInput;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.ftc9974.thorcore.control.PIDF;
import org.ftc9974.thorcore.internal.RealizableFactory;
import org.ftc9974.thorcore.robot.MotorType;
import org.ftc9974.thorcore.util.MathUtilities;
public final class SwerveModule {
private static final double AT_DIRECTION_THRESHOLD = Math.toRadians(50);
private DcMotorEx driveMotor, slewMotor;
private AnalogInput encoder;
private PIDF slewPid;
private double encoderOffset;
private boolean inverted;
private double targetDirection;
private boolean useQuadEncoder;
private double lowestEncoderValue = 0;
private double highestEncoderValue = 5;
@RealizableFactory
public SwerveModule(String name, HardwareMap hw) {
driveMotor = hw.get(DcMotorEx.class, String.format("SM-%s-driveMotor", name));
slewMotor = hw.get(DcMotorEx.class, String.format("SM-%s-slewMotor", name));
encoder = hw.get(AnalogInput.class, String.format("SM-%s-encoder", name));
driveMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
slewMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
slewPid = new PIDF(1, 0, 0, 0);
slewPid.setContinuityRange(0, 2.0 * Math.PI);
slewPid.setContinuous(true);
}
public void setUseQuadEncoder(boolean useQuadEncoder) {
this.useQuadEncoder = useQuadEncoder;
}
public void setLowestEncoderValue(double lowestEncoderValue) {
this.lowestEncoderValue = lowestEncoderValue;
}
public void setHighestEncoderValue(double highestEncoderValue) {
this.highestEncoderValue = highestEncoderValue;
}
public void setDriveInversion(boolean inversion) {
driveMotor.setDirection(inversion ? DcMotorSimple.Direction.REVERSE : DcMotorSimple.Direction.FORWARD);
}
public void setSlewInversion(boolean inversion) {
slewMotor.setDirection(inversion ? DcMotorSimple.Direction.REVERSE : DcMotorSimple.Direction.FORWARD);
}
public void setPIDFTunings(double p, double i, double d, double f) {
slewPid.setTunings(p, i, d, f);
}
public void setPIDFNominalOutput(double output) {
slewPid.setNominalOutputForward(output);
}
public void setPIDFAtTargetThreshold(double threshold) {
slewPid.setAtTargetThreshold(threshold);
}
public void setEncoderOffset(double offset) {
encoderOffset = offset;
}
public double getCurrentDirection() {
if (!useQuadEncoder) {
double wrappedVoltage = encoder.getVoltage() - encoderOffset;
if (wrappedVoltage < lowestEncoderValue) {
wrappedVoltage += (highestEncoderValue - lowestEncoderValue);
}
return MathUtilities.map(wrappedVoltage, highestEncoderValue, lowestEncoderValue, 0, 2.0 * Math.PI);
} else {
double ticksPerRevolution = MotorType.YELLOWJACKET_71_2.ticksPerRevolution;
return MathUtilities.map(
(slewMotor.getCurrentPosition() + encoderOffset) % ticksPerRevolution,
0,
ticksPerRevolution,
0,
2 * Math.PI
);
}
}
public void setTargetDirection(double direction) {
targetDirection = direction;
}
public double getTargetDirection() {
return targetDirection;
}
public boolean atTargetDirection() {
return Math.abs(slewPid.getLastError()) < AT_DIRECTION_THRESHOLD;
}
public void setDrivePower(double power) {
driveMotor.setPower((inverted) ? -power : power);
}
public void resetEncoder() {
driveMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
driveMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
public void resetSlewEncoder() {
slewMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
slewMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
public void setSlewPower(double power) {
slewMotor.setPower(power);
}
public void update() {
double error = targetDirection - getCurrentDirection();
error %= 2 * Math.PI;
if (Math.abs(error) > Math.PI) {
if (error > 0) {
error -= 2 * Math.PI;
} else {
error += 2 * Math.PI;
}
}
if (Math.abs(error) > 0.5 * Math.PI) {
inverted = true;
} else {
inverted = false;
}
if (inverted) {
slewPid.setSetpoint(targetDirection + Math.PI);
} else {
slewPid.setSetpoint(targetDirection);
}
slewMotor.setPower(slewPid.update(getCurrentDirection()));
}
} | 32.960784 | 112 | 0.664684 |
582606869b634b697445adacff39040d63ef797c | 3,516 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2006, 2007, 2009, 2010, 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.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Simple CSV file reader.
* Current implementation is not bullet-proof, but should be close enough.
* Splits on commas, possibly surrounded by spaces and quotes.
* Doesn't currently handle escaped quotes ("") or quoted strings that contain
* commas (e.g. 1,"Zimbra, Inc.",2).
*
* @author bburtin
*/
public class CsvReader {
private BufferedReader mReader;
private String[] mColNames;
private Map<String, String> mCurrent;
private static final Pattern SPLIT_PATTERN = Pattern.compile("\\\"?\\s*,\\s*\\\"?");
public CsvReader(Reader reader)
throws IOException {
mReader = new BufferedReader(reader);
String line = mReader.readLine();
if (line == null) {
mReader.close();
throw new IOException("CSV reader contains no data");
}
mColNames = SPLIT_PATTERN.split(line);
}
/**
* Returns <code>true</code> if there is another line to read.
*
* @throws IOException if an error occurred while reading the file.
*/
public boolean hasNext()
throws IOException {
String line = mReader.readLine();
if (line == null) {
mReader.close();
return false;
}
// Populate the current map for the line we just got
String[] values = SPLIT_PATTERN.split(line);
int length = Math.min(values.length, mColNames.length);
if (mCurrent == null) {
mCurrent = new HashMap<String, String>();
} else {
mCurrent.clear();
}
for (int i = 0; i < length; i++) {
mCurrent.put(mColNames[i], values[i]);
}
return true;
}
/**
* Returns the names of all the columns in the CSV file.
*/
public String[] getColNames() {
return mColNames;
}
/**
* Returns <code>true</code> if the specified column exists.
*/
public boolean columnExists(String name) {
for (String currentName : mColNames) {
if (currentName.equals(name)) {
return true;
}
}
return false;
}
/**
* Returns the value for the specified column in the current
* line.
*/
public String getValue(String colName) {
if (mCurrent == null) {
throw new IllegalStateException("getValue() called before hasNext()");
}
return mCurrent.get(colName);
}
public void close()
throws IOException {
mReader.close();
}
}
| 30.310345 | 93 | 0.616325 |
35f8751c0ea5385fa791f309b4bd6ea03b0a10d6 | 2,874 | /*
* ====================================================================
* StreamEPS Platform
*
* (C) Copyright 2012.
*
* Distributed under the Modified BSD License.
* Copyright notice: The copyright for this software and a full listing
* of individual contributors are as shown in the packaged copyright.txt
* file.
* 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 ORGANIZATION 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 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 org.streameps.io.netty;
import java.util.concurrent.TimeUnit;
/**
*
* @author Frank Appiah
*/
public class QueueContext implements IQueueContext {
private int size=5;
private long period=10;
private TimeUnit timeUnit=TimeUnit.MILLISECONDS;
public QueueContext() {
}
public QueueContext(int size, long period, TimeUnit timeUnit) {
this.size = size;
this.period = period;
this.timeUnit = timeUnit;
}
public void setQueueSize(int size) {
this.size = size;
}
public int getQueueSize() {
return this.size;
}
public void setPeriod(long period) {
this.period = period;
}
public long getPeriod() {
return this.period;
}
public void setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
public TimeUnit getTimeUnit() {
return this.timeUnit;
}
}
| 33.811765 | 82 | 0.675017 |
ff72d3182d335cc104836135ebf6c14fcb43ada6 | 2,998 | package org.shypl.common.concurrent;
import org.shypl.common.util.Cancelable;
import org.shypl.common.util.LinkedQueue;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class Worker {
private final Object lock = new Object();
private final Queue<Runnable> queue = new LinkedQueue<>();
private final Supplier<ScheduledExecutorService> executor;
private boolean executing;
public Worker(Supplier<ScheduledExecutorService> executor) {
this.executor = executor;
}
public Worker(ScheduledExecutorService executor) {
this.executor = () -> executor;
}
public void addTask(Runnable task) {
synchronized (lock) {
if (executing) {
queue.add(task);
return;
}
executing = true;
}
runTask(task);
processQueue();
}
public Cancelable scheduleTask(Runnable task, long delay, TimeUnit unit) {
ScheduledTaskHolder holder = new ScheduledTaskHolder(task);
holder.setFuture(executor.get().schedule(holder, delay, unit));
return holder;
}
public Cancelable scheduleTask(Runnable task, LocalDateTime date) {
long delayMills = Duration.between(LocalDateTime.now(), date).toMillis();
return scheduleTask(task, delayMills, MILLISECONDS);
}
public Cancelable scheduleTaskPeriodic(Runnable task, long period, TimeUnit unit) {
return scheduleTaskPeriodic(task, period, period, unit);
}
public Cancelable scheduleTaskPeriodic(Runnable task, long initialDelay, long period, TimeUnit unit) {
ScheduledTaskHolder scheduledTask = new ScheduledTaskHolder(task);
scheduledTask.setFuture(executor.get().scheduleAtFixedRate(scheduledTask, initialDelay, period, unit));
return scheduledTask;
}
private void processQueue() {
Runnable task;
while (true) {
synchronized (lock) {
task = queue.poll();
if (task == null) {
executing = false;
return;
}
}
runTask(task);
}
}
private void runTask(Runnable task) {
try {
task.run();
}
catch (Throwable e) {
LoggerFactory.getLogger(Worker.class).error("Error on run task " + task.getClass().getName(), e);
}
}
private class ScheduledTaskHolder implements Cancelable, Runnable {
private final Runnable task;
private ScheduledFuture<?> future;
private volatile boolean actual = true;
public ScheduledTaskHolder(Runnable task) {
this.task = task;
}
@Override
public void run() {
if (actual) {
addTask(task);
}
}
@Override
public void cancel() {
ScheduledFuture<?> f = future;
if (actual) {
actual = false;
f.cancel(false);
future = null;
}
}
public void setFuture(ScheduledFuture<?> future) {
this.future = future;
}
}
}
| 24.983333 | 105 | 0.707138 |
e1ba3c7106f23d4e485b99770d72384b543c8a74 | 8,687 | /*
* Copyright (c) 2002 and later by MH Software-Entwicklung. All Rights Reserved.
*
* JTattoo is multiple licensed. If your are an open source developer you can use
* it under the terms and conditions of the GNU General Public License version 2.0
* or later as published by the Free Software Foundation.
*
* see: gpl-2.0.txt
*
* If you pay for a license you will become a registered user who could use the
* software under the terms and conditions of the GNU Lesser General Public License
* version 2.0 or later with classpath exception as published by the Free Software
* Foundation.
*
* see: lgpl-2.0.txt
* see: classpath-exception.txt
*
* Registered users could also use JTattoo under the terms and conditions of the
* Apache License, Version 2.0 as published by the Apache Software Foundation.
*
* see: APACHE-LICENSE-2.0.txt
*/
package com.jtattoo.plaf.noire;
import com.jtattoo.plaf.AbstractTheme;
import com.jtattoo.plaf.ColorHelper;
import java.awt.Color;
import java.awt.Font;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
/**
* @author Michael Hagen
*/
public class NoireDefaultTheme extends AbstractTheme {
public NoireDefaultTheme() {
super();
// Setup theme with defaults
setUpColor();
// Overwrite defaults with user props
loadProperties();
// Setup the color arrays
setUpColorArrs();
}
public String getPropertyFileName() {
return "NoireTheme.properties";
}
public void setUpColor() {
super.setUpColor();
// Defaults for NoireLookAndFeel
textShadow = true;
foregroundColor = white;
disabledForegroundColor = gray;
disabledBackgroundColor = new ColorUIResource(48, 48, 48);
backgroundColor = new ColorUIResource(24, 26, 28);
backgroundColorLight = new ColorUIResource(24, 26, 28);
backgroundColorDark = new ColorUIResource(4, 5, 6);
alterBackgroundColor = new ColorUIResource(78, 84, 90);
selectionForegroundColor = new ColorUIResource(255, 220, 120);
selectionBackgroundColor = black;
frameColor = black;
gridColor = black;
focusCellColor = orange;
inputBackgroundColor = new ColorUIResource(52, 55, 59);
inputForegroundColor = foregroundColor;
rolloverColor = new ColorUIResource(240, 168, 0);
rolloverColorLight = new ColorUIResource(240, 168, 0);
rolloverColorDark = new ColorUIResource(196, 137, 0);
buttonForegroundColor = black;
buttonBackgroundColor = new ColorUIResource(120, 129, 148);
buttonColorLight = new ColorUIResource(232, 238, 244);
buttonColorDark = new ColorUIResource(196, 200, 208);
controlForegroundColor = foregroundColor;
controlBackgroundColor = new ColorUIResource(52, 55, 59); // netbeans use this for selected tab in the toolbar
controlColorLight = new ColorUIResource(44, 47, 50);
controlColorDark = new ColorUIResource(16, 18, 20);
controlHighlightColor = new ColorUIResource(96, 96, 96);
controlShadowColor = new ColorUIResource(32, 32, 32);
controlDarkShadowColor = black;
windowTitleForegroundColor = foregroundColor;
windowTitleBackgroundColor = new ColorUIResource(144, 148, 149);
windowTitleColorLight = new ColorUIResource(64, 67, 60);
windowTitleColorDark = black;
windowBorderColor = black;
windowIconColor = lightGray;
windowIconShadowColor = black;
windowIconRolloverColor = orange;
windowInactiveTitleForegroundColor = new ColorUIResource(196, 196, 196);
windowInactiveTitleBackgroundColor = new ColorUIResource(64, 64, 64);
windowInactiveTitleColorLight = new ColorUIResource(64, 64, 64);
windowInactiveTitleColorDark = new ColorUIResource(32, 32, 32);
windowInactiveBorderColor = black;
menuForegroundColor = white;
menuBackgroundColor = new ColorUIResource(24, 26, 28);
menuSelectionForegroundColor = black;
menuSelectionBackgroundColor = new ColorUIResource(196, 137, 0);
menuColorLight = new ColorUIResource(96, 96, 96);
menuColorDark = new ColorUIResource(32, 32, 32);
toolbarBackgroundColor = new ColorUIResource(24, 26, 28);
toolbarColorLight = new ColorUIResource(96, 96, 96);
toolbarColorDark = new ColorUIResource(32, 32, 32);
tabAreaBackgroundColor = backgroundColor;
desktopColor = new ColorUIResource(52, 55, 59);
tooltipForegroundColor = white;
tooltipBackgroundColor = black;//new ColorUIResource(16, 16, 16);
controlFont = new FontUIResource("Dialog", Font.BOLD, 12);
systemFont = new FontUIResource("Dialog", Font.BOLD, 12);
userFont = new FontUIResource("Dialog", Font.BOLD, 12);
menuFont = new FontUIResource("Dialog", Font.BOLD, 12);
windowTitleFont = new FontUIResource("Dialog", Font.BOLD, 12);
smallFont = new FontUIResource("Dialog", Font.PLAIN, 10);
}
public void setUpColorArrs() {
super.setUpColorArrs();
Color topHi = ColorHelper.brighter(buttonColorLight, 50);
Color topLo = buttonColorLight;
Color bottomHi = buttonColorDark;
Color bottomLo = ColorHelper.darker(buttonColorDark, 40);
Color topColors[] = ColorHelper.createColorArr(topHi, topLo, 10);
Color bottomColors[] = ColorHelper.createColorArr(bottomHi, bottomLo, 12);
BUTTON_COLORS = new Color[22];
System.arraycopy(topColors, 0, BUTTON_COLORS, 0, 10);
System.arraycopy(bottomColors, 0, BUTTON_COLORS, 10, 12);
topHi = ColorHelper.brighter(controlColorLight, 40);
topLo = ColorHelper.brighter(controlColorDark, 40);
bottomHi = controlColorLight;
bottomLo = controlColorDark;
topColors = ColorHelper.createColorArr(topHi, topLo, 10);
bottomColors = ColorHelper.createColorArr(bottomHi, bottomLo, 12);
DEFAULT_COLORS = new Color[22];
System.arraycopy(topColors, 0, DEFAULT_COLORS, 0, 10);
System.arraycopy(bottomColors, 0, DEFAULT_COLORS, 10, 12);
HIDEFAULT_COLORS = ColorHelper.createColorArr(ColorHelper.brighter(controlColorLight, 15), ColorHelper.brighter(controlColorDark, 15), 20);
ACTIVE_COLORS = ColorHelper.createColorArr(controlColorLight, controlColorDark, 20);
INACTIVE_COLORS = ColorHelper.createColorArr(new Color(64, 64, 64), new Color(32, 32, 32), 20);
SELECTED_COLORS = BUTTON_COLORS;
topHi = ColorHelper.brighter(rolloverColorLight, 40);
topLo = rolloverColorLight;
bottomHi = rolloverColorDark;
bottomLo = ColorHelper.darker(rolloverColorDark, 20);
topColors = ColorHelper.createColorArr(topHi, topLo, 10);
bottomColors = ColorHelper.createColorArr(bottomHi, bottomLo, 12);
ROLLOVER_COLORS = new Color[22];
System.arraycopy(topColors, 0, ROLLOVER_COLORS, 0, 10);
System.arraycopy(bottomColors, 0, ROLLOVER_COLORS, 10, 12);
PRESSED_COLORS = ColorHelper.createColorArr(new Color(64, 64, 64), new Color(96, 96, 96), 20);
DISABLED_COLORS = ColorHelper.createColorArr(new Color(80, 80, 80), new Color(64, 64, 64), 20);
topHi = ColorHelper.brighter(windowTitleColorLight, 40);
topLo = ColorHelper.brighter(windowTitleColorDark, 40);
bottomHi = windowTitleColorLight;
bottomLo = windowTitleColorDark;
topColors = ColorHelper.createColorArr(topHi, topLo, 8);
bottomColors = ColorHelper.createColorArr(bottomHi, bottomLo, 12);
WINDOW_TITLE_COLORS = new Color[20];
System.arraycopy(topColors, 0, WINDOW_TITLE_COLORS, 0, 8);
System.arraycopy(bottomColors, 0, WINDOW_TITLE_COLORS, 8, 12);
WINDOW_INACTIVE_TITLE_COLORS = ColorHelper.createColorArr(windowInactiveTitleColorLight, windowInactiveTitleColorDark, 20);
MENUBAR_COLORS = DEFAULT_COLORS;
TOOLBAR_COLORS = MENUBAR_COLORS;
SLIDER_COLORS = BUTTON_COLORS;
PROGRESSBAR_COLORS = DEFAULT_COLORS;
//THUMB_COLORS = ColorHelper.createColorArr(controlColorLight, controlColorDark, 20);
THUMB_COLORS = DEFAULT_COLORS;
//TRACK_COLORS = ColorHelper.createColorArr(ColorHelper.darker(backgroundColor, 10), ColorHelper.brighter(backgroundColor, 5), 20);
TRACK_COLORS = ColorHelper.createColorArr(ColorHelper.darker(inputBackgroundColor, 5), ColorHelper.brighter(inputBackgroundColor, 10), 20);
TAB_COLORS = DEFAULT_COLORS;
COL_HEADER_COLORS = DEFAULT_COLORS;
}
}
| 44.548718 | 147 | 0.695177 |
559d18e733f11cf947e4003a7fd7118ff66289c8 | 13,992 | package de.otto.edison.aws.dynamodb.jobs;
import com.google.common.collect.ImmutableList;
import de.otto.edison.jobs.domain.JobInfo;
import de.otto.edison.jobs.domain.JobMessage;
import de.otto.edison.jobs.domain.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import software.amazon.awssdk.services.dynamodb.DynamoDBClient;
import software.amazon.awssdk.services.dynamodb.model.*;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import static de.otto.edison.aws.dynamodb.jobs.JobInfoConverter.ID;
import static de.otto.edison.aws.dynamodb.jobs.testsupport.JobInfoMother.jobInfo;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = DynamoDbTestConfiguration.class)
@SpringBootTest
public class DynamoDbJobRepositoryTest {
private static final String TABLE_NAME = "jobInfo";
@Autowired
private DynamoDBClient dynamoDBClient;
private DynamoDbJobRepository dynamoJobRepository;
@Before
public void before() {
createJobInfoTable();
dynamoJobRepository = new DynamoDbJobRepository(dynamoDBClient, new DynamoDbJobRepoProperties(TABLE_NAME, "jobMeta"));
}
@After
public void after() {
deleteJobInfoTable();
}
private void createJobInfoTable() {
dynamoDBClient.createTable(CreateTableRequest.builder()
.tableName(TABLE_NAME)
.keySchema(
KeySchemaElement.builder().attributeName(ID).keyType(KeyType.HASH).build()
)
.attributeDefinitions(
AttributeDefinition.builder().attributeName(ID).attributeType(ScalarAttributeType.S).build()
)
.provisionedThroughput(ProvisionedThroughput.builder()
.readCapacityUnits(1L)
.writeCapacityUnits(1L)
.build())
.build());
}
private void deleteJobInfoTable() {
dynamoDBClient.deleteTable(DeleteTableRequest.builder().tableName(TABLE_NAME).build());
}
@Test
public void shouldWriteAndReadJobInfo() {
// given
JobInfo jobInfo = jobInfo("someJobId").build();
dynamoJobRepository.createOrUpdate(jobInfo);
// when
Optional<JobInfo> jobInfoFromDb = dynamoJobRepository.findOne("someJobId");
// then
assertThat(jobInfoFromDb.get(), is(jobInfo));
}
@Test
public void shouldFindAllJobInfos() {
//given
IntStream.range(0, 50)
.mapToObj(i -> jobInfo("someJobId-" + i).build())
.forEach(jobInfo -> dynamoJobRepository.createOrUpdate(jobInfo));
//when
List<JobInfo> jobInfos = dynamoJobRepository.findAll();
//then
assertThat(jobInfos, hasSize(50));
}
@Test
public void shouldFindByType() {
//given
IntStream.range(0, 10)
.mapToObj(i -> jobInfo("someJobId-" + i).setJobType("type-a").build())
.forEach(jobInfo -> dynamoJobRepository.createOrUpdate(jobInfo));
IntStream.range(10, 20)
.mapToObj(i -> jobInfo("someJobId-" + i).setJobType("type-b").build())
.forEach(jobInfo -> dynamoJobRepository.createOrUpdate(jobInfo));
//when
List<JobInfo> jobInfos = dynamoJobRepository.findByType("type-b");
//then
assertThat(jobInfos, hasSize(10));
assertThat(jobInfos.stream().filter(jobInfo -> jobInfo.getJobType().equals("type-b")).count(), is(10L));
}
@Test
public void shouldFindLatest() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
//when
List<JobInfo> latest = dynamoJobRepository.findLatest(2);
//then
assertThat(latest, hasSize(2));
assertThat(latest.get(0), is(jobInfo2));
assertThat(latest.get(1), is(jobInfo1));
}
@Test
public void shouldFindLatestJobsDistinct() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setJobType("foo").build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).setJobType("bar").build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).setJobType("baz").build();
JobInfo jobInfo4 = jobInfo("someJobId4").setStarted(now.minusMinutes(5)).setJobType("foo").build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
dynamoJobRepository.createOrUpdate(jobInfo4);
//when
List<JobInfo> latest = dynamoJobRepository.findLatestJobsDistinct();
//then
assertThat(latest, hasSize(3));
assertThat(latest.get(0), is(jobInfo2));
assertThat(latest.get(1), is(jobInfo1));
assertThat(latest.get(2), is(jobInfo3));
}
@Test
public void shouldFindLatestByType() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setJobType("foo").build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).setJobType("bar").build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).setJobType("baz").build();
JobInfo jobInfo4 = jobInfo("someJobId4").setStarted(now.minusMinutes(5)).setJobType("foo").build();
JobInfo jobInfo5 = jobInfo("someJobId5").setStarted(now.minusMinutes(9)).setJobType("foo").build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
dynamoJobRepository.createOrUpdate(jobInfo4);
dynamoJobRepository.createOrUpdate(jobInfo5);
//when
List<JobInfo> latest = dynamoJobRepository.findLatestBy("foo", 2);
//then
assertThat(latest, hasSize(2));
assertThat(latest.get(0), is(jobInfo1));
assertThat(latest.get(1), is(jobInfo4));
}
@Test
public void shouldFindRunningWithoutUpdateSince() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setLastUpdated(now.minusMinutes(2)).setStopped(null).build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).setLastUpdated(now.minusSeconds(10)).setStopped(null).build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).setLastUpdated(now.minusSeconds(61)).setStopped(null).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
//when
List<JobInfo> latest = dynamoJobRepository.findRunningWithoutUpdateSince(now.minusMinutes(1));
//then
assertThat(latest, hasSize(2));
assertThat(latest.get(0), is(jobInfo1));
assertThat(latest.get(1), is(jobInfo3));
}
@Test
public void shouldFindAllJobInfoWithoutMessages() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setMessages(singletonList(JobMessage.jobMessage(Level.INFO, "some message", now))).build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).setMessages(emptyList()).build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).setMessages(singletonList(JobMessage.jobMessage(Level.ERROR, "some other message", now))).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
//when
List<JobInfo> latest = dynamoJobRepository.findAllJobInfoWithoutMessages();
//then
assertThat(latest, hasSize(3));
assertThat(latest.get(1).getMessages(), is(emptyList()));
assertThat(latest.get(0).getMessages(), is(emptyList()));
assertThat(latest.get(2).getMessages(), is(emptyList()));
}
@Test
public void shouldRemoveIfStopped() {
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setStopped(now.minusSeconds(1)).build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).setStopped(null).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
//when
dynamoJobRepository.removeIfStopped("someJobId1");
dynamoJobRepository.removeIfStopped("someJobId2");
//then
List<JobInfo> allJobs = dynamoJobRepository.findAll();
assertThat(allJobs, hasSize(1));
assertThat(allJobs.get(0), is(jobInfo2));
}
@Test
public void shouldDeleteAll() {
IntStream.range(0, 90)
.mapToObj(i -> jobInfo("someJobId-" + i).setJobType("type-a").build())
.forEach(jobInfo -> dynamoJobRepository.createOrUpdate(jobInfo));
//when
dynamoJobRepository.deleteAll();
//then
List<JobInfo> allJobs = dynamoJobRepository.findAll();
assertThat(allJobs, hasSize(0));
}
@Test
public void shouldAppendMessageToJobItem() {
//given
JobMessage firstMessage = JobMessage.jobMessage(Level.INFO, "first message", OffsetDateTime.now());
JobInfo jobInfo1 = jobInfo("someJobId").setMessages(Collections.singletonList(firstMessage)).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
//when
JobMessage secondMessage = JobMessage.jobMessage(Level.WARNING, "some message", OffsetDateTime.now());
dynamoJobRepository.appendMessage("someJobId", secondMessage);
//then
Optional<JobInfo> jobInfo = dynamoJobRepository.findOne("someJobId");
assertThat(jobInfo.get().getMessages(), contains(firstMessage, secondMessage));
}
@Test
public void shouldSetJobStatus() {
//given
JobInfo jobInfo1 = jobInfo("someJobId").setStatus(JobInfo.JobStatus.OK).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
//when
dynamoJobRepository.setJobStatus("someJobId", JobInfo.JobStatus.ERROR);
//then
Optional<JobInfo> jobInfo = dynamoJobRepository.findOne("someJobId");
assertThat(jobInfo.get().getStatus(), is(JobInfo.JobStatus.ERROR));
}
@Test
public void shouldSetLastUpdate() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId").setLastUpdated(now.minusMinutes(5)).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
//when
dynamoJobRepository.setLastUpdate("someJobId", now);
//then
Optional<JobInfo> jobInfo = dynamoJobRepository.findOne("someJobId");
assertThat(jobInfo.get().getLastUpdated(), is(now));
}
@Test
public void shouldReportRepositorySize() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).build();
JobInfo jobInfo2 = jobInfo("someJobId2").setStarted(now.minusSeconds(5)).build();
JobInfo jobInfo3 = jobInfo("someJobId3").setStarted(now.minusMinutes(3)).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
dynamoJobRepository.createOrUpdate(jobInfo2);
dynamoJobRepository.createOrUpdate(jobInfo3);
//when
long size = dynamoJobRepository.size();
//then
assertThat(size, is(3L));
}
@Test
public void shouldFindStatus() {
//given
OffsetDateTime now = OffsetDateTime.now();
JobInfo jobInfo1 = jobInfo("someJobId1").setStarted(now.minusSeconds(7)).setStatus(JobInfo.JobStatus.DEAD).build();
dynamoJobRepository.createOrUpdate(jobInfo1);
//when
JobInfo.JobStatus status = dynamoJobRepository.findStatus("someJobId1");
//then
assertThat(status, is(JobInfo.JobStatus.DEAD));
}
@Test
public void shouldNotFailOnEmptyStuff() {
// given
JobInfo jobInfo = JobInfo.builder()
.setJobId("someJob")
.setStatus(JobInfo.JobStatus.OK)
.setStarted(OffsetDateTime.now())
.setLastUpdated(OffsetDateTime.now())
.build();
// when
dynamoJobRepository.createOrUpdate(jobInfo);
// then
assertThat(dynamoJobRepository.size(), is(1L));
}
}
| 37.918699 | 179 | 0.672384 |
d33fd7803eb6830fb7ff5fc113d1adb7fe01f56c | 2,093 | /*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.templateengine.context.dialect;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
public class WriteVarAttributeTagProcessor extends AbstractAttributeTagProcessor {
/*
* This processor will write (in the body) a variable previously set by another processor.
* The idea is to test that a local variable set at the very beginning lives through until the end of the tag processing.
*/
public WriteVarAttributeTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, "writevar", true, 100000000, true);
}
@Override
protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {
final String varValue = (String) context.getVariable("var");
structureHandler.setBody((varValue == null? "" : varValue), false);
}
}
| 43.604167 | 212 | 0.697563 |
1f8ae7e0c5456bf3118956d9aa944eb62e75c806 | 1,896 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecordCustomerContactRecord;
import javax.validation.Valid;
/**
* CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecord
*/
public class CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecord {
private String customerContactRecordReference = null;
private CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecordCustomerContactRecord customerContactRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the contact record assembled during the customer contact
* @return customerContactRecordReference
**/
public String getCustomerContactRecordReference() {
return customerContactRecordReference;
}
public void setCustomerContactRecordReference(String customerContactRecordReference) {
this.customerContactRecordReference = customerContactRecordReference;
}
/**
* Get customerContactRecord
* @return customerContactRecord
**/
public CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecordCustomerContactRecord getCustomerContactRecord() {
return customerContactRecord;
}
public void setCustomerContactRecord(CRCustomerContactOperatingSessionInitiateOutputModelCustomerContactOperatingSessionInstanceRecordCustomerContactRecord customerContactRecord) {
this.customerContactRecord = customerContactRecord;
}
}
| 37.92 | 209 | 0.855485 |
d21383fe1bc22995b47699a7aa149308de771302 | 447 | //Chapter 15 - Exercise 15.3
public class Purse
{
private double total;
public Purse()
{
total = 0;
}
public void read (String input)
{
boolean done = false;
Coin c = new Coin();
if (c.read(input))
{
add(c);
}
else
{
done = true;
}
}
public void add (Coin aCoin)
{
total = total + aCoin.getValue();
}
public double getTotal()
{
return total;
}
}
| 5.258824 | 35 | 0.510067 |
9357bc8e38f9a15acc07a1f0a703b50188ac1dd4 | 9,041 | package com.diamondq.common.types;
import com.diamondq.common.TypeReference;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
public abstract class Types {
private Types() {
}
/**
* Constant for string argument.
*/
public static final TypeReference<String> STRING =
new TypeReference<String>() {
};
public static final TypeReference<@Nullable String> NULLABLE_STRING =
new TypeReference<@Nullable String>() {
};
/**
* Constant for int argument.
*/
public static final TypeReference<Integer> INT =
new TypeReference<Integer>() {
};
public static final TypeReference<@Nullable Integer> NULLABLE_INT =
new TypeReference<@Nullable Integer>() {
};
/**
* Constant for long argument.
*/
public static final TypeReference<Long> LONG =
new TypeReference<Long>() {
};
public static final TypeReference<@Nullable Long> NULLABLE_LONG =
new TypeReference<@Nullable Long>() {
};
/**
* Constant for float argument.
*/
public static final TypeReference<Float> FLOAT =
new TypeReference<Float>() {
};
public static final TypeReference<@Nullable Float> NULLABLE_FLOAT =
new TypeReference<@Nullable Float>() {
};
/**
* Constant for double argument.
*/
public static final TypeReference<Double> DOUBLE =
new TypeReference<Double>() {
};
public static final TypeReference<@Nullable Double> NULLABLE_DOUBLE =
new TypeReference<@Nullable Double>() {
};
/**
* Constant for void argument.
*/
public static final TypeReference<@Nullable Void> VOID =
new TypeReference<@Nullable Void>() {
};
/**
* Constant for byte argument.
*/
public static final TypeReference<Byte> BYTE =
new TypeReference<Byte>() {
};
public static final TypeReference<@Nullable Byte> NULLABLE_BYTE =
new TypeReference<@Nullable Byte>() {
};
/**
* Constant for boolean argument.
*/
public static final TypeReference<Boolean> BOOLEAN =
new TypeReference<Boolean>() {
};
public static final TypeReference<@Nullable Boolean> NULLABLE_BOOLEAN =
new TypeReference<@Nullable Boolean>() {
};
/**
* Constant char argument.
*/
public static final TypeReference<Character> CHAR =
new TypeReference<Character>() {
};
public static final TypeReference<@Nullable Character> NULLABLE_CHAR =
new TypeReference<@Nullable Character>() {
};
/**
* Constant short argument.
*/
public static final TypeReference<Short> SHORT =
new TypeReference<Short>() {
};
public static final TypeReference<@Nullable Short> NULLABLE_SHORT =
new TypeReference<@Nullable Short>() {
};
/**
* Default Object argument.
*/
public static final TypeReference<Object> OBJECT =
new TypeReference<Object>() {
};
public static final TypeReference<@Nullable Object> NULLABLE_OBJECT =
new TypeReference<@Nullable Object>() {
};
public static final TypeReference<Map<String, String>> MAP_OF_STRING_TO_STRING =
new TypeReference<Map<String, String>>() {
};
public static final TypeReference<@Nullable Map<String, String>> NULLABLE_MAP_OF_STRING_TO_STRING =
new TypeReference<@Nullable Map<String, String>>() {
};
public static final TypeReference<Map<String, Long>> MAP_OF_STRING_TO_LONG =
new TypeReference<Map<String, Long>>() {
};
public static final TypeReference<@Nullable Map<String, Long>> NULLABLE_MAP_OF_STRING_TO_LONG =
new TypeReference<@Nullable Map<String, Long>>() {
};
public static final TypeReference<List<String>> LIST_OF_STRING =
new TypeReference<List<String>>() {
};
public static final TypeReference<@Nullable List<String>> NULLABLE_LIST_OF_STRING =
new TypeReference<@Nullable List<String>>() {
};
public static final TypeReference<Set<String>> SET_OF_STRING =
new TypeReference<Set<String>>() {
};
public static final TypeReference<@Nullable Set<String>> NULLABLE_SET_OF_STRING =
new TypeReference<@Nullable Set<String>>() {
};
public static final TypeReference<Collection<String>> COLLECTION_OF_STRING =
new TypeReference<Collection<String>>() {
};
public static final TypeReference<@Nullable Collection<String>> NULLABLE_COLLECTION_OF_STRING =
new TypeReference<@Nullable Collection<String>>() {
};
public static final TypeReference<List<Long>> LIST_OF_LONG =
new TypeReference<List<Long>>() {
};
public static final TypeReference<@Nullable List<Long>> NULLABLE_LIST_OF_LONG =
new TypeReference<@Nullable List<Long>>() {
};
}
| 49.404372 | 104 | 0.359916 |
35529a06289539cedf13867216bc504149129dcb | 1,855 | package com.yuyh.library.utils;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.SmsManager;
import com.yuyh.library.utils.log.LogUtils;
import java.util.List;
/**
* @author yuyh.
* @date 16/4/10.
*/
public class Utils {
public static final String SCHEME_TEL = "tel:";
/**
* 拨打电话
*
* @param context
* @param phoneNumber 电话号码
*/
public static void callPhone(final Context context, final String phoneNumber) {
if (context == null) {
throw new IllegalArgumentException("context can not be null.");
}
try {
final Uri uri = Uri.parse(SCHEME_TEL + phoneNumber);
final Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(uri);
context.startActivity(intent);
} catch (Exception e) {
LogUtils.e(e);
}
}
/**
* 发送短信息
*
* @param phoneNumber 接收号码
* @param content 短信内容
*/
private void toSendSMS(Context context, String phoneNumber, String content) {
if (context == null) {
throw new IllegalArgumentException("context can not be null.");
}
PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0);
SmsManager smsManager = SmsManager.getDefault();
if (content.length() >= 70) {
//短信字数大于70,自动分条
List<String> ms = smsManager.divideMessage(content);
for (String str : ms) {
//短信发送
smsManager.sendTextMessage(phoneNumber, null, str, sentIntent, null);
}
} else {
smsManager.sendTextMessage(phoneNumber, null, content, sentIntent, null);
}
}
}
| 27.686567 | 91 | 0.595148 |
fe8e86738d3688a802a4cd6369ef8aba3980d323 | 5,439 | /*
* CWS, Cryptographic Web Share - open source Cryptographic Sharing system.
* Copyright (c) 2016-2022, haugr.net
* mailto: cws AT haugr DOT net
*
* CWS is free software; you can redistribute it and/or modify it under the
* terms of the Apache License, as published by the Apache Software Foundation.
*
* CWS 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 Apache License for more details.
*
* You should have received a copy of the Apache License, version 2, along with
* this program; If not, you can download a copy of the License
* here: https://www.apache.org/licenses/
*/
package net.haugr.cws.core.model.entities;
import net.haugr.cws.api.common.Constants;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* <p>CWS Metadata Entity, maps the Metadata table from the Database.</p>
*
* @author Kim Jensen
* @since CWS 1.0
*/
@Entity
@NamedQuery(name = "metadata.findByMemberAndExternalId",
query = "select m " +
"from MetadataEntity m," +
" TrusteeEntity t " +
"where m.circle.id = t.circle.id" +
" and t.member.id = :mid" +
" and m.externalId = :eid " +
"order by m.id desc")
@NamedQuery(name = "metadata.findByMemberAndName",
query = "select m " +
"from MetadataEntity m," +
" TrusteeEntity t " +
"where m.circle.id = t.circle.id" +
" and t.member.id = :mid" +
" and m.name = :name " +
"order by m.id desc")
@NamedQuery(name = "metadata.findByMemberAndFolder",
query = "select m " +
"from MetadataEntity m," +
" TrusteeEntity t " +
"where m.circle.id = t.circle.id" +
" and t.member = :member" +
" and m.parentId = :parentId " +
"order by m.id desc")
@NamedQuery(name = "metadata.findRootByMemberAndCircle",
query = "select m " +
"from MetadataEntity m," +
" TrusteeEntity t " +
"where m.circle.id = t.circle.id" +
" and t.member.id = :mid" +
" and m.circle.externalId = :cid" +
" and m.type.name = 'folder'" +
" and m.name = '/'" +
" and m.parentId = 0 " +
"order by m.id desc")
@NamedQuery(name = "metadata.findInFolder",
query = "select m " +
"from MetadataEntity m," +
" TrusteeEntity t " +
"where m.circle.id = t.circle.id" +
" and t.member = :member" +
" and m.parentId = :parentId" +
" and lower(m.name) = lower(:name)")
@NamedQuery(name = "metadata.findByNameAndFolder",
query = "select m " +
"from MetadataEntity m " +
"where m.id <> :id" +
" and m.name = :name" +
" and m.parentId = :parentId")
@NamedQuery(name = "metadata.countFolderContent",
query = "select count(m.id) " +
"from MetadataEntity m " +
"where m.parentId = :parentId")
@NamedQuery(name = "metadata.readInventoryRecords",
query = "select m " +
"from MetadataEntity m " +
"where m.type.name <> 'folder' " +
"order by m.id desc")
@NamedQuery(name = "metadata.countInventoryRecords",
query = "select count(m.id) " +
"from MetadataEntity m " +
"where m.type.name <> 'folder'")
@Table(name = "cws_metadata")
public class MetadataEntity extends Externable {
@Column(name = "parent_id")
private Long parentId = null;
@ManyToOne(targetEntity = CircleEntity.class, fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "circle_id", referencedColumnName = "id", nullable = false, updatable = false)
private CircleEntity circle = null;
@ManyToOne(targetEntity = DataTypeEntity.class, fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "datatype_id", referencedColumnName = "id", nullable = false, updatable = false)
private DataTypeEntity type = null;
@Column(name = "name", length = Constants.MAX_NAME_LENGTH)
private String name = null;
// =========================================================================
// Entity Setters & Getters
// =========================================================================
public void setParentId(final Long parentId) {
this.parentId = parentId;
}
public Long getParentId() {
return parentId;
}
public void setCircle(final CircleEntity circle) {
this.circle = circle;
}
public CircleEntity getCircle() {
return circle;
}
public void setType(final DataTypeEntity type) {
this.type = type;
}
public DataTypeEntity getType() {
return type;
}
public void setName(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| 36.26 | 103 | 0.560949 |
3583634ea59132aefcc5723804d74265637f13f3 | 102 | public class UserDaoImpl implements IUserDao {
public String getUserDao(){
return "coldstar";
}
}
| 17 | 46 | 0.745098 |
37d5b0fe8aa69528c5a8556e799a3e545f93eb03 | 5,377 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*
* Source file modified from the original ASF source; all changes made
* are also under Apache License.
*/
package org.tightblog.bloggerui.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.tightblog.service.UserManager;
import org.tightblog.service.WeblogManager;
import org.tightblog.domain.Weblog;
import org.tightblog.domain.WeblogBookmark;
import org.tightblog.domain.WeblogRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tightblog.dao.BlogrollLinkDao;
import org.tightblog.dao.WeblogDao;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class BlogrollController {
private static Logger log = LoggerFactory.getLogger(BlogrollController.class);
private WeblogDao weblogDao;
private BlogrollLinkDao blogrollLinkDao;
private WeblogManager weblogManager;
private UserManager userManager;
@Autowired
public BlogrollController(WeblogDao weblogDao, BlogrollLinkDao blogrollLinkDao,
WeblogManager weblogManager, UserManager userManager) {
this.weblogDao = weblogDao;
this.blogrollLinkDao = blogrollLinkDao;
this.weblogManager = weblogManager;
this.userManager = userManager;
}
@GetMapping(value = "/tb-ui/authoring/rest/weblog/{id}/bookmarks")
@PreAuthorize("@securityService.hasAccess(#p.name, T(org.tightblog.domain.Weblog), #id, 'OWNER')")
public List<WeblogBookmark> getBookmarks(@PathVariable String id, Principal p) {
return weblogDao.getOne(id).getBookmarks()
.stream()
.peek(bkmk -> bkmk.setWeblog(null))
.collect(Collectors.toList());
}
@PutMapping(value = "/tb-ui/authoring/rest/bookmarks")
@PreAuthorize("@securityService.hasAccess(#p.name, T(org.tightblog.domain.Weblog), #weblogId, 'OWNER')")
public void addBookmark(@RequestParam(name = "weblogId") String weblogId, @RequestBody WeblogBookmark newData,
Principal p) {
Weblog weblog = weblogDao.getOne(weblogId);
WeblogBookmark bookmark = new WeblogBookmark(weblog, newData.getName(),
newData.getUrl(), newData.getDescription());
weblog.addBookmark(bookmark);
weblogManager.saveWeblog(weblog, true);
}
@PutMapping(value = "/tb-ui/authoring/rest/bookmark/{id}")
@PreAuthorize("@securityService.hasAccess(#p.name, T(org.tightblog.domain.WeblogBookmark), #id, 'OWNER')")
public void updateBookmark(@PathVariable String id, @RequestBody WeblogBookmark newData, Principal p) {
WeblogBookmark bookmark = blogrollLinkDao.getOne(id);
bookmark.setName(newData.getName());
bookmark.setUrl(newData.getUrl());
bookmark.setDescription(newData.getDescription());
weblogManager.saveWeblog(bookmark.getWeblog(), true);
}
private void deleteBookmark(String id, Principal p) {
WeblogBookmark itemToRemove = blogrollLinkDao.findById(id).orElse(null);
if (itemToRemove != null) {
Weblog weblog = itemToRemove.getWeblog();
if (userManager.checkWeblogRole(p.getName(), weblog, WeblogRole.OWNER)) {
weblog.getBookmarks().remove(itemToRemove);
weblogManager.saveWeblog(weblog, true);
} else {
log.warn("Effort to delete bookmark {} by user {} failed, insufficient access rights",
itemToRemove, p.getName());
}
} else {
log.warn("Effort to delete bookmark {} by user {} failed, item could not be found",
id, p.getName());
}
}
@PostMapping(value = "/tb-ui/authoring/rest/bookmarks/delete")
public void deleteBookmarks(@RequestBody List<String> bookmarkIds, Principal p) {
if (bookmarkIds != null && bookmarkIds.size() > 0) {
for (String bookmarkId : bookmarkIds) {
deleteBookmark(bookmarkId, p);
}
}
}
}
| 43.715447 | 114 | 0.70597 |
0ef20d7f302b54573377ee2f5171e0898d1dbbdf | 198 | package org.albianj.persistence.impl.db;
import org.albianj.persistence.context.IWriterJob;
public interface IPersistenceTransactionClusterScope {
public boolean execute(IWriterJob writerJob);
}
| 24.75 | 54 | 0.843434 |
f9843a996954e5fb1e4b9e1eec6d69eb4b24ad4a | 3,187 | package com.spacetimecat.control;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Compile Java source files into class files.
*
* @author erik
*/
public class Compile_java
{
private final Log log;
private final List<File> files = new ArrayList<>();
private final List<String> classpath = new ArrayList<>();
File output_dir;
public Compile_java (Log log)
{
this.log = log;
}
/**
* You can only set this once.
*
* @param path should not be null
* @return
*/
public Compile_java output_dir (String path)
{
if (output_dir != null)
{
throw new IllegalStateException("output_dir is already set");
}
output_dir = new File(path);
return this;
}
public Compile_java add (File file)
{
this.files.add(file);
return this;
}
public Compile_java add (Collection<File> files)
{
this.files.addAll(files);
return this;
}
public Compile_java add (String... paths)
{
for (final String path : paths)
{
add(new File(path));
}
return this;
}
public Compile_java add (Files files)
{
return add(files.list());
}
/**
* Add all Java source files under 'src' directory.
*
* Set output directory to 'out'.
*
* @return
*/
public Compile_java conventional ()
{
return
add(Files.under("src").having_extension("java"))
.output_dir("out");
}
/**
* Append (do not replace) the given paths to the classpath.
*
* @param paths
* @return
*/
public Compile_java classpath (String... paths)
{
classpath.addAll(Arrays.asList(paths));
return this;
}
public Compile_java classpath (Files files)
{
for (final File f : files.list())
{
classpath.add(f.getAbsolutePath());
}
return this;
}
/**
* Compile the sources.
*
* Run the compiler with this object as the configuration.
*
* @return
* @throws IOException
* @throws InterruptedException
*/
public Compile_java run () throws IOException, InterruptedException
{
if (output_dir == null)
{
throw new IllegalStateException("must set output_dir before run");
}
output_dir.mkdirs();
final List<String> args = new ArrayList<>();
args.add("javac");
args.add("-d");
args.add(output_dir.getAbsolutePath());
if (!classpath.isEmpty())
{
args.add("-classpath");
args.add(Strings.join(":", classpath));
}
for (final File file : files)
{
args.add(file.getAbsolutePath());
}
log.info(args.toString());
final int exit_code = Os.exec(args);
if (exit_code != 0)
{
log.error("java compiler exited with code " + exit_code);
}
return this;
}
}
| 22.131944 | 78 | 0.551302 |
0dd162092fe2951f02e407ff1b2866f317fc1b84 | 8,149 | package com.google.android.gms.ads.internal;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import com.google.android.gms.common.internal.C1314c;
import com.google.android.gms.internal.C1648if;
import com.google.android.gms.internal.io;
import com.google.android.gms.internal.ip;
import com.google.android.gms.internal.ir;
import com.google.android.gms.internal.is;
import com.google.android.gms.internal.kg;
import com.google.android.gms.internal.lm;
import com.google.android.gms.internal.md;
import com.google.android.gms.internal.nb;
import com.google.android.gms.internal.op;
import com.google.android.gms.internal.qw;
import com.google.android.gms.internal.rc;
import com.google.android.gms.internal.rc.C1938a;
import com.google.android.gms.internal.rq;
import com.google.android.gms.internal.sg;
import com.google.android.gms.internal.sx;
import com.google.android.gms.internal.zzec;
import com.google.android.gms.internal.zzqa;
import java.util.Map;
@op
public abstract class zzc extends zzb implements zzh, nb {
/* renamed from: com.google.android.gms.ads.internal.zzc.1 */
class C11601 implements kg {
final /* synthetic */ zzc f2564a;
C11601(zzc com_google_android_gms_ads_internal_zzc) {
this.f2564a = com_google_android_gms_ads_internal_zzc;
}
public void m4049a(sx sxVar, Map<String, String> map) {
if (this.f2564a.f.zzvk != null) {
this.f2564a.h.m6053a(this.f2564a.f.zzvj, this.f2564a.f.zzvk, sxVar.m8760b(), (lm) sxVar);
} else {
sg.m8449e("Request to enable ActiveView before adState is available.");
}
}
}
/* renamed from: com.google.android.gms.ads.internal.zzc.2 */
class C11612 implements Runnable {
final /* synthetic */ C1938a f2565a;
final /* synthetic */ zzc f2566b;
C11612(zzc com_google_android_gms_ads_internal_zzc, C1938a c1938a) {
this.f2566b = com_google_android_gms_ads_internal_zzc;
this.f2565a = c1938a;
}
public void run() {
this.f2566b.zzb(new rc(this.f2565a, null, null, null, null, null, null, null));
}
}
/* renamed from: com.google.android.gms.ads.internal.zzc.3 */
class C11643 implements Runnable {
final /* synthetic */ C1938a f2569a;
final /* synthetic */ qw f2570b;
final /* synthetic */ io f2571c;
final /* synthetic */ zzc f2572d;
/* renamed from: com.google.android.gms.ads.internal.zzc.3.1 */
class C11621 implements OnTouchListener {
final /* synthetic */ zze f2567a;
C11621(C11643 c11643, zze com_google_android_gms_ads_internal_zze) {
this.f2567a = com_google_android_gms_ads_internal_zze;
}
public boolean onTouch(View view, MotionEvent motionEvent) {
this.f2567a.recordClick();
return false;
}
}
/* renamed from: com.google.android.gms.ads.internal.zzc.3.2 */
class C11632 implements OnClickListener {
final /* synthetic */ zze f2568a;
C11632(C11643 c11643, zze com_google_android_gms_ads_internal_zze) {
this.f2568a = com_google_android_gms_ads_internal_zze;
}
public void onClick(View view) {
this.f2568a.recordClick();
}
}
C11643(zzc com_google_android_gms_ads_internal_zzc, C1938a c1938a, qw qwVar, io ioVar) {
this.f2572d = com_google_android_gms_ads_internal_zzc;
this.f2569a = c1938a;
this.f2570b = qwVar;
this.f2571c = ioVar;
}
public void run() {
if (this.f2569a.f5595b.f6600s && this.f2572d.f.f2740p != null) {
String str = null;
if (this.f2569a.f5595b.f6583b != null) {
str = zzv.zzcJ().m8501a(this.f2569a.f5595b.f6583b);
}
ir ipVar = new ip(this.f2572d, str, this.f2569a.f5595b.f6584c);
this.f2572d.f.zzvF = 1;
try {
this.f2572d.d = false;
this.f2572d.f.f2740p.m6767a(ipVar);
return;
} catch (Throwable e) {
sg.m8447c("Could not call the onCustomRenderedAdLoadedListener.", e);
this.f2572d.d = true;
}
}
zze com_google_android_gms_ads_internal_zze = new zze(this.f2572d.f.zzqr, this.f2569a);
sx a = this.f2572d.m4050a(this.f2569a, com_google_android_gms_ads_internal_zze, this.f2570b);
a.setOnTouchListener(new C11621(this, com_google_android_gms_ads_internal_zze));
a.setOnClickListener(new C11632(this, com_google_android_gms_ads_internal_zze));
this.f2572d.f.zzvF = 0;
this.f2572d.f.zzvi = zzv.zzcI().m7817a(this.f2572d.f.zzqr, this.f2572d, this.f2569a, this.f2572d.f.f2726b, a, this.f2572d.j, this.f2572d, this.f2571c);
}
}
public zzc(Context context, zzec com_google_android_gms_internal_zzec, String str, md mdVar, zzqa com_google_android_gms_internal_zzqa, zzd com_google_android_gms_ads_internal_zzd) {
super(context, com_google_android_gms_internal_zzec, str, mdVar, com_google_android_gms_internal_zzqa, com_google_android_gms_ads_internal_zzd);
}
protected sx m4050a(C1938a c1938a, zze com_google_android_gms_ads_internal_zze, qw qwVar) {
sx sxVar = null;
View nextView = this.f.f2727c.getNextView();
if (nextView instanceof sx) {
sxVar = (sx) nextView;
if (((Boolean) C1648if.ax.m6682c()).booleanValue()) {
sg.m8444b("Reusing webview...");
sxVar.m8750a(this.f.zzqr, this.f.zzvj, this.a);
} else {
sxVar.destroy();
sxVar = null;
}
}
if (sxVar == null) {
if (nextView != null) {
this.f.f2727c.removeView(nextView);
}
sxVar = zzv.zzcK().m8831a(this.f.zzqr, this.f.zzvj, false, false, this.f.f2726b, this.f.zzvf, this.a, this, this.i);
if (this.f.zzvj.f6458h == null) {
m4033a(sxVar.m8760b());
}
}
sx sxVar2 = sxVar;
sxVar2.m8776l().m8804a(this, this, this, this, false, this, null, com_google_android_gms_ads_internal_zze, this, qwVar);
m4051a(sxVar2);
sxVar2.m8763b(c1938a.f5594a.f6562w);
return sxVar2;
}
protected void m4051a(lm lmVar) {
lmVar.m7287a("/trackActiveViewUnit", new C11601(this));
}
public void zza(int i, int i2, int i3, int i4) {
m4039c();
}
public void zza(is isVar) {
C1314c.m4631b("setOnCustomRenderedAdLoadedListener must be called on the main UI thread.");
this.f.f2740p = isVar;
}
protected void zza(C1938a c1938a, io ioVar) {
if (c1938a.f5598e != -2) {
rq.f5755a.post(new C11612(this, c1938a));
return;
}
if (c1938a.f5597d != null) {
this.f.zzvj = c1938a.f5597d;
}
if (!c1938a.f5595b.f6589h || c1938a.f5595b.f6567B) {
rq.f5755a.post(new C11643(this, c1938a, null, ioVar));
return;
}
this.f.zzvF = 0;
this.f.zzvi = zzv.zzcI().m7817a(this.f.zzqr, this, c1938a, this.f.f2726b, null, this.j, this, ioVar);
}
protected boolean zza(rc rcVar, rc rcVar2) {
if (this.f.zzdm() && this.f.f2727c != null) {
this.f.f2727c.zzds().m8624b(rcVar2.f5604C);
}
return super.zza(rcVar, rcVar2);
}
public void zzbX() {
onAdClicked();
}
public void zzbY() {
recordImpression();
zzbF();
}
public void zzbZ() {
m4031a();
}
public void zzc(View view) {
this.f.f2744t = view;
zzb(new rc(this.f.zzvl, null, null, null, null, null, null, null));
}
}
| 37.380734 | 186 | 0.610627 |
6bc5d3cee6f0a3cec03445f8acc8a2bfaa4c60e5 | 2,327 | package gov.va.med.lom.avs.dao.hibernate;
import gov.va.med.lom.avs.dao.EncounterCacheDao;
import gov.va.med.lom.avs.model.EncounterCache;
import gov.va.med.lom.reports.dao.hibernate.BaseQueryDaoJpa;
import java.util.Date;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.Query;
/**
* Encounter Cache DAO Implementation
*/
@Stateless(name="gov.va.med.lom.avs.dao.EncounterCacheDao")
@Local(EncounterCacheDao.class)
public class EncounterCacheDaoImpl extends BaseQueryDaoJpa<EncounterCache, Long> implements EncounterCacheDao {
static {
addQueryFilter(EncounterCacheDaoImpl.class, "avsDateRanges", "sra.termCalendar.termCalendarId", "or");
addQueryFilter(EncounterCacheDaoImpl.class, "department", "sra.department", "or");
addQueryFilter(EncounterCacheDaoImpl.class, "courseId", "sra.courseId", "or");
}
/**
* Looks up encounter cache by facility, patient, location, and encounter date/time
*
* @param facilityNo The facility's unique identifier
* @param patientDfn The patient's unique identifier
* @param locationIen The location's unique identifier
* @param datetime The encounter date/time in FM format
* @return Clinic preferences object
*/
public EncounterCache find(String facilityNo, String patientDfn, String locationIen, double datetime){
Query query = super.entityManager.createNamedQuery(QUERY_FIND_CACHE);
query.setParameter("facilityNo", facilityNo);
query.setParameter("patientDfn", patientDfn);
query.setParameter("locationIen", locationIen);
query.setParameter("datetime", datetime);
query.setMaxResults(1);
@SuppressWarnings("unchecked")
List<EncounterCache> list = query.getResultList();
if (list == null || list.size() == 0) {
return null;
}
return list.get(0);
}
@SuppressWarnings("unchecked")
public List<EncounterCache> findByDates(String facilityNo, Date startDate, Date endDate) {
Query query = super.entityManager.createNamedQuery(QUERY_FIND_CACHE_BY_DATES);
query.setParameter("facilityNo", facilityNo);
query.setParameter("startDate", startDate);
query.setParameter("endDate", endDate);
return query.getResultList();
}
}
| 32.774648 | 112 | 0.718092 |
dc259283ab9e701eecbcaad75171f9597b0fc07e | 8,050 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.impl.sql.catalog;
import java.sql.Types;
import com.pivotal.gemfirexd.internal.catalog.UUID;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.services.uuid.UUIDFactory;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.CatalogRowFactory;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.DataDictionary;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.GfxdDiskStoreDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.SystemColumn;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.TupleDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecutionFactory;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueFactory;
import com.pivotal.gemfirexd.internal.iapi.types.SQLChar;
import com.pivotal.gemfirexd.internal.iapi.types.SQLInteger;
import com.pivotal.gemfirexd.internal.iapi.types.SQLLongint;
import com.pivotal.gemfirexd.internal.iapi.types.SQLVarchar;
/**
*
* @author Asif
*
*/
public class GfxdSYSDISKSTORESRowFactory extends CatalogRowFactory
{
public static final String TABLENAME_STRING = "SYSDISKSTORES";
public static final int SYSDISKSTORES_COLUMN_COUNT = 9;
public static final int SYSDISKSTORES_NAME = 1;
public static final int SYSDISKSTORES_MAXLOGSIZE = 2;
public static final int SYSDISKSTORES_AUTOCOMPACT = 3;
public static final int SYSDISKSTORES_ALLOWFORCECOMPACTION = 4;
public static final int SYSDISKSTORES_COMPACTIONTHRESHOLD = 5;
public static final int SYSDISKSTORES_TIMEINTERVAL = 6;
public static final int SYSDISKSTORES_WRITEBUFFERSIZE = 7;
public static final int SYSDISKSTORES_QUEUESIZE = 8;
public static final int SYSDISKSTORES_DIR_PATH_SIZE = 9;
private static final int[][] indexColumnPositions = { { SYSDISKSTORES_NAME } };
// if you add a non-unique index allocate this array.
private static final boolean[] uniqueness = null;
private static final String[] uuids = {
"a073400e-00b6-fdfc-71ce-000b0a763800" // catalog UUID
, "a073400e-00b6-fbba-75d4-000b0a763800" // heap UUID
, "a073400e-00b6-00b9-bbde-000b0a763800" // SYSDISKSTORES_INDEX1
};
// ///////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTORS
//
// ///////////////////////////////////////////////////////////////////////////
GfxdSYSDISKSTORESRowFactory(UUIDFactory uuidf, ExecutionFactory ef,
DataValueFactory dvf) {
super(uuidf, ef, dvf);
initInfo(SYSDISKSTORES_COLUMN_COUNT, TABLENAME_STRING,
indexColumnPositions, uniqueness, uuids);
}
public ExecRow makeRow(TupleDescriptor td, TupleDescriptor parent)
throws StandardException
{
ExecRow row;
UUID uuid = null;
String diskStoreName = null;
long maxLogSize = -1;
String autoCompact = null;
String allowForceCompaction = null;
int compactionThreshold = -1;
long timeInterval = -1;
int writeBufferSize = -1;
int queueSize = -1;
String dirPathSize = null;
if (td != null) {
GfxdDiskStoreDescriptor dsd = (GfxdDiskStoreDescriptor)td;
diskStoreName = dsd.getDiskStoreName();
uuid = dsd.getUUID();
maxLogSize = dsd.getMaxLogSize();
autoCompact = dsd.getAutocompact();
allowForceCompaction = dsd.getAllowForceCompaction();
compactionThreshold = dsd.getCompactionThreshold();
timeInterval = dsd.getTimeInterval();
writeBufferSize = dsd.getWriteBufferSize();
queueSize = dsd.getQueueSize();
dirPathSize = dsd.getDirPathAndSize();
}
/* Build the row to insert */
row = getExecutionFactory().getValueRow(SYSDISKSTORES_COLUMN_COUNT);
/* 1st column is diskstorename */
row.setColumn(1, new SQLChar(diskStoreName));
/* 2nd column is logsize */
row.setColumn(2, new SQLLongint(maxLogSize));
/* 3rd column is autocompact */
row.setColumn(3, new SQLVarchar(autoCompact));
/* 4th column is allowforcecompaction */
row.setColumn(4, new SQLVarchar(allowForceCompaction));
/* 5th column is compactionthreshold */
row.setColumn(5, new SQLInteger(compactionThreshold));
/* 6th column is TimeInterval */
row.setColumn(6, new SQLLongint(timeInterval));
/* 7th column is writeBufferSize */
row.setColumn(7, new SQLInteger(writeBufferSize));
/* 8th column is QueueSize */
row.setColumn(8, new SQLInteger(queueSize));
/* 9th column is Dircetion paths and sizes */
row.setColumn(9, new SQLVarchar(dirPathSize));
return row;
}
public TupleDescriptor buildDescriptor(ExecRow row,
TupleDescriptor parentDesc, DataDictionary dd) throws StandardException
{
if (SanityManager.DEBUG) {
SanityManager.ASSERT(row.nColumns() == SYSDISKSTORES_COLUMN_COUNT,
"Wrong number of columns for a SYSDISKSTORES row");
}
DataValueDescriptor col;
UUID id;
UUIDFactory uuidFactory = getUUIDFactory();
col = row.getColumn(SYSDISKSTORES_NAME);
String diskStoreName = col.getString();
id = getUUIDFactory().recreateUUID(diskStoreName);
col = row.getColumn(SYSDISKSTORES_MAXLOGSIZE);
int maxLogSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_AUTOCOMPACT);
String autoCompact = col.getString();
col = row.getColumn(SYSDISKSTORES_ALLOWFORCECOMPACTION);
String allowForceCompact = col.getString();
col = row.getColumn(SYSDISKSTORES_COMPACTIONTHRESHOLD);
int comapctionThreshold = col.getInt();
col = row.getColumn(SYSDISKSTORES_TIMEINTERVAL);
int timeInterval = col.getInt();
col = row.getColumn(SYSDISKSTORES_WRITEBUFFERSIZE);
int writeBufferSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_QUEUESIZE);
int queueSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_DIR_PATH_SIZE);
String dirPathAndSize = col.getString();
return new GfxdDiskStoreDescriptor(dd, id, diskStoreName, maxLogSize,
autoCompact, allowForceCompact, comapctionThreshold, timeInterval,
writeBufferSize, queueSize, dirPathAndSize);
}
/**
* Builds a list of columns suitable for creating this Catalog.
*
*
* @return array of SystemColumn suitable for making this catalog.
*/
public SystemColumn[] buildColumnList()
{
return new SystemColumn[] {
SystemColumnImpl.getIdentifierColumn("NAME", false),
// SystemColumnImpl.getIndicatorColumn("LOCKGRANULARITY"),
// SystemColumnImpl.getIdentifierColumn("SERVERGROUPS", false),
SystemColumnImpl.getColumn("MAXLOGSIZE", Types.BIGINT, false),
SystemColumnImpl.getColumn("AUTOCOMPACT", Types.VARCHAR, false,6),
SystemColumnImpl.getColumn("ALLOWFORCECOMPACTION", Types.VARCHAR, false,6),
SystemColumnImpl.getColumn("COMPACTIONTHRESHOLD", Types.INTEGER, false,3),
SystemColumnImpl.getColumn("TIMEINTERVAL", Types.BIGINT, false),
SystemColumnImpl.getColumn("WRITEBUFFERSIZE", Types.INTEGER, false),
SystemColumnImpl.getColumn("QUEUESIZE", Types.INTEGER, false),
SystemColumnImpl.getColumn("DIR_PATH_SIZE", Types.VARCHAR, false)};
}
}
| 35.619469 | 83 | 0.72472 |
a9144b468e00281f48ba6555c44c224df44abc78 | 18,981 | /*
* Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved.
*
* The Sun Project JXTA(TM) Software License
*
* 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 Sun Microsystems, Inc. for JXTA(TM) technology."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please contact
* Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA", nor may
* "JXTA" appear in their name, without prior written permission of Sun.
*
* 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 SUN
* MICROSYSTEMS 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.
*
* JXTA is a registered trademark of Sun Microsystems, Inc. in the United
* States and other countries.
*
* Please see the license information page at :
* <http://www.jxta.org/project/www/license.html> for instructions on use of
* the license in source files.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of Project JXTA. For more information on Project JXTA, please see
* http://www.jxta.org.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.impl.endpoint.msgframing;
import net.jxta.document.MimeMediaType;
import net.jxta.logging.Logger;
import net.jxta.logging.Logging;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Header Package for Messages. Analogous to HTTP Headers.
*/
public class MessagePackageHeader {
private final static transient Logger LOG = Logging.getLogger(MessagePackageHeader.class.getName());
/**
* Standard header name for content-length
*/
private final static String CONTENT_LENGTH = "content-length";
/**
* Standard header name for content-type
*/
private final static String CONTENT_TYPE = "content-type";
/**
* The maximum size of Header data buffers we will emit.
*/
private final static int MAX_HEADER_LEN = 1024;
/**
* Used for storing individual header elements.
*/
public static class Header {
final String name;
final byte[] value;
public Header(String name, byte[] value) {
this.name = name;
assert value.length <= 65535;
this.value = value;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return MessageFormat.format("{0} := {1}", name, value);
}
public String getName() {
return name;
}
public byte[] getValue() {
return value;
}
public String getValueString() {
try {
return new String(value, "UTF-8");
} catch (UnsupportedEncodingException never) {
// utf-8 is a required encoding.
throw new Error("UTF-8 encoding support missing!");
}
}
}
/**
* The individual header elements in the order they were read.
*/
private final List<Header> headers = new ArrayList<Header>();
/**
* Creates a new instance of MessagePackageHeader. Used for outgoing messages.
*/
public MessagePackageHeader() {}
/**
* Creates a new instance of MessagePackageHeader. Used for incoming messages.
*
* @param in The stream from which the headers will be read.
* @throws java.io.IOException if an io error occurs.
*/
public MessagePackageHeader(InputStream in) throws IOException {
boolean sawEmpty = false;
boolean sawLength = false;
boolean sawType = false;
DataInput di = new DataInputStream(in);
// todo 20021014 [email protected] A framing signature would help here.
do {
byte headerNameLength = di.readByte();
if (0 == headerNameLength) {
sawEmpty = true;
} else {
byte[] headerNameBytes = new byte[headerNameLength];
di.readFully(headerNameBytes);
String headerNameString = new String(headerNameBytes, "UTF-8");
if (headerNameString.equalsIgnoreCase(CONTENT_LENGTH)) {
if (sawLength) {
throw new IOException("Duplicate content-length header");
}
sawLength = true;
}
if (headerNameString.equalsIgnoreCase(CONTENT_TYPE)) {
if (sawType) {
throw new IOException("Duplicate content-type header");
}
sawType = true;
}
int headerValueLength = di.readUnsignedShort();
byte[] headerValueBytes = new byte[headerValueLength];
di.readFully(headerValueBytes);
headers.add(new Header(headerNameString, headerValueBytes));
}
} while (!sawEmpty);
if (!sawLength) {
Logging.logCheckedWarning(LOG, "Content Length header was missing");
throw new IOException("Content Length header was missing");
}
if (!sawType) {
Logging.logCheckedWarning(LOG, "Content Type header was missing");
throw new IOException("Content Type header was missing");
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append('[');
Iterator<Header> eachHeader = getHeaders();
while (eachHeader.hasNext()) {
Header aHeader = eachHeader.next();
result.append(" {");
result.append(aHeader);
result.append('}');
if (eachHeader.hasNext()) {
result.append(',');
}
}
result.append(']');
return result.toString();
}
/**
* Returns number of header elements otherwise -1
*
* @param buffer the byte buffer
* @return number of header elements
*/
private int getHeaderCount(ByteBuffer buffer) {
int pos = buffer.position();
int limit = buffer.limit();
int headerCount = 0;
boolean sawZero = false;
while (pos < limit) {
// get header name length
int len = buffer.get(pos) & 0xFF;
pos += 1;
if (0 == len) {
sawZero = true;
break;
}
// advance past name
pos += len;
if ((pos + 2) >= limit) {
// not enough data
break;
}
// get value length
len = buffer.getShort(pos) & 0xFFFF;
pos += 2;
// advance past value
pos += len;
headerCount++;
}
return sawZero ? headerCount : -1;
}
/**
* Reads a Header from a ByteBuffer
*
* @param buffer the input buffer
* @return {@code true} If the header block was completely read.
* @throws IOException if an io error is encountered
*/
public boolean readHeader(ByteBuffer buffer) throws IOException {
Logging.logCheckedDebug(LOG, MessageFormat.format("Parsing Package Header from byte buffer :{0}", buffer.toString()));
int count = getHeaderCount(buffer);
if (count < 0) {
return false;
}
for (int i = 1; i <= count; i++) {
byte headerNameLength = buffer.get();
byte[] headerNameBytes = new byte[headerNameLength];
buffer.get(headerNameBytes);
String headerNameString = new String(headerNameBytes, "UTF-8");
int headerValueLength = buffer.getShort() & 0x0FFFF; // unsigned
byte[] headerValueBytes = new byte[headerValueLength];
buffer.get(headerValueBytes);
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, MessageFormat.format("Adding Name {0}: {1}", headerNameString, headerValueBytes));
headers.add(new Header(headerNameString, headerValueBytes));
}
// get the end-of-pkg
buffer.get();
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, MessageFormat.format("Parsed {0} header elements, buffer stats :{1}", count, buffer.toString()));
return true;
}
/**
* Add a header.
*
* @param name The header name. The UTF-8 encoded representation of this
* name may not be longer than 255 bytes.
* @param value The value for the header. May not exceed 65535 bytes in
* length.
*/
public void addHeader(String name, byte[] value) {
if (name.length() > 255) {
throw new IllegalArgumentException("name may not exceed 255 bytes in length.");
}
if (value.length > 65535) {
throw new IllegalArgumentException("value may not exceed 65535 bytes in length.");
}
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, "Add header :", name, "(", name.length(), ") with ", value.length, " bytes of value");
headers.add(new Header(name, value));
}
/**
* Add a header.
*
* @param name The header name. The UTF-8 encoded representation of this
* name may not be longer than 255 bytes.
* @param value The value for the header. May not exceed 65535 bytes in
* length.
*/
public void addHeader(String name, String value) {
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, "Add header :", name, "(", name.length(), ") with ", value.length(), " chars of value");
try {
addHeader(name, value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException never) {
// utf-8 is a required encoding.
throw new IllegalStateException("UTF-8 encoding support missing!");
}
}
/**
* Replace a header. Replaces all existing headers with the same name.
*
* @param name The header name. The UTF-8 encoded representation of this
* name may not be longer than 255 bytes.
* @param value The value for the header. May not exceed 65535 bytes in
* length.
*/
public void replaceHeader(String name, byte[] value) {
if (name.length() > 255) {
throw new IllegalArgumentException("name may not exceed 255 bytes in length.");
}
if (value.length > 65535) {
throw new IllegalArgumentException("value may not exceed 65535 bytes in length.");
}
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, "Replace header :", name, "(", name.length(), ") with ", value.length, " bytes of value");
Header newHeader = new Header(name, value);
ListIterator<Header> eachHeader = getHeaders();
boolean replaced = false;
while (eachHeader.hasNext()) {
Header aHeader = eachHeader.next();
if (aHeader.getName().equalsIgnoreCase(name)) {
eachHeader.set(newHeader);
replaced = true;
}
}
if(!replaced) {
headers.add(newHeader);
}
}
/**
* Replace a header. Replaces all existing headers with the same name
*
* @param name The header name. The UTF-8 encoded representation of this
* name may not be longer than 255 bytes.
* @param value The value for the header. May not exceed 65535 bytes in
* length.
*/
public void replaceHeader(String name, String value) {
// LOGGING: was Finer
Logging.logCheckedDebug(LOG, "Replace header :", name, "(", name.length(), ") with ", value.length(), " chars of value");
try {
replaceHeader(name, value.getBytes("UTF-8"));
} catch (UnsupportedEncodingException never) {
// utf-8 is a required encoding.
throw new IllegalStateException("UTF-8 encoding support missing!");
}
}
/**
* Gets all of the headers. This iterator provides access to the live
* data of this instance. Modifying the headers using {@code add()},
* {@code set()}, {@code remove()} is permitted.
*
* @return all of the headers
*/
public ListIterator<Header> getHeaders() {
return headers.listIterator();
}
/**
* Gets all of the headers matching the specified name
*
* @param name the name of the header we are seeking.
*/
public Iterator<Header> getHeader(String name) {
List<Header> matchingHeaders = new ArrayList<Header>();
for (Header aHeader : headers) {
if (name.equals(aHeader.getName())) {
matchingHeaders.add(aHeader);
}
}
return matchingHeaders.iterator();
}
/**
* Write this group of header elements to a stream.
*
* @param out the stream to send the headers to.
* @throws java.io.IOException if an io error occurs
*/
public void sendToStream(OutputStream out) throws IOException {
Iterator<Header> eachHeader = getHeaders();
DataOutput dos = new DataOutputStream(out);
// todo 20021014 [email protected] A framing signature would help here
while (eachHeader.hasNext()) {
Header aHeader = eachHeader.next();
byte[] nameBytes = aHeader.getName().getBytes("UTF-8");
byte[] value = aHeader.getValue();
assert nameBytes.length <= 255;
assert value.length <= 65535;
dos.write(nameBytes.length);
dos.write(nameBytes);
dos.writeShort(value.length);
dos.write(value);
}
// write empty header
dos.write(0);
}
/**
* Return a ByteBuffer representing this group of header elements.
*
* @return ByteBuffer representing this Header
*/
public ByteBuffer getByteBuffer() {
// note: according to the spec this may exceed MAX_HEADER_LEN,
// but since there are practically only 3 header elements used
// it's safe to assume this implemention detail.
ByteBuffer buffer = ByteBuffer.allocate(MAX_HEADER_LEN);
for (Header header : headers) {
byte[] name;
try {
name = header.getName().getBytes("UTF-8");
} catch (UnsupportedEncodingException never) {
throw new Error("Required UTF-8 encoding not available.");
}
byte[] value = header.getValue();
assert name.length <= 255;
assert value.length <= 65535;
buffer.put((byte) name.length);
buffer.put(name);
buffer.putShort((short) value.length);
buffer.put(value);
}
// write empty header
buffer.put((byte) 0);
buffer.flip();
return buffer;
}
/**
* Convenience method setting the "{@code content-length}" header.
*
* @param length length of the message.
*/
public void setContentLengthHeader(long length) {
byte[] lengthAsBytes = new byte[8];
for (int eachByte = 0; eachByte < 8; eachByte++) {
lengthAsBytes[eachByte] = (byte) (length >> ((7 - eachByte) * 8L));
}
replaceHeader(CONTENT_LENGTH, lengthAsBytes);
}
/**
* Convenience method for getting the "{@code content-length}" header.
*
* @return length from the header or -1 if there was no
* {@code content-length} header element.
*/
public long getContentLengthHeader() {
Iterator<Header> it = getHeader(CONTENT_LENGTH);
if (!it.hasNext()) {
return -1L;
}
Header header = it.next();
byte[] lengthAsBytes = header.getValue();
long lengthAsLong = 0L;
for (int eachByte = 0; eachByte < 8; eachByte++) {
lengthAsLong |= ((long) (lengthAsBytes[eachByte] & 0xff)) << ((7 - eachByte) * 8L);
}
return lengthAsLong;
}
/**
* Convenience method for setting the "{@code content-type}" header.
*
* @param type type of the message.
*/
public void setContentTypeHeader(MimeMediaType type) {
replaceHeader(CONTENT_TYPE, type.toString());
}
/**
* Convenience method for getting the "{@code content-type}" header.
*
* @return type from the header or "{@code application/octet-stream}" if
* there was no {@code content-type} header.
*/
public MimeMediaType getContentTypeHeader() {
Iterator<Header> it = getHeader(CONTENT_TYPE);
if (!it.hasNext()) {
// return the generic type. Better than returning "null".
return MimeMediaType.AOS;
}
Header header = it.next();
return MimeMediaType.valueOf(header.getValueString());
}
}
| 31.79397 | 134 | 0.597018 |
f47ee09237e669edc9400beaeb3d93b8b708fc7a | 2,835 | package ru.job4j.tracker;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class TrackerTest {
@Test
public void whenAddNewItemThenTrackerHasSameItem() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "testDescription", 123L);
tracker.add(item);
List<Item> expect = new ArrayList<>();
expect.add(item);
assertThat(tracker.getAll(), is(expect));
}
@Test
public void whenReplaceNameThenReturnNewName() {
Tracker tracker = new Tracker();
Item previous = new Item("test1", "testDescription", 123L);
tracker.add(previous);
Item next = new Item("test2", "testDescription2", 1234L);
next.setId(previous.getId());
next.setId(previous.getId());
tracker.replace(next);
assertThat(tracker.findById(previous.getId()).getName(), is("test2"));
}
@Test
public void whenFindidThenReturnId() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "testdesc", 123L);
tracker.add(item);
assertThat((tracker.findById(item.getId()).getName()), is("test1"));
}
@Test
public void whenDeleteItemThenReturnNewArrayWithoutItem() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "desc1", 123L);
tracker.add(item);
Item next = new Item("test2", "testDescription2", 1234L);
tracker.add(next);
Item next2 = new Item("test22", "testDescription22", 12342L);
tracker.add(next2);
tracker.delete(next.getId());
List<Item> expectList = Arrays.asList(item, next2);
assertThat(tracker.getAll(), is(expectList));
}
@Test
public void whenFindByNameWhenReturnByName() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "desc1", 123L);
tracker.add(item);
Item next = new Item("test1", "desc41", 1243L);
tracker.add(next);
Item previuos = new Item("test12", "desc1", 123L);
tracker.add(previuos);
List<Item> expectList = Arrays.asList(item, next);
assertThat(tracker.findByName(item.getName()), is(expectList));
}
@Test
public void whenFindAllWhenReturnAllItemsWithoutNull() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "desc1", 123L);
tracker.add(item);
Item next = new Item("test1", "desc1", 123L);
tracker.add(next);
Item third = new Item("test1", "desc1", 123L);
tracker.add(third);
List<Item> expectList = Arrays.asList(item, next, third);
assertThat(tracker.getAll().toString(), is(expectList.toString()));
}
}
| 36.346154 | 78 | 0.620811 |
abef776d7a03f26e2f610649e0cfd99f783851d7 | 642 | package frc.team2767.deepspace.command.elevator;
import edu.wpi.first.wpilibj.command.InstantCommand;
import frc.team2767.deepspace.Robot;
import frc.team2767.deepspace.subsystem.ElevatorSubsystem;
public class ElevatorSetPositionCommand extends InstantCommand {
private static final ElevatorSubsystem ELEVATOR = Robot.ELEVATOR;
private final double height;
public ElevatorSetPositionCommand(double height) {
this.height = height;
requires(ELEVATOR);
}
@Override
protected void initialize() {
ELEVATOR.setPosition(height);
}
@Override
protected boolean isFinished() {
return ELEVATOR.onTarget();
}
}
| 23.777778 | 67 | 0.772586 |
a48e52c2daf10ee3d0e280d6964e8ef172288d07 | 622 | package nc_io_test;
import java.util.Scanner;
/**
* @author: afuya
* @program: BiShiLianXi
* @date: 2021/8/25 2:27 下午
*/
public class T_05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
int n = Integer.parseInt(str1);
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
String s[] = str.split(" ");
int sum = 0;
for (int j = 1; j < s.length; j++) {
sum += Integer.parseInt(s[j]);
}
System.out.println(sum);
}
}
} | 24.88 | 48 | 0.491961 |
6673e71c39c536654790154c56713a2e06f7307a | 1,431 | package com.govnomarket.market.service;
import com.govnomarket.market.dto.OrderDTO;
import com.govnomarket.market.repository.IOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
public class OrderService implements IOrderService{
@Autowired
private IOrderRepository repository;
@Override
public OrderDTO save(OrderDTO orderDto) {
return OrderDTO.orderToOrderDto(repository.save(OrderDTO.orderDtoToOrder(orderDto)));
}
@Override
public void deleteById(Long orderId){
repository.deleteById(orderId);
}
@Override
public List<OrderDTO> findAll() {
return OrderDTO.orderListToOrderDtoList(repository.findAll());
}
@Override
public OrderDTO getOne(Long orderId) {
return OrderDTO.orderToOrderDto(repository.getOne(orderId));
}
@Override
public List<OrderDTO> findAllByAddressId(Long addressId) {
return OrderDTO.orderListToOrderDtoList(repository.findAllByAddressId(addressId));
}
@Override
public List<OrderDTO> findAllByCreateDatetime(Date createDatetime) {
return OrderDTO.orderListToOrderDtoList(repository.findAllByCreateDatetime(createDatetime));
}
@Override
public List<OrderDTO> findAllByStatus(String status) {
return OrderDTO.orderListToOrderDtoList(repository.findAllByStatus(status));
}
}
| 29.204082 | 101 | 0.744235 |
e8296a909ed316ebde88a114938b20d392229e2d | 692 | package org.saltframework.core.properties;
import java.util.*;
/**
* @author Seok Kyun. Choi. 최석균 (Syaku)
* @site http://syaku.tistory.com
* @since 2016. 11. 15.
*/
public final class ApplicationProperties {
private Map<String, List<Properties>> context = new LinkedHashMap<>();
protected void addProperties(ApplicationType applicationType, List<Properties> properties) {
this.context.put(applicationType.name(), properties);
}
public List<Properties> getProperties(ApplicationType applicationType) {
if (context.isEmpty() || !context.containsKey(applicationType.name())) {
return Collections.EMPTY_LIST;
} else {
return context.get(applicationType.name());
}
}
}
| 26.615385 | 93 | 0.734104 |
ba970a233f272ec9c6d9fbac186b942fce31063d | 2,560 | package com.crest.backend.util;
import com.crest.backend.constants.Service;
import com.crest.backend.constants.TimeBucket;
import com.crest.backend.constants.TripMonth;
import java.io.File;
import java.io.FileWriter;
public class DataWriter {
private final String arff_55_NORTH_ON_COUNT = "Bus55NorthCountOn_Random_Forest_tree.arff";
private final String arff_60_NORTH_ON_COUNT = "Bus60NorthCountOn_Random_Forest_tree.arff";
private final String arff_181_NORTH_ON_COUNT = "Bus181NorthCountOn_Random_Forest_tree.arff";
private final String arff_55_NORTH_OFF_COUNT = "Bus55NorthCountOff_Random_Forest_tree.arff";
private final String arff_60_NORTH_OFF_COUNT = "Bus60NorthCountOff_Random_Forest_tree.arff";
private final String arff_181_NORTH_OFF_COUNT = "Bus181NorthCountOff_Random_Forest_tree.arff";
private String arffFileLocation;
public DataWriter(String arffFileLocation) {
this.arffFileLocation = arffFileLocation;
}
public boolean writeDataToArffFile(TripMonth tripMonth, Service service, TimeBucket timeBucket, String stopName, String busNumber) {
try {
String timeBucketValue = timeBucket == TimeBucket.EARLY_MORNING ? "\'" + TimeBucket.EARLY_MORNING.getDisplayValue() + "\'" : timeBucket.getDisplayValue();
String data = "\n" + tripMonth.getMonthSequence() + "," + service.getValue() + "," +
timeBucketValue + "," + "0" + "," + "\'" + stopName + "\'";
File file = new File(getArffFileToLoad(busNumber));
//if file doesnt exists, then create it
if (!file.exists()) {
System.out.println("Creating a file..");
file.createNewFile();
}
//true = append file
FileWriter fileWriter = new FileWriter(file, true);
fileWriter.write(data);
fileWriter.flush();
fileWriter.close();
System.out.println("Done");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
}
private String getArffFileToLoad(String busNumber) {
switch (busNumber) {
case "55":
return arffFileLocation + arff_55_NORTH_ON_COUNT;
case "60":
return arffFileLocation + arff_60_NORTH_ON_COUNT;
case "181":
return arffFileLocation + arff_181_NORTH_ON_COUNT;
default:
throw new IllegalArgumentException("No arff found for bus");
}
}
}
| 37.647059 | 166 | 0.654688 |
9ecab39d5d0c32b4538c9335fcd63e2b8236fc09 | 691 | package com.liang._02springTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration
public class HelloTest {
// 这里是自动注入标签
@Autowired
private BeanFactory factory;
@Test
public void test() throws Exception {
HelloWorld bean = factory.getBean("helloWorld", HelloWorld.class);
bean.sayHello();
}
}
| 25.592593 | 71 | 0.81042 |
4f8f8ffd6d3015ad46c28d0fe2700f45414ece76 | 133 | package org.atlasapi.content;
import java.util.List;
public interface MutableContentList {
List<ContentRef> getContents();
}
| 13.3 | 37 | 0.759398 |
b7dc24bc635a455a253b14bdc0f89b8a9cbdd7fb | 2,462 | package io.magicthegathering.javasdk.api;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import io.magicthegathering.javasdk.resource.Card;
import io.magicthegathering.javasdk.resource.MtgSet;
/**
* {@link SetAPI} is used to fetch {@link MtgSet}s from magicthegathering.io
*
* @author nniklas
*/
public class SetAPI extends MTGAPI {
private static final String RESOURCE_PATH = "sets";
/**
* Returns a {@link MtgSet} based on the given set code.
* @param setCode Code to find the specific set.
*/
public static MtgSet getSet(String setCode) {
String path = String.format("%s/%s/", RESOURCE_PATH, setCode);
MtgSet returnSet = get(path, "set", MtgSet.class);
if(returnSet != null) {
returnSet.setCards(CardAPI.getAllCards(new LinkedList<>(Collections.singletonList("set=" + setCode))));
}
return returnSet;
}
/**
* The method that returns all the {@link MtgSet}.
* If you want all the card lists populated use
* {@link #getAllSetsWithCards()}.
* @return A List of all the sets.
*/
public static List<MtgSet> getAllSets() {
return getList(RESOURCE_PATH, "sets", MtgSet.class);
}
/**
* The method that will generate a booster for the selected {@link MtgSet}
* @param setCode Code of which set you want a booster for.
* @return the randomized booster for the set.
*/
public static List<Card> getBooster(String setCode) {
String path = String.format("%s/%s/%s/", RESOURCE_PATH, setCode,
"booster");
return getList(path, "cards", Card.class);
}
/**
* Gets a list of {@link MtgSet} based on the provided filters in the
* <a href="https://docs.magicthegathering.io/#sets">web API documentation.</a>
* @param filters List of string filters
* @return The list of {@link MtgSet}s that was found by the filter.
*/
public static List<MtgSet> getAllSets(List<String> filters){
return getList(RESOURCE_PATH, "sets", MtgSet.class, filters);
}
/**
* Gets a list of {@link MtgSet} with all the card objects populated.
* Performance will be degraded because of all the Api calls that will
* happen.
* @return A list of all the sets with cards populated.
*/
public static List<MtgSet> getAllSetsWithCards() {
List<MtgSet> returnList = getList(RESOURCE_PATH, "sets", MtgSet.class);
for(MtgSet set : returnList){
set.setCards(CardAPI.getAllCards(new LinkedList<>(Collections.singletonList("set=" + set.getCode()))));
}
return returnList;
}
}
| 32.394737 | 106 | 0.708367 |
a216fda92ff272c543268cfb09419deb83346d58 | 2,760 | package ch.bailu.tlg_gtk;
import org.gnome.gdk.RGBA;
import ch.bailu.tlg.PlatformContext;
import ch.bailu.tlg.StateRunning;
import ch.bailu.tlg.TlgPoint;
import ch.bailu.tlg.TlgRectangle;
public class BaseContext extends PlatformContext {
private static final int PALETTE_RESERVED=5;
private static final int PALETTE_SIZE=(StateRunning.SHAPE_PER_LEVEL*3)+PALETTE_RESERVED;
private static final int COLOR_GRID=PALETTE_SIZE-PALETTE_RESERVED-1;
private static final int COLOR_BACKGROUND=COLOR_GRID+1;
private static final int COLOR_HIGHLIGHT=COLOR_GRID+2;
private static final int COLOR_DARK=COLOR_GRID+3;
private static final int COLOR_FRAME=COLOR_GRID+4;
private static final int COLOR_GRAYED=COLOR_GRID+5;
private static RGBA palette[] = null;
public BaseContext() {
if (palette == null) {
initPalette();
}
}
private void initPalette() {
float h=0f;
palette=new RGBA[PALETTE_SIZE];
for (int i=0; i< (PALETTE_SIZE - PALETTE_RESERVED); i++) {
float[] rgb = ColorHelper.HSVtoRGB(h, 1f, 1f);
palette[i]= new RGBA(rgb[0], rgb[1], rgb[2], 1);
h++;
h%=6;
}
double x=1d/256d;
palette[COLOR_GRID]= new RGBA(x*44,x*67,x*77,1);
palette[COLOR_FRAME]= new RGBA(x*44,x*109,x*205,1);
palette[COLOR_BACKGROUND]= new RGBA(x*10,x*10,x*10,1);
palette[COLOR_HIGHLIGHT]= new RGBA(1,1,1,1);
palette[COLOR_DARK]= new RGBA(0,0,0,1);
palette[COLOR_GRAYED]= new RGBA(x*208,x*208,x*208,1);
}
public RGBA getGtkColor(int color) {
return palette[color];
}
@Override
public void drawLine(int color, TlgPoint p1, TlgPoint p2) {
}
@Override
public void drawFilledRectangle(int color, TlgRectangle rect) {
}
@Override
public void drawText(int color, TlgRectangle rect, String text) {
}
@Override
public int colorBackground() {
return COLOR_BACKGROUND;
}
@Override
public int colorDark() {
return COLOR_DARK;
}
@Override
public int colorHighlight() {
return COLOR_HIGHLIGHT;
}
@Override
public int colorGrayed() {
return COLOR_GRAYED;
}
@Override
public int colorFrame() {
return COLOR_FRAME;
}
@Override
public int colorGrid() {
return COLOR_GRID;
}
@Override
public int countOfColor() {
return PALETTE_SIZE;
}
@Override
public int getColor(int i) {
return i;
}
@Override
public void onNewHighscore() {
}
}
| 22.08 | 92 | 0.602536 |
e9b1a997f5147b9c381b91ed91a2189a7a1fb773 | 2,085 | package io.raindev.router;
import java.util.List;
import java.util.Optional;
import io.raindev.router.Router.PathNode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RouterTest {
List<String> paths = List.of(
"/",
"/users/",
"/users/{userId}",
"/users/{userId}/books",
"/books",
"/books/{bookId}",
"/static/images");
Router router = new Router(paths);
@Test public void constructPathTree() {
var expectedTree = new PathNode(true,
new PathNode("users", true,
new PathNode("{userId}", true,
new PathNode("books", true))),
new PathNode("books", true,
new PathNode("{bookId}", true)),
new PathNode("static", false,
new PathNode("images", true))
);
var actualTree = Router.constructTree(paths);
assertEquals(expectedTree, actualTree);
}
@Test public void matchingRoot() {
assertEquals(Optional.of("/"), router.match("/"));
}
@Test public void matchingFullPath() {
assertEquals(
Optional.of("/static/images"),
router.match("/static/images"));
}
@Test public void matchingSubPath() {
assertEquals(
Optional.of("/books"),
router.match("/books"));
}
@Test public void matchingWildcard() {
assertEquals(
Optional.of("/users/{userId}/books"),
router.match("/users/5/books"));
}
@Test public void mismatchingPath() {
assertEquals(
Optional.empty(),
router.match("/books/3/author"));
}
@Test public void pathTooShort() {
assertEquals(
Optional.empty(),
router.match("/static"));
}
@Test public void pathTooLong() {
assertEquals(
Optional.empty(),
router.match("/static/images/books"));
}
}
| 27.077922 | 60 | 0.530935 |
c849dc40e5dff6192b11ef5d6fd86e9fdbb93b18 | 1,127 | package org.zalando.riptide.autoconfigure.testing;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.client.MockRestServiceServer;
import org.zalando.riptide.autoconfigure.RiptideClientTest;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
@RiptideClientTest
@ActiveProfiles("testing")
final class RiptideClientTestTest {
@Configuration
@Import(TestService.class)
static class ContextConfiguration {
}
@Autowired
private TestService client;
@Autowired
private MockRestServiceServer server;
@Test
void shouldAutowireMockedHttp() {
server.expect(requestTo("https://example.com/foo/bar")).andRespond(withSuccess());
client.callViaHttp();
server.verify();
}
}
| 29.657895 | 96 | 0.78882 |
d92c6cc0e4317f6ba8fa9f5156a810c4d37810aa | 5,366 | package test;
import boardgames.model.CheckersGame;
import boardgames.model.board.BoardImpl;
import boardgames.model.board.Box;
import boardgames.model.board.CheckersBoard;
import boardgames.model.piece.CheckersPawn;
import boardgames.model.piece.PieceImpl;
import boardgames.utility.Colour;
import boardgames.utility.PairImpl;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test class for Checkers methods.
*
*/
public class CheckersLogicTest {
private CheckersGame game;
private BoardImpl b;
/**
* Initialize Checkers game.
*/
@Before
public void setGame() {
game = new CheckersGame();
b = new BoardImpl();
b.setBoardType(new CheckersBoard());
b.reset();
}
/**
* Black and white player at the beginning have 12 pieces each.
*/
@Test
public void initialSize() {
// CHECKSTYLE: MagicNumber OFF
assertEquals(game.getBoard().getBlackPieces().size(), 12, "Assert size is 12");
assertEquals(game.getBoard().getWhitePieces().size(), 12, "Assert size is 12");
}
/**
* Testing pieces initial possible moves.
*/
@Test
public void chessPiecesInitialPossibleMovesTest() {
assertTrue("Pawn 0 no moves", game.getBoard().getWhitePieces().get(0).possibleMoves(b).isEmpty());
assertTrue("Pawn 2 no moves", game.getBoard().getWhitePieces().get(2).possibleMoves(b).isEmpty());
assertTrue("Pawn 4 no moves", game.getBoard().getWhitePieces().get(4).possibleMoves(b).isEmpty());
assertTrue("Pawn 6 no moves", game.getBoard().getWhitePieces().get(6).possibleMoves(b).isEmpty());
assertTrue("Pawn 8 no moves", game.getBoard().getWhitePieces().get(8).possibleMoves(b).isEmpty());
assertTrue("Pawn 9 no moves", game.getBoard().getWhitePieces().get(9).possibleMoves(b).isEmpty());
assertTrue("Pawn 10 no moves", game.getBoard().getWhitePieces().get(10).possibleMoves(b).isEmpty());
assertTrue("Pawn 11 no moves", game.getBoard().getWhitePieces().get(11).possibleMoves(b).isEmpty());
assertEquals(game.getBoard().getWhitePieces().get(1).possibleMoves(b).size(), 2, "Assert Pawn have 2 moves");
assertEquals(game.getBoard().getWhitePieces().get(3).possibleMoves(b).size(), 2, "Assert Pawn have 2 moves");
assertEquals(game.getBoard().getWhitePieces().get(5).possibleMoves(b).size(), 2, "Assert Pawn have 2 moves");
assertEquals(game.getBoard().getWhitePieces().get(7).possibleMoves(b).size(), 1, "Assert Pawn have 1 moves");
}
/**
* Test piece possible moves after movement.
*/
@Test
public void chessPiecesAfterMovementPossibleMovesTest() {
assertTrue("Pawn 7 can move in 6,3", game.move(Colour.White, game.getBoard().getWhitePieces().get(7), b.getBox(6, 3)));
game.updateMove(game.getBoard().getWhitePieces().get(7), b.getBox(6, 3));
assertTrue("Pawn 11 now can move in 7,2", game.move(Colour.White, game.getBoard().getWhitePieces().get(11), b.getBox(7, 2)));
game.updateMove(game.getBoard().getWhitePieces().get(11), b.getBox(7, 2));
assertFalse("Pawn 9 can't move in 1,2", game.move(Colour.White, game.getBoard().getWhitePieces().get(9), b.getBox(7, 2)));
assertTrue("Pawn 1 can move in 2,3", game.move(Colour.White, game.getBoard().getWhitePieces().get(1), b.getBox(2, 3)));
game.updateMove(game.getBoard().getWhitePieces().get(1), b.getBox(2, 3));
assertTrue("Pawn 9 can now move in 1,2", game.move(Colour.White, game.getBoard().getWhitePieces().get(9), b.getBox(1, 2)));
game.updateMove(game.getBoard().getWhitePieces().get(9), b.getBox(1, 2));
}
/**
* Test if piece promotion happens in right way.
*/
@Test
public void testPromotion() {
final Box b = new Box(new PairImpl<>(7, 7), Optional.empty());
final PieceImpl p = new PieceImpl(b, Colour.White);
p.setPieceType(new CheckersPawn());
b.setPiece(Optional.of(p));
game.setLastPieceMoved(Optional.of(p));
game.promotion(Colour.White, "King");
assertTrue("Now there is Dama", p.getPieceType().get().getName().equals("King"));
}
/**
* Test if piece is correctly remove from board after it has been eaten.
*/
@Test
public void eatTest() {
b.reset();
assertTrue("Pawn 1 can move", game.move(Colour.White, game.getBoard().getWhitePieces().get(1), game.getBoard().getBox(2, 3)));
game.updateMove(game.getBoard().getWhitePieces().get(1), game.getBoard().getBox(2, 3));
assertTrue("Pawn 9 can move", game.move(Colour.Black, game.getBoard().getBlackPieces().get(9), game.getBoard().getBox(3, 4)));
game.updateMove(game.getBoard().getBlackPieces().get(9), game.getBoard().getBox(3, 4));
assertTrue("Pawn 1 eats", game.move(Colour.White, game.getBoard().getBox(2, 3).get().getPiece().get(), game.getBoard().getBox(4, 5)));
game.updateMove(game.getBoard().getWhitePieces().get(1), game.getBoard().getBox(4, 5));
assertFalse("Pawn 9 is no longer on board", game.getBoard().getBlackPieces().contains(game.getLastPieceEated().get(0)));
}
}
| 43.983607 | 142 | 0.663996 |
090c4aa7479550828a8362327501900f155ccef4 | 4,673 | package cn.zhengcaiyun.idata.develop.dal.dao.dag;
import java.sql.JDBCType;
import java.util.Date;
import javax.annotation.Generated;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;
public final class DAGInfoDynamicSqlSupport {
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source Table: dev_dag_info")
public static final DAGInfo dag_info = new DAGInfo();
/**
* Database Column Remarks:
* 主键
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.id")
public static final SqlColumn<Long> id = dag_info.id;
/**
* Database Column Remarks:
* 是否删除,0否,1是
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.del")
public static final SqlColumn<Integer> del = dag_info.del;
/**
* Database Column Remarks:
* 创建者
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.creator")
public static final SqlColumn<String> creator = dag_info.creator;
/**
* Database Column Remarks:
* 创建时间
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.create_time")
public static final SqlColumn<Date> createTime = dag_info.createTime;
/**
* Database Column Remarks:
* 修改者
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.editor")
public static final SqlColumn<String> editor = dag_info.editor;
/**
* Database Column Remarks:
* 修改时间
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.edit_time")
public static final SqlColumn<Date> editTime = dag_info.editTime;
/**
* Database Column Remarks:
* 名称
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.name")
public static final SqlColumn<String> name = dag_info.name;
/**
* Database Column Remarks:
* 数仓分层
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.dw_layer_code")
public static final SqlColumn<String> dwLayerCode = dag_info.dwLayerCode;
/**
* Database Column Remarks:
* 状态,1启用,0停用
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.status")
public static final SqlColumn<Integer> status = dag_info.status;
/**
* Database Column Remarks:
* 备注
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.remark")
public static final SqlColumn<String> remark = dag_info.remark;
/**
* Database Column Remarks:
* 文件夹id
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.folder_id")
public static final SqlColumn<Long> folderId = dag_info.folderId;
/**
* Database Column Remarks:
* 环境
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: dev_dag_info.environment")
public static final SqlColumn<String> environment = dag_info.environment;
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source Table: dev_dag_info")
public static final class DAGInfo extends SqlTable {
public final SqlColumn<Long> id = column("id", JDBCType.BIGINT);
public final SqlColumn<Integer> del = column("del", JDBCType.TINYINT);
public final SqlColumn<String> creator = column("creator", JDBCType.VARCHAR);
public final SqlColumn<Date> createTime = column("create_time", JDBCType.TIMESTAMP);
public final SqlColumn<String> editor = column("editor", JDBCType.VARCHAR);
public final SqlColumn<Date> editTime = column("edit_time", JDBCType.TIMESTAMP);
public final SqlColumn<String> name = column("name", JDBCType.VARCHAR);
public final SqlColumn<String> dwLayerCode = column("dw_layer_code", JDBCType.VARCHAR);
public final SqlColumn<Integer> status = column("status", JDBCType.INTEGER);
public final SqlColumn<String> remark = column("remark", JDBCType.VARCHAR);
public final SqlColumn<Long> folderId = column("folder_id", JDBCType.BIGINT);
public final SqlColumn<String> environment = column("environment", JDBCType.VARCHAR);
public DAGInfo() {
super("dev_dag_info");
}
}
} | 36.795276 | 119 | 0.695485 |
8247e7e2099f85581fa483eb01f51231d168ad7b | 1,434 | /**
* Copyright 2011-2015 John Ericksen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.androidtransfuse.scope;
import javax.inject.Provider;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Encapsulates a scope map utilizing the double-check locking algorithm.
*
* @author John Ericksen
*/
public class ConcurrentDoubleLockingScope implements Scope {
private final ConcurrentMap<ScopeKey, Object> singletonMap = new ConcurrentHashMap<ScopeKey, Object>();
@Override
public <T> T getScopedObject(ScopeKey<T> key, Provider<T> provider) {
Object result = singletonMap.get(key);
if (result == null) {
Object value = provider.get();
result = singletonMap.putIfAbsent(key, value);
if (result == null) {
result = value;
}
}
return (T) result;
}
}
| 31.866667 | 107 | 0.692469 |
89b97851781950dc75ccd8986b19660274ec46c3 | 461 | package com.twitter.summingbird.javaapi;
import com.twitter.summingbird.Platform;
/**
* a Store used in sumByKey
*
* @author Julien Le Dem
*
* @param <P> the underlying platform
* @param <STORE> Is the actual type used by the underlying Platform it is parameterized in <K,V>
* @param <K> key
* @param <V> value
*/
public class Store<P extends Platform<P>, STORE, K, V> extends Wrapper<STORE> {
public Store(STORE store) {
super(store);
}
}
| 20.954545 | 97 | 0.687636 |
ec97820dcfe46d9da9791969f1629a06da9bcf90 | 751 | package com.anrc.model;
public class Location {
private int id;
private String city;
private String road;
private String postalNo;
public Location(){}
public Location(int id, String city, String road, String postalNo) {
super();
this.id = id;
this.city = city;
this.road = road;
this.postalNo = postalNo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
public String getPostalNo() {
return postalNo;
}
public void setPostalNo(String postalNo) {
this.postalNo = postalNo;
}
}
| 17.880952 | 69 | 0.6751 |
497957031dd5720bb86d1c9ccd1cc2f481aaab24 | 378 | package io.quarkus.deployment.pkg;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
@ConfigGroup
public class ManifestConfig {
/**
* If the Implementation information should be included in the runner jar's MANIFEST.MF.
*/
@ConfigItem(defaultValue = "true")
public boolean addImplementationEntries;
}
| 23.625 | 92 | 0.756614 |
4da7e5443846124c5bfef0d8d869b537b5ba98c9 | 4,045 | package org.aaaa;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.aaaa.Enums.DatabasePath;
import org.aaaa.Enums.Models.DeliveryCancellationModel;
import org.aaaa.FileHandlers.FileHandlerOrder;
import org.aaaa.FileHandlers.FileHandlerUser;
public class DeliveryCancellation implements DataInterface {
private String orderID;
private String accountID;
private Order order;
private Staff staff;
private String reason;
private String status;
private LocalDateTime requestDate;
private LocalDateTime approvalDate;
public DeliveryCancellation() {
this.accountID = CurrentUser.getStaff().getAccountID();
this.requestDate = LocalDateTime.now();
}
public DeliveryCancellation(String orderID, String reason, String status) {
this.accountID = CurrentUser.getStaff().getAccountID();
this.requestDate = LocalDateTime.now();
this.orderID = orderID;
this.reason = reason;
this.status = status;
}
public DeliveryCancellation(List<String> data) {
this.set(data);
}
@Override
public List<String> get() {
List<String> result = new ArrayList<>();
result.add(orderID);
result.add(accountID);
result.add(reason);
result.add(status);
if (requestDate == null) {
result.add("");
} else {
result.add(requestDate.toString());
}
if (approvalDate == null) {
result.add("");
} else {
result.add(approvalDate.toString());
}
return result;
}
@Override
public void set(List<String> data) {
FileHandlerUser fileHandlerUser = new FileHandlerUser(DatabasePath.Staff.getName());
this.staff = fileHandlerUser.getUserByAccountID(data.get(DeliveryCancellationModel.AccountID.getIndex()));
FileHandlerOrder fileHandlerOrder = new FileHandlerOrder(DatabasePath.Order.getName());
this.order = fileHandlerOrder.assignOrder(fileHandlerOrder.getOrderByID(data.get(DeliveryCancellationModel.OrderID.getIndex())));
this.orderID = data.get(DeliveryCancellationModel.OrderID.getIndex());
this.accountID = data.get(DeliveryCancellationModel.AccountID.getIndex());
this.reason = data.get(DeliveryCancellationModel.Reason.getIndex());
this.status = data.get(DeliveryCancellationModel.Status.getIndex());
this.requestDate = LocalDateTime.parse(data.get(DeliveryCancellationModel.RequestDate.getIndex()));
if(!data.get(DeliveryCancellationModel.ApprovalDate.getIndex()).equals("")) {
this.approvalDate = LocalDateTime.parse(data.get(DeliveryCancellationModel.ApprovalDate.getIndex()));
}
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getAccountID() {
return accountID;
}
public void setAccountID(String accountID) {
this.accountID = accountID;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getRequestDate() {
return requestDate;
}
public void setRequestDate(LocalDateTime requestDate) {
this.requestDate = requestDate;
}
public LocalDateTime getApprovalDate() {
return approvalDate;
}
public void setApprovalDate(LocalDateTime approvalDate) {
this.approvalDate = approvalDate;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
}
| 27.896552 | 137 | 0.65513 |
5cdb50cca83c9ba0b0b842a5d6526bfd6da66886 | 4,110 | package com.xj.scud.scan;
import com.xj.scud.annotation.Client;
import com.xj.scud.spring.bean.ClientBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author: xiajun
* @date: 2019/5/24 下午8:31
* @since 1.0.0
*/
public class ClientAnnotationProcessor implements BeanClassLoaderAware, BeanFactoryPostProcessor, ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(ClientAnnotationProcessor.class);
private ClassLoader classLoader;
private ApplicationContext context;
private Map<String, BeanDefinition> beanDefinitions = new LinkedHashMap();
private static Set<String> completeBeanName = new HashSet<>();
public void processor(Field field) {
Client scudClient = field.getAnnotation(Client.class);
if (scudClient != null) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClientBean.class);
builder.addPropertyValue("host", scudClient.host());
builder.addPropertyValue("version", scudClient.version());
builder.addPropertyValue("timeout", scudClient.timeout());
builder.addPropertyValue("connentTimeout", scudClient.connentTimeout());
//conf.setNettyBossThreadSize(scudClient.);
if (scudClient.type() != null) {
builder.addPropertyValue("type", scudClient.type().getName());
}
if (scudClient.route() != null) {
builder.addPropertyValue("route", scudClient.route().getValue());
}
builder.addPropertyValue("interfaceClass", field.getType());
builder.getBeanDefinition().setLazyInit(scudClient.lazy());
builder.getBeanDefinition().setScope("singleton");
String name = field.getType().getSimpleName() + ":" + scudClient.version();
beanDefinitions.put(name, builder.getBeanDefinition());
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanDefinitionName);
String beanClassName = definition.getBeanClassName();
if (beanClassName != null) {
Class<?> clazz = ClassUtils.resolveClassName(beanClassName, this.classLoader);
ReflectionUtils.doWithFields(clazz, (field) -> processor(field));
}
}
for (Map.Entry<String, BeanDefinition> entry : beanDefinitions.entrySet()) {
if (!completeBeanName.contains(entry.getKey()) && !context.containsBean(entry.getKey())) {
((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(entry.getKey(), entry.getValue());
completeBeanName.add(entry.getKey());
logger.info("registered scud client bean '{} in spring context.", entry.getKey());
}
}
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
| 47.241379 | 123 | 0.711192 |
f79b204eb0b7edb60811d7e3f72c68719d6e5ce9 | 2,185 | package com.entity;
import java.io.Serializable;
import java.util.List;
public class User implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = 2710820901930537171L;
private int id;
private int cardID;
private String name;
private String pwd;
private String sex;
private String tutor;
private String specialty;
private int papers;
private List<String> title;
private List<String> URL;
public User() {
this(1,0,"","","","","",0);
}
public User(int id, int cardId, String name, String pwd, String sex, String tutor, String specialty, int papers) {
this.id = id;
this.cardID = cardId;
this.name = name;
this.pwd = pwd;
this.sex = sex;
this.tutor = tutor;
this.specialty = specialty;
this.papers = papers;
this.title = null;
this.URL = null;
}
public int getId() {
return this.id;
}
public int getCardID() {
return this.cardID;
}
public String getName() {
return this.name;
}
public String getPwd() {
return this.pwd;
}
public String getSex() {
return this.sex;
}
public String getTutor() {
return this.tutor;
}
public String getSpecialty() {
return this.specialty;
}
public int getPapers() {
return this.papers;
}
public List<String> getTitle() {
return this.title;
}
public List<String> getURL() {
return this.URL;
}
public void setId(int id) {
this.id = id;
}
public void setCardID(int cardId) {
this.cardID = cardId;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setTutor(String tutor) {
this.tutor = tutor;
}
public void setSpecialty(String specialty) {
this.specialty = specialty;
}
public void setPapers(int papers) {
this.papers = papers;
}
public void setTitle(List<String> title) {
this.title = title;
}
public void setURL(List<String> URL) {
this.URL = URL;
}
public void appendPaper(String title, String URL) {
this.papers++;
this.title.add(title);
this.URL.add(URL);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 19.684685 | 115 | 0.679176 |
2230d123f10e9c7838440ac47a4199d61e31cfab | 17,659 | package java_cup;
import java_cup.runtime.Symbol;
import java.util.Hashtable;
/** This class implements a small scanner (aka lexical analyzer or lexer) for
* the JavaCup specification. This scanner reads characters from standard
* input (System.in) and returns integers corresponding to the terminal
* number of the next Symbol. Once end of input is reached the EOF Symbol is
* returned on every subsequent call.<p>
* Symbols currently returned include: <pre>
* Symbol Constant Returned Symbol Constant Returned
* ------ ----------------- ------ -----------------
* "package" PACKAGE "import" IMPORT
* "code" CODE "action" ACTION
* "parser" PARSER "terminal" TERMINAL
* "non" NON "init" INIT
* "scan" SCAN "with" WITH
* "start" START "precedence" PRECEDENCE
* "left" LEFT "right" RIGHT
* "nonassoc" NONASSOC "%prec PRECENT_PREC
* [ LBRACK ] RBRACK
* ; SEMI
* , COMMA * STAR
* . DOT : COLON
* ::= COLON_COLON_EQUALS | BAR
* identifier ID {:...:} CODE_STRING
* "nonterminal" NONTERMINAL
* </pre>
* All symbol constants are defined in sym.java which is generated by
* JavaCup from parser.cup.<p>
*
* In addition to the scanner proper (called first via init() then with
* next_token() to get each Symbol) this class provides simple error and
* warning routines and keeps a count of errors and warnings that is
* publicly accessible.<p>
*
* This class is "static" (i.e., it has only static members and methods).
*
* @version last updated: 7/3/96
* @author Frank Flannery
*/
public class lexer {
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** The only constructor is private, so no instances can be created. */
private lexer() { }
/*-----------------------------------------------------------*/
/*--- Static (Class) Variables ------------------------------*/
/*-----------------------------------------------------------*/
/** First character of lookahead. */
protected static int next_char;
/** Second character of lookahead. */
protected static int next_char2;
/** Second character of lookahead. */
protected static int next_char3;
/** Second character of lookahead. */
protected static int next_char4;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** EOF constant. */
protected static final int EOF_CHAR = -1;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Table of keywords. Keywords are initially treated as identifiers.
* Just before they are returned we look them up in this table to see if
* they match one of the keywords. The string of the name is the key here,
* which indexes Integer objects holding the symbol number.
*/
protected static Hashtable keywords = new Hashtable(23);
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Table of single character symbols. For ease of implementation, we
* store all unambiguous single character Symbols in this table of Integer
* objects keyed by Integer objects with the numerical value of the
* appropriate char (currently Character objects have a bug which precludes
* their use in tables).
*/
protected static Hashtable char_symbols = new Hashtable(11);
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Current line number for use in error messages. */
protected static int current_line = 1;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Character position in current line. */
protected static int current_position = 1;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Character position in current line. */
protected static int absolute_position = 1;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Count of total errors detected so far. */
public static int error_count = 0;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Count of warnings issued so far */
public static int warning_count = 0;
/*-----------------------------------------------------------*/
/*--- Static Methods ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Initialize the scanner. This sets up the keywords and char_symbols
* tables and reads the first two characters of lookahead.
*/
public static void init() throws java.io.IOException
{
/* set up the keyword table */
keywords.put("package", new Integer(sym.PACKAGE));
keywords.put("import", new Integer(sym.IMPORT));
keywords.put("code", new Integer(sym.CODE));
keywords.put("action", new Integer(sym.ACTION));
keywords.put("parser", new Integer(sym.PARSER));
keywords.put("terminal", new Integer(sym.TERMINAL));
keywords.put("non", new Integer(sym.NON));
keywords.put("nonterminal",new Integer(sym.NONTERMINAL));// [CSA]
keywords.put("init", new Integer(sym.INIT));
keywords.put("scan", new Integer(sym.SCAN));
keywords.put("with", new Integer(sym.WITH));
keywords.put("start", new Integer(sym.START));
keywords.put("precedence", new Integer(sym.PRECEDENCE));
keywords.put("left", new Integer(sym.LEFT));
keywords.put("right", new Integer(sym.RIGHT));
keywords.put("nonassoc", new Integer(sym.NONASSOC));
/* set up the table of single character symbols */
char_symbols.put(new Integer(';'), new Integer(sym.SEMI));
char_symbols.put(new Integer(','), new Integer(sym.COMMA));
char_symbols.put(new Integer('*'), new Integer(sym.STAR));
char_symbols.put(new Integer('.'), new Integer(sym.DOT));
char_symbols.put(new Integer('|'), new Integer(sym.BAR));
char_symbols.put(new Integer('['), new Integer(sym.LBRACK));
char_symbols.put(new Integer(']'), new Integer(sym.RBRACK));
/* read two characters of lookahead */
next_char = System.in.read();
if (next_char == EOF_CHAR) {
next_char2 = EOF_CHAR;
next_char3 = EOF_CHAR;
next_char4 = EOF_CHAR;
} else {
next_char2 = System.in.read();
if (next_char2 == EOF_CHAR) {
next_char3 = EOF_CHAR;
next_char4 = EOF_CHAR;
} else {
next_char3 = System.in.read();
if (next_char3 == EOF_CHAR) {
next_char4 = EOF_CHAR;
} else {
next_char4 = System.in.read();
}
}
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Advance the scanner one character in the input stream. This moves
* next_char2 to next_char and then reads a new next_char2.
*/
protected static void advance() throws java.io.IOException
{
int old_char;
old_char = next_char;
next_char = next_char2;
if (next_char == EOF_CHAR) {
next_char2 = EOF_CHAR;
next_char3 = EOF_CHAR;
next_char4 = EOF_CHAR;
} else {
next_char2 = next_char3;
if (next_char2 == EOF_CHAR) {
next_char3 = EOF_CHAR;
next_char4 = EOF_CHAR;
} else {
next_char3 = next_char4;
if (next_char3 == EOF_CHAR) {
next_char4 = EOF_CHAR;
} else {
next_char4 = System.in.read();
}
}
}
/* count this */
absolute_position++;
current_position++;
if (old_char == '\n' || (old_char == '\r' && next_char!='\n'))
{
current_line++;
current_position = 1;
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Emit an error message. The message will be marked with both the
* current line number and the position in the line. Error messages
* are printed on standard error (System.err).
* @param message the message to print.
*/
public static void emit_error(String message)
{
System.err.println("Error at " + current_line + "(" + current_position +
"): " + message);
error_count++;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Emit a warning message. The message will be marked with both the
* current line number and the position in the line. Messages are
* printed on standard error (System.err).
* @param message the message to print.
*/
public static void emit_warn(String message)
{
System.err.println("Warning at " + current_line + "(" + current_position +
"): " + message);
warning_count++;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if a character is ok to start an id.
* @param ch the character in question.
*/
protected static boolean id_start_char(int ch)
{
/* allow for % in identifiers. a hack to allow my
%prec in. Should eventually make lex spec for this
frankf */
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch == '_');
// later need to deal with non-8-bit chars here
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if a character is ok for the middle of an id.
* @param ch the character in question.
*/
protected static boolean id_char(int ch)
{
return id_start_char(ch) || (ch >= '0' && ch <= '9');
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Try to look up a single character symbol, returns -1 for not found.
* @param ch the character in question.
*/
protected static int find_single_char(int ch)
{
Integer result;
result = (Integer)char_symbols.get(new Integer((char)ch));
if (result == null)
return -1;
else
return result.intValue();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Handle swallowing up a comment. Both old style C and new style C++
* comments are handled.
*/
protected static void swallow_comment() throws java.io.IOException
{
/* next_char == '/' at this point */
/* is it a traditional comment */
if (next_char2 == '*')
{
/* swallow the opener */
advance(); advance();
/* swallow the comment until end of comment or EOF */
for (;;)
{
/* if its EOF we have an error */
if (next_char == EOF_CHAR)
{
emit_error("Specification file ends inside a comment");
return;
}
/* if we can see the closer we are done */
if (next_char == '*' && next_char2 == '/')
{
advance();
advance();
return;
}
/* otherwise swallow char and move on */
advance();
}
}
/* is its a new style comment */
if (next_char2 == '/')
{
/* swallow the opener */
advance(); advance();
/* swallow to '\n', '\r', '\f', or EOF */
while (next_char != '\n' && next_char != '\r' &&
next_char != '\f' && next_char!=EOF_CHAR)
advance();
return;
}
/* shouldn't get here, but... if we get here we have an error */
emit_error("Malformed comment in specification -- ignored");
advance();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Swallow up a code string. Code strings begin with "{:" and include
all characters up to the first occurrence of ":}" (there is no way to
include ":}" inside a code string). The routine returns a String
object suitable for return by the scanner.
*/
protected static Symbol do_code_string() throws java.io.IOException
{
StringBuffer result = new StringBuffer();
/* at this point we have lookahead of "{:" -- swallow that */
advance(); advance();
/* save chars until we see ":}" */
while (!(next_char == ':' && next_char2 == '}'))
{
/* if we have run off the end issue a message and break out of loop */
if (next_char == EOF_CHAR)
{
emit_error("Specification file ends inside a code string");
break;
}
/* otherwise record the char and move on */
result.append(new Character((char)next_char));
advance();
}
/* advance past the closer and build a return Symbol */
advance(); advance();
return new Symbol(sym.CODE_STRING, result.toString());
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Process an identifier. Identifiers begin with a letter, underscore,
* or dollar sign, which is followed by zero or more letters, numbers,
* underscores or dollar signs. This routine returns a String suitable
* for return by the scanner.
*/
protected static Symbol do_id() throws java.io.IOException
{
StringBuffer result = new StringBuffer();
String result_str;
Integer keyword_num;
char buffer[] = new char[1];
/* next_char holds first character of id */
buffer[0] = (char)next_char;
result.append(buffer,0,1);
advance();
/* collect up characters while they fit in id */
while(id_char(next_char))
{
buffer[0] = (char)next_char;
result.append(buffer,0,1);
advance();
}
/* extract a string and try to look it up as a keyword */
result_str = result.toString();
keyword_num = (Integer)keywords.get(result_str);
/* if we found something, return that keyword */
if (keyword_num != null)
return new Symbol(keyword_num.intValue());
/* otherwise build and return an id Symbol with an attached string */
return new Symbol(sym.ID, result_str);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Return one Symbol. This is the main external interface to the scanner.
* It consumes sufficient characters to determine the next input Symbol
* and returns it. To help with debugging, this routine actually calls
* real_next_token() which does the work. If you need to debug the
* parser, this can be changed to call debug_next_token() which prints
* a debugging message before returning the Symbol.
*/
public static Symbol next_token() throws java.io.IOException
{
return real_next_token();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Debugging version of next_token(). This routine calls the real scanning
* routine, prints a message on System.out indicating what the Symbol is,
* then returns it.
*/
public static Symbol debug_next_token() throws java.io.IOException
{
Symbol result = real_next_token();
System.out.println("# next_Symbol() => " + result.sym);
return result;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The actual routine to return one Symbol. This is normally called from
* next_token(), but for debugging purposes can be called indirectly from
* debug_next_token().
*/
protected static Symbol real_next_token() throws java.io.IOException
{
int sym_num;
for (;;)
{
/* look for white space */
if (next_char == ' ' || next_char == '\t' || next_char == '\n' ||
next_char == '\f' || next_char == '\r')
{
/* advance past it and try the next character */
advance();
continue;
}
/* look for a single character symbol */
sym_num = find_single_char(next_char);
if (sym_num != -1)
{
/* found one -- advance past it and return a Symbol for it */
advance();
return new Symbol(sym_num);
}
/* look for : or ::= */
if (next_char == ':')
{
/* if we don't have a second ':' return COLON */
if (next_char2 != ':')
{
advance();
return new Symbol(sym.COLON);
}
/* move forward and look for the '=' */
advance();
if (next_char2 == '=')
{
advance(); advance();
return new Symbol(sym.COLON_COLON_EQUALS);
}
else
{
/* return just the colon (already consumed) */
return new Symbol(sym.COLON);
}
}
/* find a "%prec" string and return it. otherwise, a '%' was found,
which has no right being in the specification otherwise */
if (next_char == '%') {
advance();
if ((next_char == 'p') && (next_char2 == 'r') && (next_char3 == 'e') &&
(next_char4 == 'c')) {
advance();
advance();
advance();
advance();
return new Symbol(sym.PERCENT_PREC);
} else {
emit_error("Found extraneous percent sign");
}
}
/* look for a comment */
if (next_char == '/' && (next_char2 == '*' || next_char2 == '/'))
{
/* swallow then continue the scan */
swallow_comment();
continue;
}
/* look for start of code string */
if (next_char == '{' && next_char2 == ':')
return do_code_string();
/* look for an id or keyword */
if (id_start_char(next_char)) return do_id();
/* look for EOF */
if (next_char == EOF_CHAR) return new Symbol(sym.EOF);
/* if we get here, we have an unrecognized character */
emit_warn("Unrecognized character '" +
new Character((char)next_char) + "'(" + next_char +
") -- ignored");
/* advance past it */
advance();
}
}
/*-----------------------------------------------------------*/
}
| 32.461397 | 80 | 0.53729 |
60785c358973e548121c64d5836d73e51078c1b0 | 10,847 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 The Voxel Plugineering Team
*
* 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.voxelplugineering.voxelsniper;
import com.voxelplugineering.voxelsniper.brush.BrushInfo;
import com.voxelplugineering.voxelsniper.brush.CommonBrushManager;
import com.voxelplugineering.voxelsniper.brush.GlobalBrushManager;
import com.voxelplugineering.voxelsniper.commands.AliasCommand;
import com.voxelplugineering.voxelsniper.commands.BrushCommand;
import com.voxelplugineering.voxelsniper.commands.HelpCommand;
import com.voxelplugineering.voxelsniper.commands.MaskMaterialCommand;
import com.voxelplugineering.voxelsniper.commands.MaterialCommand;
import com.voxelplugineering.voxelsniper.commands.ParameterCommand;
import com.voxelplugineering.voxelsniper.commands.RedoCommand;
import com.voxelplugineering.voxelsniper.commands.ResetCommand;
import com.voxelplugineering.voxelsniper.commands.UndoCommand;
import com.voxelplugineering.voxelsniper.commands.VSCommand;
import com.voxelplugineering.voxelsniper.config.BaseConfiguration;
import com.voxelplugineering.voxelsniper.config.VoxelSniperConfiguration;
import com.voxelplugineering.voxelsniper.event.handler.CommonEventHandler;
import com.voxelplugineering.voxelsniper.service.BrushManagerService;
import com.voxelplugineering.voxelsniper.service.Builder;
import com.voxelplugineering.voxelsniper.service.InitHook;
import com.voxelplugineering.voxelsniper.service.OfflineUndoHandlerService;
import com.voxelplugineering.voxelsniper.service.PostInit;
import com.voxelplugineering.voxelsniper.service.PreStop;
import com.voxelplugineering.voxelsniper.service.ServicePriorities;
import com.voxelplugineering.voxelsniper.service.alias.AnnotationScanner;
import com.voxelplugineering.voxelsniper.service.alias.CommonAliasHandler;
import com.voxelplugineering.voxelsniper.service.alias.GlobalAliasHandler;
import com.voxelplugineering.voxelsniper.service.alias.GlobalAliasOwner;
import com.voxelplugineering.voxelsniper.service.alias.GlobalAliasService;
import com.voxelplugineering.voxelsniper.service.command.CommandHandler;
import com.voxelplugineering.voxelsniper.service.command.CommandHandlerService;
import com.voxelplugineering.voxelsniper.service.config.Configuration;
import com.voxelplugineering.voxelsniper.service.config.ConfigurationContainer;
import com.voxelplugineering.voxelsniper.service.config.ConfigurationService;
import com.voxelplugineering.voxelsniper.service.eventbus.AsyncEventBus;
import com.voxelplugineering.voxelsniper.service.eventbus.EventBus;
import com.voxelplugineering.voxelsniper.service.meta.AnnotationScannerService;
import com.voxelplugineering.voxelsniper.service.permission.PermissionProxy;
import com.voxelplugineering.voxelsniper.service.permission.TrivialPermissionProxy;
import com.voxelplugineering.voxelsniper.service.platform.PlatformProxy;
import com.voxelplugineering.voxelsniper.service.platform.TrivialPlatformProxy;
import com.voxelplugineering.voxelsniper.service.registry.PlayerRegistry;
import com.voxelplugineering.voxelsniper.service.scheduler.Scheduler;
import com.voxelplugineering.voxelsniper.service.text.TextFormatParser;
import com.voxelplugineering.voxelsniper.util.AnnotationHelper;
import com.voxelplugineering.voxelsniper.util.Context;
import com.voxelplugineering.voxelsniper.util.DataTranslator;
import com.voxelplugineering.voxelsniper.util.defaults.DefaultAliasBuilder;
import com.voxelplugineering.voxelsniper.world.queue.ChangeQueueTask;
import com.voxelplugineering.voxelsniper.world.queue.OfflineUndoHandler;
import java.io.File;
import java.io.IOException;
import java.net.URLClassLoader;
import java.util.Optional;
/**
* The core service provider.
*/
@SuppressWarnings({ "checkstyle:javadocmethod", "javadoc", "static-method" })
public class CoreServiceProvider
{
public CoreServiceProvider()
{
}
@Builder(target = AnnotationScanner.class,
priority = ServicePriorities.ANNOTATION_SCANNER_PRIORITY)
public final AnnotationScanner buildAnnotationScanner(Context context)
{
return new AnnotationScannerService(context);
}
@Builder(target = Configuration.class,
priority = ServicePriorities.CONFIGURATION_PRIORITY)
public final Configuration buildConfig(Context context)
{
return new ConfigurationService(context);
}
@Builder(target = TextFormatParser.class,
priority = ServicePriorities.TEXT_FORMAT_PRIORITY)
public final TextFormatParser buildFormatProxy(Context context)
{
return new TextFormatParser.TrivialTextFormatParser(context);
}
@Builder(target = EventBus.class,
priority = ServicePriorities.EVENT_BUS_PRIORITY)
public final EventBus buildEventBus(Context context)
{
return new AsyncEventBus(context);
}
@Builder(target = GlobalAliasHandler.class,
priority = ServicePriorities.GLOBAL_ALIAS_HANDLER_PRIORITY)
public final GlobalAliasHandler buildAliasRegistry(Context context)
{
PlatformProxy platform = context.getRequired(PlatformProxy.class);
return new GlobalAliasService(context, new CommonAliasHandler(new GlobalAliasOwner(new File(platform.getRoot(), "aliases.json"))));
}
@InitHook(target = EventBus.class)
public final void initEventBus(Context context, EventBus service)
{
service.register(new CommonEventHandler(context));
}
@InitHook(target = Configuration.class)
public final void initConfig(Context context, Configuration configuration)
{
context.getRequired(AnnotationScanner.class).register(ConfigurationContainer.class, (ConfigurationService) configuration);
}
@InitHook(target = GlobalAliasHandler.class)
public final void initAlias(Context context, GlobalAliasHandler service)
{
service.registerTarget("brush");
service.registerTarget("material");
try
{
service.load();
} catch (IOException e)
{
GunsmithLogger.getLogger().error(e, "Error loading global aliases");
}
}
@Builder(target = GlobalBrushManager.class,
priority = ServicePriorities.GLOBAL_BRUSH_MANAGER_PRIORITY)
public final GlobalBrushManager getGlobalBrushManager(Context context)
{
return new BrushManagerService(context, new CommonBrushManager(context));
}
@InitHook(target = GlobalBrushManager.class)
public final void findBrushes(Context context, GlobalBrushManager gbm)
{
context.getRequired(AnnotationScanner.class).register(BrushInfo.class, gbm);
}
@Builder(target = CommandHandler.class,
priority = ServicePriorities.COMMAND_HANDLER_PRIORITY)
public final CommandHandler getCommandHandler(Context context)
{
return new CommandHandlerService(context);
}
@InitHook(target = CommandHandler.class)
public final void registerCommands(Context context, CommandHandler cmd)
{
cmd.registerCommand(new BrushCommand(context));
cmd.registerCommand(new MaterialCommand(context));
cmd.registerCommand(new MaskMaterialCommand(context));
cmd.registerCommand(new VSCommand(context));
cmd.registerCommand(new AliasCommand(context));
cmd.registerCommand(new HelpCommand(context));
cmd.registerCommand(new ResetCommand(context));
cmd.registerCommand(new UndoCommand(context));
cmd.registerCommand(new RedoCommand(context));
cmd.registerCommand(new ParameterCommand(context));
}
@Builder(target = OfflineUndoHandler.class,
priority = ServicePriorities.UNDO_HANDLER_PRIORITY)
public final OfflineUndoHandler getOfflineUndo(Context context)
{
return new OfflineUndoHandlerService(context);
}
@Builder(target = PlatformProxy.class,
priority = ServicePriorities.PLATFORM_PROXY_PRIORITY)
public final PlatformProxy getTrivialPlatform(Context context)
{
return new TrivialPlatformProxy(context);
}
@Builder(target = PermissionProxy.class,
priority = ServicePriorities.PERMISSION_PROXY_PRIORITY)
public final PermissionProxy getPermissionsProxy(Context context)
{
return new TrivialPermissionProxy(context);
}
/**
* Post init.
*/
@PostInit
public final void post(Context context)
{
DataTranslator.initialize(context);
context.getRequired(AnnotationScanner.class).scanClassPath((URLClassLoader) Gunsmith.getClassLoader());
PlayerRegistry<?> players = context.getRequired(PlayerRegistry.class);
Configuration conf = context.getRequired(Configuration.class);
PlatformProxy platform = context.getRequired(PlatformProxy.class);
try
{
conf.initialize(platform.getRoot(), false);
} catch (IOException e)
{
GunsmithLogger.getLogger().error(e, "Error initializing configuration files.");
}
Optional<Scheduler> sched = context.get(Scheduler.class);
if (sched.isPresent())
{
sched.get().startSynchronousTask(new ChangeQueueTask(players), BaseConfiguration.changeInterval);
}
Optional<GlobalAliasHandler> aliases = context.get(GlobalAliasHandler.class);
if (aliases.isPresent() && VoxelSniperConfiguration.generateDefaultAliases)
{
DefaultAliasBuilder.loadDefaultAliases(aliases.get());
}
}
/**
* Stop hook.
*/
@PreStop
public final void onStop(Context context)
{
Optional<Scheduler> sched = context.get(Scheduler.class);
if (sched.isPresent())
{
sched.get().stopAllTasks();
}
AnnotationHelper.clean();
}
}
| 41.400763 | 139 | 0.763068 |
a62836b993723e200cfc7bd4ee6b00dda1fd1061 | 9,039 | package DataLayer.Sistem;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatatypeMismatchException;
import android.database.sqlite.SQLiteException;
import android.util.Log;
;import java.util.ArrayList;
import java.util.List;
import ContractLayer.OrtakCo.OrtakAgacTuru_Co;
import ContractLayer.SistemCo.SOrgBirim_Co;
import DataLayer.Ortak.DataController;
import EntityLayer.Ortak.OrtakAgacTuru;
import EntityLayer.Sistem.SOrgBirim;
import ToolLayer.OrbisDefaultException;
/**
* Created by Ömer YILDIRIM on 21.01.2016.
*/
public class SOrgBirim_Data extends DataController<SOrgBirim> {
public SOrgBirim_Data(Context ctx) {
super(ctx, new SOrgBirim());
}
public List<SOrgBirim> loadFromQuery(String queryStr) throws OrbisDefaultException {
List<SOrgBirim> birimList = new ArrayList<SOrgBirim>();
try {
db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery(queryStr, null);
if(cursor.getCount()>0){
while (cursor.moveToNext()){
birimList.add((SOrgBirim) CursorToObject(cursor));
}
cursor.close();
}
}catch (Exception e){
throw new OrbisDefaultException(e.toString());
}
finally {
db.close();
return birimList;
}
}
public SOrgBirim CursorToObject(Cursor cursor) throws OrbisDefaultException {
SOrgBirim o = new SOrgBirim();
o.setId(cursor.getLong(cursor.getColumnIndex("id")));
o.setUstId(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c1_ust_id_typ_long)));
o.setYol(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c2_yol_typ_string)));
o.setKurumId(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c3_kurum_id_typ_long)));
o.setAdi(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c4_adi_typ_string)));
//o.setAktif(cursor.getInt(cursor.getColumnIndex(SOrgBirim_Co.c5_aktif_typ_int)));
o.setKodu(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c6_kodu_typ_string)));
o.setDesimalKodu(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c7_desimal_kodu_typ_string)));
o.setDahiliKod(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c8_dahili_kod_typ_string)));
o.setKategori(cursor.getInt(cursor.getColumnIndex(SOrgBirim_Co.c9_kategori_typ_int)));
o.setTipi(cursor.getInt(cursor.getColumnIndex(SOrgBirim_Co.c10_tipi_typ_int)));
o.setSinifi(cursor.getInt(cursor.getColumnIndex(SOrgBirim_Co.c11_sinifi_typ_int)));
o.setOzelKod1(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c12_ozel_kod_1_typ_string)));
o.setOzelKod2(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c13_ozel_kod_2_typ_string)));
o.setAdres(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c14_adres_typ_string)));
o.setKatNo(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c15_kat_no_typ_string)));
o.setOdaNo(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c16_oda_no_typ_string)));
o.setTelefon1(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c17_telefon_1_typ_string)));
o.setTelefon2(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c18_telefon_2_typ_string)));
o.setDahiliTelefon1(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c19_dahili_telefon_1_typ_string)));
o.setDahiliTelefon2(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c20_dahili_telefon_2_typ_string)));
o.setEposta(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c21_e_posta_typ_string)));
o.setYetkiliId(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c22_yetkili_id_typ_long)));
// o.setGunlemeZamani(cursor.getString(cursor.getColumnIndex(SOrgBirim_Co.c23_gunleme_zamani_typ_string)));
o.setGunleyenId(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c24_gunleyen_id_typ_long)));
o.setOrgId(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c25_org_id_typ_long)));
o.setMid(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c26_mid)));
o.setMustid(cursor.getLong(cursor.getColumnIndex(SOrgBirim_Co.c27_mustid)));
o.setGonderildi(cursor.getInt(cursor.getColumnIndex(SOrgBirim_Co.c28_gonderildi)));
return o;
}
public Boolean insertFromContent(List<SOrgBirim> itms) throws OrbisDefaultException
{
Boolean status =false;
if (itms!=null&& itms.size()>0)
{
Long m_id=0L;
db = helper.getWritableDatabase();
db.beginTransaction();
for (SOrgBirim kayit : itms)
{
long id = 0;
try {
ContentValues line = new ContentValues();
line = ObjectToContentValues(kayit);
m_id = db.insertOrThrow(SOrgBirim_Co.S_ORG_BIRIM_TABLE, null, line);
if (m_id > 0) {
status = true;
kayit.setMid(m_id);
} else {
status = false;
throw new OrbisDefaultException("oragacdata-insert:Kayit Eklenemedi, database tablosu hatalı !" + kayit.toString());
}
} catch (SQLiteConstraintException e) {
status = false;
Log.d("DataController", e.getMessage());
throw new OrbisDefaultException("DataController(insert)Hata:" + e.getMessage());
} catch (SQLiteDatatypeMismatchException e) {
Log.d("DataController", e.getMessage());
status = false;
throw new OrbisDefaultException("DataController(insert)Hata:" + e.getMessage());
} catch (SQLiteException e) {
Log.d("DataController", e.getMessage());
status = false;
throw new OrbisDefaultException("DataController(insert)Hata:" + e.getMessage());
}
catch (Throwable e)
{
Log.d("DataController:insert\n", e.getMessage());
status = false;
throw new OrbisDefaultException("DataController:insert\n:" + e.toString());
}
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
return status;
}
public ContentValues ObjectToContentValues(SOrgBirim o) throws OrbisDefaultException {
ContentValues satir = new ContentValues();
try{
satir.put(SOrgBirim_Co.c0_id_typ_long,o.getId());
satir.put(SOrgBirim_Co.c1_ust_id_typ_long,o.getUstId());
satir.put(SOrgBirim_Co.c2_yol_typ_string,o.getYol());
satir.put(SOrgBirim_Co.c3_kurum_id_typ_long,o.getKurumId());
satir.put(SOrgBirim_Co.c4_adi_typ_string,o.getAdi());
satir.put(SOrgBirim_Co.c5_aktif_typ_int,o.getAktif());
satir.put(SOrgBirim_Co.c6_kodu_typ_string,o.getKodu());
satir.put(SOrgBirim_Co.c7_desimal_kodu_typ_string,o.getDesimalKodu());
satir.put(SOrgBirim_Co.c8_dahili_kod_typ_string,o.getDahiliKod());
satir.put(SOrgBirim_Co.c9_kategori_typ_int,o.getKategori());
satir.put(SOrgBirim_Co.c10_tipi_typ_int,o.getTipi());
satir.put(SOrgBirim_Co.c11_sinifi_typ_int,o.getSinifi());
satir.put(SOrgBirim_Co.c12_ozel_kod_1_typ_string,o.getOzelKod1());
satir.put(SOrgBirim_Co.c13_ozel_kod_2_typ_string,o.getOzelKod2());
satir.put(SOrgBirim_Co.c14_adres_typ_string,o.getAdres());
satir.put(SOrgBirim_Co.c15_kat_no_typ_string,o.getKatNo());
satir.put(SOrgBirim_Co.c16_oda_no_typ_string,o.getOdaNo());
satir.put(SOrgBirim_Co.c17_telefon_1_typ_string,o.getTelefon1());
satir.put(SOrgBirim_Co.c18_telefon_2_typ_string,o.getTelefon2());
satir.put(SOrgBirim_Co.c19_dahili_telefon_1_typ_string,o.getDahiliTelefon1());
satir.put(SOrgBirim_Co.c20_dahili_telefon_2_typ_string,o.getDahiliTelefon2());
satir.put(SOrgBirim_Co.c21_e_posta_typ_string,o.getEposta());
satir.put(SOrgBirim_Co.c22_yetkili_id_typ_long,o.getYetkiliId());
// satir.put(SOrgBirim_Co.c23_gunleme_zamani_typ_string,o.getGunlemeZamani());
satir.put(SOrgBirim_Co.c24_gunleyen_id_typ_long,o.getGunleyenId());
satir.put(SOrgBirim_Co.c25_org_id_typ_long,o.getOrgId());
satir.put(SOrgBirim_Co.c26_mid,o.getMid());
satir.put(SOrgBirim_Co.c27_mustid,o.getMustid());
}
catch (Exception e){
throw new OrbisDefaultException(e.toString());
}
finally {
return satir;
}
}
} | 51.948276 | 141 | 0.66556 |
17e7976a6a46d676f081ad4b1d20be33fb0b781f | 1,385 | package de.leoliebig.playground.data;
import java.util.List;
/**
* Defines the basic operations of a data source. Use this interface to encapsulate a data source
* and the technology used to access it.
* <p>
* Created by Leo on 25.02.2017.
*/
public interface DataSource<T> {
void load(long id, LoadListener listener);
void loadList(int page, LoadListener listener);
void save(T data, SaveListener listener);
void saveList(List<T> data, SaveListener listener);
void delete(long id, DeleteListener listener);
void deleteList(List<Long> ids, DeleteListener listener);
interface LoadListener<T> {
void onLoaded(long id, T data, int resultCode);
void onListLoaded(int page, List<T> data, int resultCode);
void onLoadError(long id, Throwable t);
void onListLoadError(int page, Throwable t);
}
interface SaveListener<T> {
void onSaved(T data, int resultCode);
void onListSaved(List<T> data, int resultCode);
void onSaveError(T data, Throwable t);
void onListSaveError(List<T> data, Throwable t);
}
interface DeleteListener<T> {
void onDeleted(long id, int resultCode);
void onListDeleted(List<Long> ids, int resultCode);
void onDeleteError(long id, Throwable t);
void onListDeleteError(List<Long> ids, Throwable t);
}
}
| 24.298246 | 97 | 0.676534 |
f161eba7a2bb0d0944e130e2d65731837701f14a | 1,006 | package firstinspires.ftc.teamcode.autonomous.camera;
/*
import java.awt.image.BufferedImage;
import java.util.function.Predicate;
public class PixelValidator {
public static Pixel[] loadPixelsFromImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
Pixel[] pixels = new Pixel[width * height];
int pos = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = image.getRGB(x, y);
pixels[pos++] = new Pixel(rgb, x, y);
}
}
return pixels;
}
public static Pixel[] validate(Pixel[] pixels, Predicate<Pixel> validator) {
Pixel[] valid = new Pixel[pixels.length];
for (int i = 0; i < pixels.length; i++) {
if (validator.test(pixels[i])) {
valid[i] = pixels[i];
} else {
valid[i] = null;
}
}
return valid;
}
}
*/ | 25.794872 | 80 | 0.520875 |
9bc928f008c625b7f67fb34c5c28c3b6b6105589 | 3,112 | // Copyright (c) 2012 Tim Niblett. All Rights Reserved.
//
// File: ShortenURLBitly.java (30/09/12)
// Author: tim
//
// Copyright in the whole and every part of this source file belongs to
// Tim Niblett (the Author) and may not be used, sold, licenced,
// transferred, copied or reproduced in whole or in part in
// any manner or form or in or on any media to any person other than
// in accordance with the terms of The Author's agreement
// or otherwise without the prior written consent of The Author. All
// information contained in this source file is confidential information
// belonging to The Author and as such may not be disclosed other
// than in accordance with the terms of The Author's agreement, or
// otherwise, without the prior written consent of The Author. As
// confidential information this source file must be kept fully and
// effectively secure at all times.
//
package com.cilogi.util.services.shorten;
import com.cilogi.util.Secrets;
import com.cilogi.util.WebUtil;
import com.google.common.collect.ImmutableMap;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class ShortenURLBitly extends BaseGen implements IShortenURL {
static final Logger LOG = LoggerFactory.getLogger(ShortenURLBitly.class);
private static final String TOKEN = Secrets.get("shorten2go_bitly");
public ShortenURLBitly() {
super("https://api-ssl.bitly.com/v3/shorten", TOKEN, "cilogi");
}
@Override
JSONObject shortenJSON(String inputURL) throws IOException {
try {
URI uri = buildQueryURI(baseURL, ImmutableMap.<String,String>of(
"tokenName", "apiKey", "token", token, "userName", "login", "user", user
));
String response = WebUtil.getURL(uri.toURL());
try {
return (JSONObject)new JSONParser().parse(response);
} catch (ParseException e) {
return new JSONObject();
}
} catch (URISyntaxException e) {
LOG.warn("Can't create short URL for \"" + inputURL + "\", syntax error: " + e.getMessage());
}
return new JSONObject();
}
@Override
public String shorten(String urlString) {
try {
JSONObject json = cache.get(urlString);
if (json.size() == 0) {
return urlString;
} else {
JSONObject data = (JSONObject)json.get("data");
if (data != null && data.containsKey("url")) {
return (String)data.get("url");
}
}
LOG.warn("No shortening for " + urlString + " with response " + json.toString());
return urlString;
} catch (Exception e) {
throw new ShortenException(e);
}
}
}
| 37.047619 | 106 | 0.625 |
b5e49f82e9555ee875df09ffabb21ce9840eeef3 | 3,706 | /*
* Copyright (c) 2015 Uber Technologies, Inc.
*
* 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.uber.tchannel.messages;
import com.uber.tchannel.api.ResponseCode;
import com.uber.tchannel.headers.ArgScheme;
import io.netty.buffer.ByteBuf;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public final class JsonResponse<T> extends EncodedResponse<T> {
private JsonResponse(Builder<T> builder) {
super(builder);
}
protected JsonResponse(long id, ResponseCode responseCode,
Map<String, String> transportHeaders,
ByteBuf arg2, ByteBuf arg3) {
super(id, responseCode, transportHeaders, arg2, arg3);
}
protected JsonResponse(ErrorResponse error) {
super(error);
}
/**
* @param <T> response body type
*/
public static class Builder<T> extends EncodedResponse.Builder<T> {
public Builder(@NotNull JsonRequest<?> req) {
super(req);
this.argScheme = ArgScheme.JSON;
}
@Override
public @NotNull Builder<T> validate() {
super.validate();
return this;
}
public @NotNull JsonResponse<T> build() {
return new JsonResponse<>(this.validate());
}
@Override
public @NotNull Builder<T> setArg2(ByteBuf arg2) {
super.setArg2(arg2);
return this;
}
@Override
public @NotNull Builder<T> setArg3(ByteBuf arg3) {
super.setArg3(arg3);
return this;
}
@Override
public @NotNull Builder<T> setHeader(String key, String value) {
super.setHeader(key, value);
return this;
}
@Override
public @NotNull Builder<T> setHeaders(Map<String, String> headers) {
super.setHeaders(headers);
return this;
}
@Override
public @NotNull Builder<T> setBody(T body) {
super.setBody(body);
return this;
}
@Override
public @NotNull Builder<T> setTransportHeader(String key, String value) {
super.setTransportHeader(key, value);
return this;
}
@Override
public @NotNull Builder<T> setTransportHeaders(@NotNull Map<String, String> transportHeaders) {
super.setTransportHeaders(transportHeaders);
return this;
}
@Override
public @NotNull Builder<T> setResponseCode(ResponseCode responseCode) {
super.setResponseCode(responseCode);
return this;
}
}
}
| 31.142857 | 103 | 0.635186 |
50af61a98c315736de353faa8feb32c6dfae173e | 12,087 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.04.19 um 09:36:45 AM CEST
//
package de.immobilienscout24.rest.schema.offer.realestates._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.immobilienscout24.rest.schema.common._1.Adapter1;
import de.immobilienscout24.rest.schema.common._1.CourtageInfo;
import de.immobilienscout24.rest.schema.common._1.HouseTypeBuildingType;
import de.immobilienscout24.rest.schema.common._1.HouseTypeConstructionMethodType;
import de.immobilienscout24.rest.schema.common._1.HouseTypeEnergyStandardType;
import de.immobilienscout24.rest.schema.common._1.HouseTypeStageOfCompletionType;
import de.immobilienscout24.rest.schema.common._1.Price;
/**
* Eigenschaften fr den Immobilientyp "Typenhuser"
*
* <p>Java-Klasse fr HouseType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="HouseType">
* <complexContent>
* <extension base="{http://rest.immobilienscout24.de/schema/offer/realestates/1.0}RealEstate">
* <sequence>
* <group ref="{http://rest.immobilienscout24.de/schema/common/1.0}ExtendedHouseTypeGroup"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HouseType", propOrder = {
"price",
"livingSpace",
"totalArea",
"baseArea",
"numberOfRooms",
"courtage",
"constructionMethod",
"buildingType",
"stageOfCompletionType",
"energyStandardType",
"uValue",
"typeInformationNote",
"modelInformationNote",
"contructionPriceInformationNote",
"floorInformationNote",
"roofInformationNote"
})
public class HouseType
extends RealEstate
{
@XmlElement(required = true)
protected Price price;
protected double livingSpace;
protected Double totalArea;
protected Double baseArea;
protected Double numberOfRooms;
protected CourtageInfo courtage;
protected HouseTypeConstructionMethodType constructionMethod;
@XmlElement(required = true)
protected HouseTypeBuildingType buildingType;
protected HouseTypeStageOfCompletionType stageOfCompletionType;
protected HouseTypeEnergyStandardType energyStandardType;
protected Double uValue;
@XmlJavaTypeAdapter(Adapter1 .class)
protected String typeInformationNote;
@XmlJavaTypeAdapter(Adapter1 .class)
protected String modelInformationNote;
@XmlJavaTypeAdapter(Adapter1 .class)
protected String contructionPriceInformationNote;
@XmlJavaTypeAdapter(Adapter1 .class)
protected String floorInformationNote;
@XmlJavaTypeAdapter(Adapter1 .class)
protected String roofInformationNote;
/**
* Ruft den Wert der price-Eigenschaft ab.
*
* @return
* possible object is
* {@link Price }
*
*/
public Price getPrice() {
return price;
}
/**
* Legt den Wert der price-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Price }
*
*/
public void setPrice(Price value) {
this.price = value;
}
/**
* Ruft den Wert der livingSpace-Eigenschaft ab.
*
*/
public double getLivingSpace() {
return livingSpace;
}
/**
* Legt den Wert der livingSpace-Eigenschaft fest.
*
*/
public void setLivingSpace(double value) {
this.livingSpace = value;
}
/**
* Ruft den Wert der totalArea-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getTotalArea() {
return totalArea;
}
/**
* Legt den Wert der totalArea-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setTotalArea(Double value) {
this.totalArea = value;
}
/**
* Ruft den Wert der baseArea-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getBaseArea() {
return baseArea;
}
/**
* Legt den Wert der baseArea-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setBaseArea(Double value) {
this.baseArea = value;
}
/**
* Ruft den Wert der numberOfRooms-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getNumberOfRooms() {
return numberOfRooms;
}
/**
* Legt den Wert der numberOfRooms-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setNumberOfRooms(Double value) {
this.numberOfRooms = value;
}
/**
* Ruft den Wert der courtage-Eigenschaft ab.
*
* @return
* possible object is
* {@link CourtageInfo }
*
*/
public CourtageInfo getCourtage() {
return courtage;
}
/**
* Legt den Wert der courtage-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CourtageInfo }
*
*/
public void setCourtage(CourtageInfo value) {
this.courtage = value;
}
/**
* Ruft den Wert der constructionMethod-Eigenschaft ab.
*
* @return
* possible object is
* {@link HouseTypeConstructionMethodType }
*
*/
public HouseTypeConstructionMethodType getConstructionMethod() {
return constructionMethod;
}
/**
* Legt den Wert der constructionMethod-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link HouseTypeConstructionMethodType }
*
*/
public void setConstructionMethod(HouseTypeConstructionMethodType value) {
this.constructionMethod = value;
}
/**
* Ruft den Wert der buildingType-Eigenschaft ab.
*
* @return
* possible object is
* {@link HouseTypeBuildingType }
*
*/
public HouseTypeBuildingType getBuildingType() {
return buildingType;
}
/**
* Legt den Wert der buildingType-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link HouseTypeBuildingType }
*
*/
public void setBuildingType(HouseTypeBuildingType value) {
this.buildingType = value;
}
/**
* Ruft den Wert der stageOfCompletionType-Eigenschaft ab.
*
* @return
* possible object is
* {@link HouseTypeStageOfCompletionType }
*
*/
public HouseTypeStageOfCompletionType getStageOfCompletionType() {
return stageOfCompletionType;
}
/**
* Legt den Wert der stageOfCompletionType-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link HouseTypeStageOfCompletionType }
*
*/
public void setStageOfCompletionType(HouseTypeStageOfCompletionType value) {
this.stageOfCompletionType = value;
}
/**
* Ruft den Wert der energyStandardType-Eigenschaft ab.
*
* @return
* possible object is
* {@link HouseTypeEnergyStandardType }
*
*/
public HouseTypeEnergyStandardType getEnergyStandardType() {
return energyStandardType;
}
/**
* Legt den Wert der energyStandardType-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link HouseTypeEnergyStandardType }
*
*/
public void setEnergyStandardType(HouseTypeEnergyStandardType value) {
this.energyStandardType = value;
}
/**
* Ruft den Wert der uValue-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getUValue() {
return uValue;
}
/**
* Legt den Wert der uValue-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setUValue(Double value) {
this.uValue = value;
}
/**
* Ruft den Wert der typeInformationNote-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTypeInformationNote() {
return typeInformationNote;
}
/**
* Legt den Wert der typeInformationNote-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTypeInformationNote(String value) {
this.typeInformationNote = value;
}
/**
* Ruft den Wert der modelInformationNote-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModelInformationNote() {
return modelInformationNote;
}
/**
* Legt den Wert der modelInformationNote-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModelInformationNote(String value) {
this.modelInformationNote = value;
}
/**
* Ruft den Wert der contructionPriceInformationNote-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContructionPriceInformationNote() {
return contructionPriceInformationNote;
}
/**
* Legt den Wert der contructionPriceInformationNote-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContructionPriceInformationNote(String value) {
this.contructionPriceInformationNote = value;
}
/**
* Ruft den Wert der floorInformationNote-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFloorInformationNote() {
return floorInformationNote;
}
/**
* Legt den Wert der floorInformationNote-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFloorInformationNote(String value) {
this.floorInformationNote = value;
}
/**
* Ruft den Wert der roofInformationNote-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRoofInformationNote() {
return roofInformationNote;
}
/**
* Legt den Wert der roofInformationNote-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoofInformationNote(String value) {
this.roofInformationNote = value;
}
}
| 25.717021 | 115 | 0.580624 |
f4c411a3a5f4a2f398bc5a5a3508f6dd5d9335c7 | 2,791 | package com.lmax.disruptor.demo;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.demo.consumer.InParkingDataEventDbHandler;
import com.lmax.disruptor.demo.consumer.InParkingDataEventKafkaHandler;
import com.lmax.disruptor.demo.consumer.InParkingDataEventSmsHandler;
import com.lmax.disruptor.demo.publisher.InParkingDataEvent;
import com.lmax.disruptor.demo.publisher.InParkingDataEventFactory;
import com.lmax.disruptor.demo.publisher.InParkingDataEventPublisher;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.EventHandlerGroup;
import com.lmax.disruptor.dsl.ProducerType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 多线程模式
* Created by Lusifer on 2017/5/27.
*/
public final class InParkingMultiDisruptor {
private static Logger logger = LoggerFactory.getLogger(InParkingMultiDisruptor.class);
// 指定 ringBuffer 字节大小, 必须是 2 的倍数
private static final int BUFFER_SIZE = 1024;
private ThreadFactory threadFactory;
private InParkingDataEventFactory factory;
private Disruptor<InParkingDataEvent> disruptor;
private RingBuffer<InParkingDataEvent> ringBuffer;
private InParkingDataEventPublisher publisher;
private InParkingMultiDisruptor() {
// 执行器,用于构造消费者线程
threadFactory = Executors.defaultThreadFactory();
threadFactory = Executors.defaultThreadFactory();
// 指定事件工厂
factory = new InParkingDataEventFactory();
/**
* 多线程模式
* YieldingWaitStrategy 在多次循环尝试不成功后,选择让出CPU,等待下次调。平衡了延迟和CPU资源占用,但延迟也比较均匀
*/
disruptor = new Disruptor<InParkingDataEvent>(factory, BUFFER_SIZE, threadFactory, ProducerType.MULTI, new YieldingWaitStrategy());
// 使用 Disruptor 创建消费者组
EventHandlerGroup<InParkingDataEvent> handlerGroup = disruptor.handleEventsWith(new InParkingDataEventKafkaHandler(), new InParkingDataEventDbHandler());
InParkingDataEventSmsHandler smsHandler = new InParkingDataEventSmsHandler();
// 声明在 C1,C2 完事之后发送短信消息,也就是流程走到 C3
handlerGroup.then(smsHandler);
// 启动 disruptor 线程
disruptor.start();
// 获取 ringBuffer 环,用于接取生产者生产的事件
ringBuffer = disruptor.getRingBuffer();
// 为 ringBuffer 指定事件生产者
publisher = new InParkingDataEventPublisher(ringBuffer);
logger.debug("Created InParkingMultiDisruptor.");
}
public void publish(String carLicense) {
publisher.onData(carLicense);
}
/**
* 服务器关闭时别忘记调用
*/
public void shutdown() {
disruptor.shutdown();
}
/**
* 静态初始化器,由 JVM 来保证线程安全
*/
private static class SingletonHolder {
private static InParkingMultiDisruptor instance = new InParkingMultiDisruptor();
}
public static InParkingMultiDisruptor getInstance() {
return InParkingMultiDisruptor.SingletonHolder.instance;
}
}
| 31.011111 | 155 | 0.799713 |
145c1af6d7de16043ee4d688922736ca8ccb7ec2 | 3,246 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.server.http;
import io.druid.server.coordinator.DruidCoordinator;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.net.URL;
public class CoordinatorRedirectInfoTest
{
private DruidCoordinator druidCoordinator;
private CoordinatorRedirectInfo coordinatorRedirectInfo;
@Before
public void setUp()
{
druidCoordinator = EasyMock.createMock(DruidCoordinator.class);
coordinatorRedirectInfo = new CoordinatorRedirectInfo(druidCoordinator);
}
@Test
public void testDoLocalWhenLeading()
{
EasyMock.expect(druidCoordinator.isLeader()).andReturn(true).anyTimes();
EasyMock.replay(druidCoordinator);
Assert.assertTrue(coordinatorRedirectInfo.doLocal(null));
Assert.assertTrue(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/leader"));
Assert.assertTrue(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/isLeader"));
Assert.assertTrue(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/other/path"));
EasyMock.verify(druidCoordinator);
}
@Test
public void testDoLocalWhenNotLeading()
{
EasyMock.expect(druidCoordinator.isLeader()).andReturn(false).anyTimes();
EasyMock.replay(druidCoordinator);
Assert.assertFalse(coordinatorRedirectInfo.doLocal(null));
Assert.assertTrue(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/leader"));
Assert.assertTrue(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/isLeader"));
Assert.assertFalse(coordinatorRedirectInfo.doLocal("/druid/coordinator/v1/other/path"));
EasyMock.verify(druidCoordinator);
}
@Test
public void testGetRedirectURLNull()
{
EasyMock.expect(druidCoordinator.getCurrentLeader()).andReturn(null).anyTimes();
EasyMock.replay(druidCoordinator);
URL url = coordinatorRedirectInfo.getRedirectURL("http", "query", "/request");
Assert.assertNull(url);
EasyMock.verify(druidCoordinator);
}
@Test
public void testGetRedirectURL()
{
String host = "localhost";
String query = "foo=bar&x=y";
String request = "/request";
EasyMock.expect(druidCoordinator.getCurrentLeader()).andReturn(host).anyTimes();
EasyMock.replay(druidCoordinator);
URL url = coordinatorRedirectInfo.getRedirectURL("http", query, request);
Assert.assertEquals("http://localhost/request?foo=bar&x=y", url.toString());
EasyMock.verify(druidCoordinator);
}
}
| 36.47191 | 92 | 0.761553 |
af98bf7ad0257c19e70b4c266c3543e2fa96884b | 2,165 | package nn;
import lib.StdArrayIO;
import java.util.Arrays;
public class Vec {
public static double sum(double[] x) {
return Arrays.stream(x).sum();
}
public static double norm(double[] x) {
double s = 0.0;
for (int i = 0; i<x.length; i++) {
s += x[i]*x[i];
}
double r = Math.sqrt(s);
return r;
}
public static double[] abs(double[] x) {
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = Math.abs(x[i]);
}
return r;
}
public static double[] exp(double[] x) {
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = Math.exp(x[i]);
}
return r;
}
public static double[] ones(int n) {
double[] r = new double[n];
for (int i = 0; i<n; i++) {
r[i] = 1.0;
}
return r;
}
public static double[] scale(double[] x, double v) {
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = x[i] * v;
}
return r;
}
public static double[] add(double[] x, double[] y) {
if ( x.length!=y.length ) {
throw new IllegalArgumentException("diff vec lens");
}
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = x[i] + y[i];
}
return r;
}
public static double[] add(double[] x, double y) {
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = x[i] + y;
}
return r;
}
public static double[] subtract(double[] x, double[] y) {
if ( x.length!=y.length ) {
throw new IllegalArgumentException("diff vec lens");
}
double[] r = new double[x.length];
for (int i = 0; i<x.length; i++) {
r[i] = x[i] - y[i];
}
return r;
}
public static void main(String[] args) {
/*
31.20000 3.40000 55.00000
-15.60000 1.70000 -27.50000
0.00000 13.40000 -50.00000
-62.40000 -6.60000 50.00000
*/
StdArrayIO.print(abs(new double[]{-31.2, 3.4, -55}));
StdArrayIO.print(scale(new double[]{-31.2, 3.4, -55}, 0.5));
StdArrayIO.print(add(new double[]{-31.2, 3.4, -55},
new double[]{31.2, 10, 5}));
StdArrayIO.print(subtract(new double[]{-31.2, 3.4, 55},
new double[]{31.2, 10, 5}));
}
}
| 22.091837 | 62 | 0.550577 |
77dd33457ddc25e0cceaf5473ed97df2b3150330 | 2,570 | package ua.restaurant.utils;
import ua.restaurant.dto.CategoryDTO;
import ua.restaurant.dto.DishDTO;
import ua.restaurant.entity.Baskets;
import ua.restaurant.entity.Categories;
import ua.restaurant.entity.Dishes;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Converts entities to DTO objects
*/
public class Mapper {
private static DishDTO dishDTOMapper(Dishes d) {
return DishDTO.builder()
.id(d.getId())
.price(d.getPrice())
.name(ContextHelpers.isLocaleEnglish()
? d.getNameEn()
: d.getNameUa())
.category(categoryDTOMapper(d.getCategories()))
.build();
}
private static CategoryDTO categoryDTOMapper(Categories c) {
return CategoryDTO.builder()
.id(c.getId())
.category(ContextHelpers.isLocaleEnglish()
? c.getCategoryEn()
: c.getCategoryUa())
.build();
}
public static List<DishDTO> dishesToDishesDTO(List<Dishes> list) {
return list.stream()
.map(Mapper::dishDTOMapper)
.collect(Collectors.toList());
}
public static List<DishDTO> basketToDishesDTO(List<Baskets> list) {
return list.stream()
.map(Baskets::getDishes)
.map(Mapper::dishDTOMapper)
.collect(Collectors.toList());
}
public static BigDecimal getTotalPrice(List<DishDTO> dishes) {
return dishes.stream()
.map(DishDTO::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public static List<CategoryDTO> categoriesToCategoriesDTO(List<Categories> list) {
return list.stream()
.map(Mapper::categoryDTOMapper)
.collect(Collectors.toList());
}
public static List<CategoryDTO> dishesToCategoriesDTO(List<Dishes> list) {
return list.stream()
.filter(distinctByKey(Dishes::getCategories))
.map(d -> categoryDTOMapper(d.getCategories()))
.collect(Collectors.toList());
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
| 32.531646 | 87 | 0.607393 |
e68963960748c0cc772a6b586fc93dd6cf0b203a | 1,012 | package com.ttdt.modle;
/**
* Created by Administrator on 2017/10/8.
*/
public class LeftMenu {
private String text;
private String imageUrl;
private int image;
public LeftMenu() {
}
public LeftMenu(String text, int image) {
this.text = text;
this.image = image;
}
public LeftMenu(String text, String imageUrl) {
this.text = text;
this.imageUrl = imageUrl;
}
public LeftMenu(String text, String imageUrl, int image) {
this.text = text;
this.imageUrl = imageUrl;
this.image = image;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
| 17.152542 | 62 | 0.577075 |
3d5e2f6f3ef30b2bf0c58be692cd2631e6f9555e | 306 | package cn.emay.utils.string;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Frank
*/
public class StringUtilsTest {
@Test
public void test() {
Assert.assertTrue(StringUtils.isBool("true"));
Assert.assertFalse(StringUtils.isBool("1"));
}
}
| 17 | 55 | 0.617647 |
4d6f7af56f7a95ede95d6651f3851b1069326772 | 12,778 | /*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* MIT License
*
* 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.microsoft.azuretools.azureexplorer.forms;
import java.net.URL;
import java.util.Arrays;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.HelpEvent;
import org.eclipse.swt.events.HelpListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import com.microsoft.azure.hdinsight.common.mvc.SettableControl;
import com.microsoft.azure.hdinsight.serverexplore.AddNewClusterCtrlProvider;
import com.microsoft.azure.hdinsight.serverexplore.AddNewClusterModel;
import com.microsoft.azure.hdinsight.serverexplore.hdinsightnode.HDInsightRootModule;
import com.microsoft.azuretools.azurecommons.helpers.NotNull;
import com.microsoft.azuretools.azurecommons.helpers.Nullable;
import com.microsoft.azuretools.azureexplorer.Activator;
import com.microsoft.azuretools.core.components.AzureTitleAreaDialogWrapper;
import com.microsoft.azuretools.core.rxjava.EclipseSchedulers;
import com.microsoft.azuretools.core.utils.Messages;
import com.microsoft.azuretools.telemetry.AppInsightsClient;
public class AddNewClusterForm extends AzureTitleAreaDialogWrapper implements SettableControl<AddNewClusterModel> {
@NotNull
private AddNewClusterCtrlProvider ctrlProvider;
protected Text clusterNameField;
private Text userNameField;
private Text storageNameField;
private Text storageKeyField;
private Combo containersComboBox;
private Text passwordField;
@Nullable
private HDInsightRootModule hdInsightModule;
private Label clusterNameLabel;
private Label userNameLabel;
private Label passwordLabel;
public AddNewClusterForm(Shell parentShell, @Nullable HDInsightRootModule module) {
super(parentShell);
// enable help button
setHelpAvailable(true);
this.hdInsightModule = module;
this.ctrlProvider = new AddNewClusterCtrlProvider(this, new EclipseSchedulers(Activator.PLUGIN_ID));
}
private void refreshContainers() {
ctrlProvider.refreshContainers()
.subscribe();
}
protected void customizeUI() {
}
@Override
protected Control createDialogArea(Composite parent) {
setTitle("Link New HDInsight Cluster");
setMessage("Please enter HDInsight Cluster details");
Composite container = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
container.setLayout(gridLayout);
GridData gridData = new GridData();
gridData.widthHint = 350;
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
container.setLayoutData(gridData);
clusterNameLabel = new Label(container, SWT.LEFT);
clusterNameLabel.setText("Cluster Name:");
gridData = new GridData();
gridData.horizontalIndent = 30;
gridData.horizontalAlignment = SWT.RIGHT;
clusterNameLabel.setLayoutData(gridData);
clusterNameField = new Text(container, SWT.BORDER);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
clusterNameField.setLayoutData(gridData);
clusterNameField.setToolTipText("The HDInsight cluster name, such as 'mycluster' of cluster URL 'mycluster.azurehdinsight.net'.\n\n Press the F1 key or click the '?'(Help) button to get more details.");
Group clusterAccountGroup = new Group(container, SWT.NONE);
clusterAccountGroup.setText("The Cluster Account");
gridLayout = new GridLayout();
gridLayout.numColumns = 2;
clusterAccountGroup.setLayout(gridLayout);
gridData = new GridData();
gridData.horizontalSpan = 2;
gridData.widthHint = 350;
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
clusterAccountGroup.setLayoutData(gridData);
userNameLabel = new Label(clusterAccountGroup, SWT.LEFT);
userNameLabel.setText("User Name:");
gridData = new GridData();
gridData.horizontalIndent = 38;
gridData.horizontalAlignment = SWT.RIGHT;
userNameLabel.setLayoutData(gridData);
userNameField = new Text(clusterAccountGroup, SWT.BORDER);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
userNameField.setLayoutData(gridData);
userNameField.setToolTipText("The user name of the HDInsight cluster.\n\n Press the F1 key or click the '?'(Help) button to get more details.");
passwordLabel = new Label(clusterAccountGroup, SWT.LEFT);
passwordLabel.setText("Password:");
gridData = new GridData();
gridData.horizontalIndent = 38;
gridData.horizontalAlignment = SWT.RIGHT;
passwordLabel.setLayoutData(gridData);
passwordField = new Text(clusterAccountGroup, SWT.PASSWORD | SWT.BORDER);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
passwordField.setLayoutData(gridData);
passwordField.setToolTipText("The password of the HDInsight cluster user provided.\n\n Press the F1 key or click the '?'(Help) button to get more details.");
Group clusterStorageGroup = new Group(container, SWT.NONE);
clusterStorageGroup.setText("The Cluster Storage Information (Optional)");
clusterStorageGroup.setToolTipText("The Cluster Storage Information provided can enable the Storage Explorer support in the left tree view.");
gridLayout = new GridLayout();
gridLayout.numColumns = 2;
clusterStorageGroup.setLayout(gridLayout);
gridData = new GridData();
gridData.horizontalSpan = 2;
gridData.widthHint = 350;
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
clusterStorageGroup.setLayoutData(gridData);
Label storageNameLabel = new Label(clusterStorageGroup, SWT.LEFT);
storageNameLabel.setText("Storage Account:");
gridData = new GridData();
gridData.horizontalAlignment = SWT.RIGHT;
storageNameLabel.setLayoutData(gridData);
storageNameField = new Text(clusterStorageGroup, SWT.BORDER);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
storageNameField.setLayoutData(gridData);
storageNameField.setToolTipText("The default storage account of the HDInsight cluster, which can be found from HDInsight cluster properties of Azure portal.\n\n Press the F1 key or click the '?'(Help) button to get more details");
Label storageKeyLabel = new Label(clusterStorageGroup, SWT.LEFT);
storageKeyLabel.setText("Storage Key:");
gridData = new GridData();
gridData.horizontalAlignment = SWT.RIGHT;
storageKeyLabel.setLayoutData(gridData);
storageKeyField = new Text(clusterStorageGroup, SWT.BORDER | SWT.WRAP);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.heightHint = 4 * storageKeyField.getLineHeight();
storageKeyField.setLayoutData(gridData);
storageKeyField.setToolTipText("The storage key of the default storage account, which can be found from HDInsight cluster storage accounts of Azure portal.\n\n Press the F1 key or click the '?'(Help) button to get more details.");
storageNameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
refreshContainers();
}
});
storageKeyField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
refreshContainers();
}
});
Label storageContainerLabel = new Label(clusterStorageGroup, SWT.LEFT);
storageContainerLabel.setText("Storage Container:");
gridData = new GridData();
gridData.horizontalAlignment = SWT.RIGHT;
storageContainerLabel.setLayoutData(gridData);
containersComboBox = new Combo(clusterStorageGroup, SWT.DROP_DOWN | SWT.BORDER);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
containersComboBox.setLayoutData(gridData);
container.addHelpListener(new HelpListener() {
@Override public void helpRequested(HelpEvent e) {
try {
IWebBrowser webBrowser = PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser();
if (webBrowser != null)
webBrowser.openURL(new URL("https://go.microsoft.com/fwlink/?linkid=866472"));
} catch (Exception ignored) {
}
}
});
customizeUI();
return container;
}
protected void afterOkActionPerformed() {
if (hdInsightModule != null) {
hdInsightModule.load(false);
}
}
@Override
protected void okPressed() {
ctrlProvider.validateAndAdd()
.subscribe(toUpdate -> {
afterOkActionPerformed();
AppInsightsClient.create(Messages.HDInsightAddNewClusterAction, null);
super.okPressed();
});
}
@Override
public void getData(AddNewClusterModel data) {
// Components -> Data
data.setClusterName(clusterNameField.getText()).setClusterNameLabelTitle(clusterNameLabel.getText())
.setUserName(userNameField.getText()).setUserNameLabelTitle(userNameLabel.getText())
.setPassword(passwordField.getText()).setPasswordLabelTitle(passwordLabel.getText())
.setStorageName(storageNameField.getText()).setStorageKey(storageKeyField.getText())
.setErrorMessage(getErrorMessage()).setSelectedContainerIndex(containersComboBox.getSelectionIndex())
.setContainers(Arrays.asList(containersComboBox.getItems()));
}
@Override
public void setData(AddNewClusterModel data) {
// Data -> Components
// Text fields
clusterNameField.setText(data.getClusterName());
clusterNameLabel.setText(data.getClusterNameLabelTitle());
userNameField.setText(data.getUserName());
userNameLabel.setText(data.getUserNameLabelTitle());
passwordField.setText(data.getPassword());
passwordLabel.setText(data.getPasswordLabelTitle());
storageNameField.setText(data.getStorageName());
storageKeyField.setText(data.getStorageKey());
setErrorMessage(data.getErrorMessage());
// Combo box
containersComboBox.removeAll();
data.getContainers().forEach(containersComboBox::add);
containersComboBox.select(data.getSelectedContainerIndex());
// Resize layout
getShell().layout(true, true);
}
}
| 44.368056 | 238 | 0.703788 |
c5f0d08a5a0bda1e2d0a660ddf62efffcc9741a3 | 706 | package com.meiya.nio2;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
/**
* 创建目录,要求path中所有的名字元素都存在,如果不是会得到IOException
*/
public class TestNine {
private static String home = System.getProperty("user.home");
public static void main(String[] args) throws IOException {
String dirName = "myDir_" + UUID.randomUUID().toString();
Path path = Paths.get("d:" + File.separator + dirName);
if (!Files.exists(path)) {
Files.createDirectory(path);
}
System.out.println(Files.exists(path));
}
}
| 10.085714 | 65 | 0.628895 |
e0ec202f5cb99923e955de843cfc2476ba940749 | 552 | package org.pjp.cag.instruction.group4;
import static org.junit.Assert.assertEquals;
import static org.pjp.cag.cpu.Store.ZERO;
import org.junit.Test;
import org.pjp.cag.cpu.Store;
import org.pjp.cag.test.TestConstants;
public class ARCTest {
@Test
public void testExecute() {
Store store = new Store();
store.accumulator().set(1);
ARC instruction = new ARC(false, ZERO, ZERO);
instruction.execute(store);
assertEquals((float) Math.atan(1), store.accumulator().get(), TestConstants.DELTA);
}
}
| 23 | 91 | 0.682971 |
e57925329e5f750d90dde75038b435740300d621 | 1,124 | package com.eaglesakura.sloth.persistence;
import com.eaglesakura.util.ThrowableRunnable;
import com.eaglesakura.util.ThrowableRunner;
import android.arch.persistence.room.RoomDatabase;
import java.io.Closeable;
/**
* 設計上の注意点:
* {@link android.arch.persistence.room.Query} に対して "AS"文を含めるとビルドが終了しない不具合がある(alpha1)
*/
public abstract class SlothRoomDatabase extends RoomDatabase {
/**
* try-with-resourceで使用するためのClosableを生成する
* 実際のOpenは自動的に行われるが、try(Closable token = db.open()){...} とすることでcloseされることが明示されるめ。
*/
public Closeable open() {
return () -> this.close();
}
/**
* 戻り値と例外を許容してトランザクション実行を行う
*/
public <RetType, ErrType extends Exception> RetType runInTx(ThrowableRunnable<RetType, ErrType> runnable) throws ErrType {
ThrowableRunner<RetType, ErrType> runner = new ThrowableRunner<>(runnable);
try {
beginTransaction();
runner.run();
RetType result = runner.getOrThrow();
setTransactionSuccessful();
return result;
} finally {
endTransaction();
}
}
}
| 27.414634 | 126 | 0.662811 |
6526a59002aac4ee372a50c5cb448fbf3f211284 | 306 | package net.spy.memcached.collection;
/**
* A type component for "bop smgetmode"
*/
public enum SMGetMode {
UNIQUE("unique"),
DUPLICATE("duplicate");
private String mode;
SMGetMode(String mode) {
this.mode = mode;
}
public String getMode() {
return mode;
}
}
| 15.3 | 40 | 0.611111 |
6de76fc7d2f7ef85e231481b571a3f60dade26e5 | 6,251 | package com.svega.vanitygen;
import com.svega.common.math.UInt8;
import com.svega.common.version.Version;
import com.svega.moneroutils.Base58;
import com.svega.moneroutils.addresses.MainAddress;
import com.svega.vanitygen.fxmls.LaunchPage;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import kotlin.text.Regex;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class MoneroVanityGenMain extends Application {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((a, b) -> {
if(b instanceof ThreadDeath)
return;
System.out.println("Thread "+a.getName());
b.printStackTrace();
File errFile = new File("err.txt");
int cnt = 0;
while(errFile.exists() && cnt < 256){
errFile = new File("err"+(cnt++)+".txt");
}
try (PrintWriter pw = new PrintWriter(new FileWriter(errFile))){
b.printStackTrace(pw);
pw.flush();
} catch (IOException ignored) {}
});
if(args.length == 0)
launch(args);
else {
Scanner in = null;
char read = 'y';
if(System.console() != null){
in = new Scanner(System.in);
System.out.printf("Matching %s, is this okay? (y/n): ", args[0]);
read = in.next().charAt(0);
while(!isYN(read)){
System.out.print("\nInvalid character. Proceed? (y/n): ");
read = in.next().charAt(0);
}
}
if(read == 'y')
VanityGenMain.INSTANCE.cliVanityAddress(args[0], in);
else
System.out.println("Not starting the instance.");
System.exit(0);
}
}
public static long getComplexity(String text) {
if(text.isEmpty())
return 1;
ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes());
char read;
boolean open = false;
ArrayList<Regex> regexes = new ArrayList<>();
String temp = "";
while ((read = (char) bais.read()) != 65535) {
switch (read) {
case '[':
if(open)
return -1;
open = true;
temp = "[";
break;
case ']':
if(!open)
return -2;
open = false;
temp += read;
regexes.add(new Regex(temp));
break;
default:
if (open)
temp += read;
else
regexes.add(new Regex(String.valueOf(read)));
}
}
double pass = 0;
for (String s : validSeconds) {
if (regexes.get(0).matches(s))
++pass;
}
if(pass == 0)
return -3;
double diff = validSeconds.length / pass;
for (Regex r : regexes.subList(1, regexes.size())){
pass = 0;
for (String s : validOthers) {
if (r.matches(s))
++pass;
}
if(pass == 0)
return -4;
diff *= (validOthers.length / pass);
}
StringBuilder full = new StringBuilder("4");
if(!checkRecursive(regexes, full, 0)) return -5;
return (long)diff;
}
private static String[] validSeconds = "123456789AB".split("(?!^)");
private static String[] validOthers = Base58.INSTANCE.getAlphabetStr().split("(?!^)");
private static boolean checkRecursive(ArrayList<Regex> regexes, StringBuilder full, int s) {
Regex current = regexes.get(s);
if(s == 0){
for (String sd : validSeconds) {
if (current.matches(sd)) {
if(s == regexes.size() - 1) {
boolean res2 = attemptDecode(full);
if (res2)
return true;
}else{
return checkRecursive(regexes, full.append(sd), ++s);
}
}
}
}else{
for (String sd : validOthers) {
if (current.matches(sd)) {
if(s == regexes.size() - 1) {
boolean res2 = attemptDecode(full);
if (res2)
return true;
}else{
return checkRecursive(regexes, full.append(sd), ++s);
}
}
}
}
return false;
}
private static boolean attemptDecode(StringBuilder full) {
int oLen = full.length();
while(full.length() != 95) full.append("1");
try{
UInt8[] res = Base58.INSTANCE.decode(full.toString());
if(res.length != 69)
return false;
}catch (Exception e){
while(oLen != full.length()) full.deleteCharAt(full.length() - 1);
return false;
}
return true;
}
public static boolean isYN(char yn){
return yn == 'y' || yn == 'n';
}
@Override
public void start(Stage stage) {
Parent root = null;
try{
InputStream in = getClass().getResourceAsStream("/com/svega/vanitygen/fxmls/LaunchPage.fxml");
root = new FXMLLoader().load(in);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "There was an error loading the application: "+e.getMessage());
e.printStackTrace();
System.exit(-1);
}
Scene scene = new Scene(root, 1280, 480);
stage.setTitle("Monero Vanity Address Generator");
stage.setScene(scene);
stage.show();
}
@Override
public void stop(){
System.out.println("Stage is closing");
LaunchPage.stopAll();
}
}
| 33.25 | 111 | 0.484243 |
cb8f68f6e9b2c90c471fb554736b0332d09091b6 | 1,120 | /**
* @FileName : PPRuleGetConditionJsonParser.java
* @Project : Presence Pro
* @Copyright : Copyright (c) 2016 People Power Company. All rights reserved.
*/
package com.peoplepowerco.virtuoso.parser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.peoplepowerco.virtuoso.models.rules.PPRuleGetPhrasesModel;
public class PPRuleGetConditionJsonParser implements PPBaseJsonParser {
@SuppressWarnings("unchecked")
@Override
public boolean setData(JSONObject jso, Object[] obj) {
PPRuleGetPhrasesModel getPhrasesModel = (PPRuleGetPhrasesModel) obj[0];
try{
PPRuleGetPhrasesModel response = JSON.parseObject(jso.toString(), PPRuleGetPhrasesModel.class);
if(response == null) {
return false;
}
getPhrasesModel.setTriggers(response.getTriggers());
getPhrasesModel.setStates(response.getStates());
getPhrasesModel.setActions(response.getActions());
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
catch (OutOfMemoryError ex)
{
Runtime.getRuntime().gc();
}
return false;
}
}
| 26.046512 | 107 | 0.723214 |
f65f801acb41c04d949f6cc0683e621a78363a2c | 899 | package todo.spark.transformer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.orientechnologies.orient.core.id.ORID;
import spark.ResponseTransformer;
/**
* @author [email protected]
*/
@Singleton
public class JsonTransformer implements ResponseTransformer {
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(ORID.class, new ORIDAdapter())
.create();
@Inject
private JsonTransformer() {}
@Override
public String render(final Object obj) throws Exception {
return toJson(obj);
}
public static String toJson(final Object obj) {
return GSON.toJson(obj);
}
public static <T> T fromJson(final String string, final Class<T> clazz) {
return GSON.fromJson(string, clazz);
}
}
| 24.972222 | 77 | 0.704116 |
10732385235f823436a4cb5363515e43ae179eca | 14,111 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.siddhi.extension.execution.time;
import io.siddhi.annotation.Example;
import io.siddhi.annotation.Extension;
import io.siddhi.annotation.Parameter;
import io.siddhi.annotation.ParameterOverload;
import io.siddhi.annotation.ReturnAttribute;
import io.siddhi.annotation.util.DataType;
import io.siddhi.core.config.SiddhiQueryContext;
import io.siddhi.core.exception.SiddhiAppRuntimeException;
import io.siddhi.core.executor.ConstantExpressionExecutor;
import io.siddhi.core.executor.ExpressionExecutor;
import io.siddhi.core.executor.function.FunctionExecutor;
import io.siddhi.core.util.config.ConfigReader;
import io.siddhi.core.util.snapshot.state.State;
import io.siddhi.core.util.snapshot.state.StateFactory;
import io.siddhi.extension.execution.time.util.TimeExtensionConstants;
import io.siddhi.query.api.definition.Attribute;
import io.siddhi.query.api.exception.SiddhiAppValidationException;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* extract(unit,dateValue,dateFormat)/extract(unit,dateValue,dateFormat,locale)/extract(unit,dateValue)
* /extract(timestampInMilliseconds,unit)/extract(timestampInMilliseconds,unit,locale)
* Returns date attributes from a date expression.
* dateValue - value of date. eg: "2014-11-11 13:23:44.657", "2014-11-11" , "13:23:44.657"
* unit - Which part of the date format you want to manipulate. eg: "MINUTE" , "HOUR" , "MONTH" , "YEAR" , "QUARTER" ,
* "WEEK" , "DAY" , "SECOND"
* dateFormat - Date format of the provided date value. eg: yyyy-MM-dd HH:mm:ss.SSS
* timestampInMilliseconds - date value in milliseconds.(from the epoch) eg: 1415712224000L
* locale - optional parameter which represents a specific geographical, political or cultural region.
* eg: "en_US", "fr_FR"
* Accept Type(s) for extract(unit,dateValue,dateFormat):
* unit : STRING
* dateValue : STRING
* dateFormat : STRING
* Accept Type(s) for extract(timestampInMilliseconds,unit):
* timestampInMilliseconds : LONG
* unit : STRING
* Return Type(s): INT
*/
/**
* Class representing the Time extract implementation.
*/
@Extension(
name = "extract",
namespace = "time",
description = "Function extracts a date unit from the date.",
parameters = {
@Parameter(name = "unit",
description = "This is the part of the date that needs to be modified. " +
"For example, `MINUTE`, `HOUR`, `MONTH`, `YEAR`, `QUARTER`," +
" `WEEK`, `DAY`, `SECOND`.",
type = {DataType.STRING}),
@Parameter(name = "date.value",
description = "The value of the date. " +
"For example, `2014-11-11 13:23:44.657`, `2014-11-11`, " +
"`13:23:44.657`.",
type = {DataType.STRING},
dynamic = true,
optional = true,
defaultValue = "-"),
@Parameter(name = "date.format",
description = "The format of the date value provided. " +
"For example, `yyyy-MM-dd HH:mm:ss.SSS`.",
type = {DataType.STRING},
dynamic = true,
optional = true,
defaultValue = "`yyyy-MM-dd HH:mm:ss.SSS`"),
@Parameter(name = "timestamp.in.milliseconds",
description = "The date value in milliseconds. For example, `1415712224000L`.",
type = {DataType.LONG},
dynamic = true,
optional = true,
defaultValue = "-"),
@Parameter(name = "locale",
description = "Represents a specific geographical, political or cultural region. " +
"For example `en_US` and `fr_FR`",
type = {DataType.STRING},
optional = true,
defaultValue = "Current default locale set in the Java Virtual Machine.")
},
parameterOverloads = {
@ParameterOverload(parameterNames = {"unit", "date.value"}),
@ParameterOverload(parameterNames = {"unit", "date.value", "date.format"}),
@ParameterOverload(parameterNames = {"unit", "date.value", "date.format", "locale"}),
@ParameterOverload(parameterNames = {"timestamp.in.milliseconds", "unit"}),
@ParameterOverload(parameterNames = {"timestamp.in.milliseconds", "unit", "locale"})
},
returnAttributes = @ReturnAttribute(
description = "Returns the extracted data unit value.",
type = {DataType.INT}),
examples = {
@Example(
syntax = "time:extract('YEAR', '2019/11/11 13:23:44.657', 'yyyy/MM/dd HH:mm:ss.SSS')",
description = "Extracts the year amount and returns `2019`."
),
@Example(
syntax = "time:extract('DAY', '2019-11-12 13:23:44.657')",
description = "Extracts the day amount and returns `12`."
),
@Example(
syntax = "time:extract(1394556804000L, 'HOUR')",
description = "Extracts the hour amount and returns `22`."
)
}
)
public class ExtractAttributesFunctionExtension extends FunctionExecutor {
private Attribute.Type returnType = Attribute.Type.INT;
private boolean useDefaultDateFormat = false;
private String dateFormat = null;
private Calendar cal = Calendar.getInstance();
private String unit = null;
private boolean isLocaleDefined = false;
private boolean useTimestampInMilliseconds = false;
private Locale locale = null;
@Override
protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors,
ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) {
if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.LONG && attributeExpressionExecutors
.length == 2) {
useDefaultDateFormat = true;
dateFormat = TimeExtensionConstants.EXTENSION_TIME_DEFAULT_DATE_FORMAT;
}
if (attributeExpressionExecutors.length == 4) {
locale = LocaleUtils.toLocale((String) ((ConstantExpressionExecutor)
attributeExpressionExecutors[3]).getValue());
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0])
.getValue()).toUpperCase(Locale.getDefault());
} else if (attributeExpressionExecutors.length == 3) {
if (attributeExpressionExecutors[0].getReturnType() == Attribute.Type.LONG) {
useTimestampInMilliseconds = true;
locale = LocaleUtils.toLocale((String) ((ConstantExpressionExecutor)
attributeExpressionExecutors[2]).getValue());
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()).
toUpperCase(Locale.getDefault());
} else {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue()).
toUpperCase(Locale.getDefault());
}
} else if (attributeExpressionExecutors.length == 2) {
if (useDefaultDateFormat) {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue()).
toUpperCase(Locale.getDefault());
} else {
unit = ((String) ((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()).
toUpperCase(Locale.getDefault());
}
} else {
throw new SiddhiAppValidationException("Invalid no of arguments passed to time:extract() function, " +
"required 2 or 3, but found " +
attributeExpressionExecutors.length);
}
if (locale != null) {
isLocaleDefined = true;
cal = Calendar.getInstance(locale);
} else {
cal = Calendar.getInstance();
}
return null;
}
@Override
protected Object execute(Object[] data, State state) {
String source = null;
if ((data.length == 3 || data.length == 4 || useDefaultDateFormat) && !useTimestampInMilliseconds) {
try {
if (data[1] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Second " +
"argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Second " +
"argument cannot be null");
}
}
if (!useDefaultDateFormat) {
if (data[2] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat, locale) function" + ". Third " +
"argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(unit,dateValue," +
"dateFormat) function" + ". Third " +
"argument cannot be null");
}
}
dateFormat = (String) data[2];
}
FastDateFormat userSpecificFormat;
source = (String) data[1];
userSpecificFormat = FastDateFormat.getInstance(dateFormat);
Date userSpecifiedDate = userSpecificFormat.parse(source);
cal.setTime(userSpecifiedDate);
} catch (ParseException e) {
String errorMsg = "Provided format " + dateFormat + " does not match with the timestamp " + source +
". " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
} catch (ClassCastException e) {
String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
}
} else {
if (data[0] == null) {
if (isLocaleDefined) {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(timestampInMilliseconds," +
"unit, locale) function" + ". First " + "argument cannot be null");
} else {
throw new SiddhiAppRuntimeException("Invalid input given to time:extract(timestampInMilliseconds," +
"unit) function" + ". First " + "argument cannot be null");
}
}
try {
long millis = (Long) data[0];
cal.setTimeInMillis(millis);
} catch (ClassCastException e) {
String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage();
throw new SiddhiAppRuntimeException(errorMsg, e);
}
}
int returnValue = 0;
if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_YEAR)) {
returnValue = cal.get(Calendar.YEAR);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_MONTH)) {
returnValue = (cal.get(Calendar.MONTH) + 1);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_SECOND)) {
returnValue = cal.get(Calendar.SECOND);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_MINUTE)) {
returnValue = cal.get(Calendar.MINUTE);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_HOUR)) {
returnValue = cal.get(Calendar.HOUR_OF_DAY);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_DAY)) {
returnValue = cal.get(Calendar.DAY_OF_MONTH);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_WEEK)) {
returnValue = cal.get(Calendar.WEEK_OF_YEAR);
} else if (unit.equals(TimeExtensionConstants.EXTENSION_TIME_UNIT_QUARTER)) {
returnValue = (cal.get(Calendar.MONTH) / 3) + 1;
}
return returnValue;
}
@Override
protected Object execute(Object data, State state) {
return null;
}
@Override
public Attribute.Type getReturnType() {
return returnType;
}
}
| 47.672297 | 120 | 0.581249 |
188a67377387cf2525e274c50356508088538537 | 7,825 | /*
* Copyright (C) 2018 The Sylph Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.harbby.sylph.spi.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.harbby.gadtry.base.Platform;
import com.github.harbby.gadtry.collection.MutableMap;
import com.github.harbby.gadtry.ioc.IocFactory;
import com.github.harbby.gadtry.spi.VolatileClassLoader;
import com.github.harbby.sylph.api.Operator;
import com.github.harbby.sylph.api.PluginConfig;
import com.github.harbby.sylph.api.annotation.Description;
import com.github.harbby.sylph.api.annotation.Name;
import com.github.harbby.sylph.spi.CompileJobException;
import com.github.harbby.sylph.spi.job.JobEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.github.harbby.gadtry.base.MoreObjects.checkState;
public class PluginFactory
{
private static final Logger logger = LoggerFactory.getLogger(PluginFactory.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private PluginFactory() {}
public static boolean analyzePlugin(Class<? extends Operator> operatorClass, JobEngine jobEngine)
{
List<Class<?>> keywords = jobEngine.keywords();
VolatileClassLoader volatileClassLoader = (VolatileClassLoader) operatorClass.getClassLoader();
volatileClassLoader.setSpiClassLoader(jobEngine.getClass().getClassLoader());
try {
Type[] types = operatorClass.getGenericInterfaces();
boolean isSupportOperator = keywords.contains(
((ParameterizedType) ((ParameterizedType) types[0]).getActualTypeArguments()[0]).getRawType());
return isSupportOperator;
}
catch (TypeNotPresentException e) {
return false;
}
}
public static <T extends PluginConfig> T createPluginConfig(Class<T> type, Map<String, Object> config)
throws Exception
{
T pluginConfig = pluginConfigInstance(type);
//--- inject map config
injectConfig(pluginConfig, config);
return pluginConfig;
}
public static <T extends PluginConfig> T pluginConfigInstance(Class<T> type)
throws IllegalAccessException, InvocationTargetException, InstantiationException
{
checkState(!Modifier.isAbstract(type.getModifiers()), "%s is Interface or Abstract, unable to inject", type);
//Ignore the constructor in the configuration class
try {
Constructor<? extends T> pluginConfigConstructor = type.getDeclaredConstructor();
logger.debug("find 'no parameter' constructor with [{}]", type);
pluginConfigConstructor.setAccessible(true);
return pluginConfigConstructor.newInstance();
}
catch (NoSuchMethodException e) {
logger.warn("Not find 'no parameter' constructor, use javassist inject with [{}]", type);
// copy proxyConfig field value to pluginConfig ...
return Platform.allocateInstance2(type);
}
}
@SuppressWarnings("unchecked")
public static <T extends PluginConfig> void injectConfig(T pluginConfig, Map<String, Object> config)
throws IllegalAccessException, NoSuchFieldException
{
Map<String, Object> otherConfig = new HashMap<>(config);
otherConfig.remove("type");
Class<?> typeClass = pluginConfig.getClass();
for (Field field : typeClass.getDeclaredFields()) {
Name name = field.getAnnotation(Name.class);
if (name != null) {
field.setAccessible(true);
Object value = otherConfig.remove(name.value());
if (value != null) {
field.set(pluginConfig, MAPPER.convertValue(value, field.getType()));
}
else if (field.get(pluginConfig) == null) {
// Unable to inject via config, and there is no default value
logger.info("[PluginConfig] {} field {}[{}] unable to inject ,and there is no default value, config only {}", typeClass, field.getName(), name.value(), config);
}
}
}
Field field = PluginConfig.class.getDeclaredField("otherConfig");
field.setAccessible(true);
((Map<String, Object>) field.get(pluginConfig)).putAll(otherConfig);
logger.info("inject pluginConfig Class [{}], outObj is {}", typeClass, pluginConfig);
}
public static List<Map<String, Object>> getPluginConfigDefaultValues(Class<? extends PluginConfig> configClass)
throws InvocationTargetException, InstantiationException, IllegalAccessException
{
PluginConfig pluginConfig = pluginConfigInstance(configClass);
List<Map<String, Object>> mapList = new ArrayList<>();
for (Field field : configClass.getDeclaredFields()) {
Name name = field.getAnnotation(Name.class);
if (name == null) {
continue;
}
Description description = field.getAnnotation(Description.class);
field.setAccessible(true);
Object defaultValue = field.get(pluginConfig);
Map<String, Object> fieldConfig = MutableMap.of(
"key", name.value(),
"description", description == null ? "" : description.value(),
"default", defaultValue == null ? "" : defaultValue);
mapList.add(fieldConfig);
}
return mapList;
}
public static <T> T getPluginInstance(IocFactory iocFactory, Class<T> driver, Map<String, Object> config)
{
Constructor<?>[] constructors = driver.getConstructors();
if (constructors.length == 0) {
throw new CompileJobException("plugin " + driver + " not found public Constructor");
}
Constructor<T> constructor = (Constructor<T>) constructors[0];
Object[] values = new Object[constructor.getParameterCount()];
int i = 0;
for (Class<?> aClass : constructor.getParameterTypes()) {
if (PluginConfig.class.isAssignableFrom(aClass)) { //config injection
try {
values[i++] = PluginFactory.createPluginConfig(aClass.asSubclass(PluginConfig.class), config);
}
catch (Exception e) {
throw new CompileJobException("config inject failed", e);
}
}
else {
values[i++] = iocFactory.getInstance(aClass);
}
}
try {
return constructor.newInstance(values);
}
catch (InstantiationException | IllegalAccessException e) {
throw new CompileJobException("instance plugin " + driver + "failed", e);
}
catch (InvocationTargetException e) {
throw new CompileJobException("instance plugin " + driver + "failed", e.getTargetException());
}
}
}
| 42.994505 | 180 | 0.65508 |
2ae2c673d17e384892dec897bb3abb19e3b393c4 | 254 | package dev.exception;
public class CollegueNonTrouveException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param arg0
*/
public CollegueNonTrouveException(String message) {
super(message);
}
} | 14.111111 | 59 | 0.700787 |
5db66133abacfde45960000d75a9692661782c6a | 549 | package pl.entpoint.harmony.service.settings.dayOff;
import java.time.LocalDate;
import java.util.List;
import pl.entpoint.harmony.entity.pojo.controller.DayOffPojo;
import pl.entpoint.harmony.entity.settings.DayOff;
/**
* @author Mateusz Dąbek
* @created 19 maj 2020
*
*/
public interface DayOffService {
DayOff getDayOff(LocalDate date);
List<DayOff> getDayOffByYear(String year);
List<DayOff> getDayOffBetweenDats(LocalDate start, LocalDate end);
void create(DayOff dayOff);
void update(DayOffPojo dayOff);
void delete(Long id);
}
| 23.869565 | 67 | 0.777778 |
40401dbc9ae37f1b620fd91bd45537a9d39e65fd | 2,589 | package com.neusoft.hp.runtime.dyn.visitor.element;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import com.neusoft.core.dao.GenDO;
import com.neusoft.core.service.annotation.SubTable;
import com.neusoft.hp.runtime.dyn.AttributeBean;
import com.neusoft.hp.runtime.dyn.bean.DynBean;
import com.neusoft.hp.runtime.dyn.impl.DynBeanFactoryImpl;
import com.neusoft.hp.runtime.dyn.visitor.DynFieldVisitor;
import com.neusoft.hp.runtime.dyn.visitor.ListDynFieldVisitor;
import com.neusoft.hp.runtime.dyn.visitor.QueryDynFieldVisitor;
/**
* 类SubTableDynField.java的实现描述:子表字段
*
* @author Administrator 2017年4月21日 下午2:53:32
*/
public class SubTableDynField extends DynField {
public SubTableDynField(){
super();
}
public SubTableDynField(List<AttributeBean> selectedAttributes, DynBean bean, Field field){
super(selectedAttributes, bean, field);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void makeForQuery() {
DynFieldVisitor visitor = new QueryDynFieldVisitor();
Type type = getField().getGenericType();
Class<? extends GenDO> domain = null;
if (type instanceof ParameterizedType) {
ParameterizedType param = (ParameterizedType) type;
domain = (Class) param.getActualTypeArguments()[0];
} else {
domain = (Class<? extends GenDO>) getField().getType();
}
DynBeanFactoryImpl.create(getSelectedAttributes(), domain, visitor, getBean());
}
@Override
public void accept(DynFieldVisitor visitor) {
visitor.visitor(this);
}
@Override
public void makeForEntity() {
DynFieldVisitor visitor = new ListDynFieldVisitor();
SubTable sub = getField().getAnnotation(SubTable.class);
DynBeanFactoryImpl.create(getSelectedAttributes(), sub.subClass(), visitor, getBean());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void makeForList() {
DynFieldVisitor visitor = new ListDynFieldVisitor();
Type type = getField().getGenericType();
Class<? extends GenDO> domain = null;
if (type instanceof ParameterizedType) {
ParameterizedType param = (ParameterizedType) type;
domain = (Class) param.getActualTypeArguments()[0];
} else {
domain = (Class<? extends GenDO>) getField().getType();
}
DynBeanFactoryImpl.create(getSelectedAttributes(), domain, visitor, getBean());
}
}
| 34.065789 | 95 | 0.688683 |
efdcc524751b830190cf0be2828678f0def6ad5a | 398 | package io.getlime.security.powerauth.lib.webflow.authentication.mtoken.exception;
/**
* Exception thrown when request object is invalid.
*
* @author Petr Dvorak, [email protected]
*/
public class InvalidRequestObjectException extends MobileAppApiException {
public InvalidRequestObjectException() {
super("Invalid request object sent to Mobile Token API component.");
}
}
| 28.428571 | 82 | 0.761307 |
a2f0096cd94b8a1e84ecc5239ab17eb9bd5a3cf2 | 769 | package org.jfl110.prender.api.render;
import org.jfl110.prender.api.RenderNode;
import com.google.common.base.Function;
/**
* Wrapper for a RenderNode to allow child swapping
*
* @author JFL110
*/
public class RenderNodeSpace{
private RenderNode node;
public static RenderNodeSpace renderNodeSpace(RenderNode node){
return new RenderNodeSpace(node);
}
private RenderNodeSpace(RenderNode node){
this.node = node;
}
public RenderNode get() {
return node;
}
public void set(RenderNode node) {
this.node = node;
}
public static Function<RenderNodeSpace,RenderNode> getNodes(){
return new Function<RenderNodeSpace,RenderNode>(){
@Override
public RenderNode apply(RenderNodeSpace space) {
return space.get();
}
};
}
}
| 18.309524 | 64 | 0.725618 |
0ebf5c94548845e6a106caf46aa2d0ecdcbccffa | 5,665 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package player;
import com.sun.xml.ws.developer.StreamingDataHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
/**
*
* @author Marek Potociar <marek.potociar at sun.com>
*/
public class Main {
private static enum Composition {
/*
Lady Gaga - Just Dance (Dance)
Lily Allen - The Fear (Alternative)
Britney Spears - Womanizer (Pop Rock)
Metallica - ... (Rock Ballad)
Carlos Santana & Buddy Guy at Montreux Jazz Festival (Electric Jazz)
J.S.Bach - Air (Orchestral Suite)
Manowar - Kings Of Metal (Heavy Metal)
*/
DANCE(1, "Lady Gaga", "Just Dance", "Dance", "dance"),
ALTERNATIVE(2, "Lily Allen", "The Fear", "Alternative Rock", "alternative"),
POP_ROCK(3, "Britney Spears", "Womanizer", "Pop", "pop"),
ROCK_BALLAD(4, "Metallica", "Turn The Page", "Rock Ballad", "ballad"),
HEAVY_METAL(5, "Manowar", "Kings Of Metal", "Heavy Metal", "metal"),
JAZZ(6, "Carlos Santana & Buddy Guy", "Montreux Jazz Festival", "Jazz", "jazz"),
ORCHESTRAL(7, "J.S.Bach", "Air", "Classical", "classical");
private static Composition getById(int chosenId) {
for (Composition c : values()) {
if (c.id == chosenId) {
return c;
}
}
return null;
}
//
final int id;
final String artist;
final String songTitle;
final String genre;
final String fileName;
private Composition(int id, String artist, String songTitle, String genre, String fileName) {
this.id = id;
this.artist = artist;
this.songTitle = songTitle;
this.genre = genre;
this.fileName = fileName;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
StreamingDataHandler sdh = null;
InputStream is = null;
try {
System.out.println("Choose genre to start audio streaming:");
Composition chosen;
do {
for (Composition c : Composition.values()) {
System.out.println(String.format("%d. %s", c.id, c.genre));
}
int chosenId = new Scanner(System.in).nextInt();
chosen = Composition.getById(chosenId);
if (chosen == null) {
System.out.println("\n\nIncorrect choice. Please select a proper number in range:");
}
} while (chosen == null);
System.out.println(String.format("\n\nLoading %s - %s :\n\n", chosen.artist, chosen.songTitle));
System.out.println("Creating and configuring stream service reference... ");
provider.AudioStreamerService service = new provider.AudioStreamerService();
provider.AudioStreamer port = service.getAudioStreamerPort();
System.out.println("DONE\nGeting data handler... ");
sdh = (StreamingDataHandler) port.getWavStream(chosen.fileName);
System.out.println("DONE\nOpening data stream... ");
is = sdh.readOnce();
System.out.println("DONE\nStarting audio player thread... ");
sun.audio.AudioPlayer.player.start(is);
System.out.println("Audio player thread started, waiting for it to finish... ");
sun.audio.AudioPlayer.player.join();
System.out.println("DONE");
} finally {
System.out.println("Closing data streams... ");
is.close();
sdh.close();
System.out.println("DONE");
}
}
}
| 41.654412 | 108 | 0.632304 |
926dd76ef3d8a91f5a8689df8690c228d559dd87 | 1,247 | package net.szum123321.tool_action_helper.impl;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.Block;
import net.minecraft.block.PillarBlock;
import net.szum123321.tool_action_helper.exception.BadBlockException;
import net.szum123321.tool_action_helper.mixin.accessors.AxeItemAccessor;
public class AxeStrippingHelper implements net.szum123321.tool_action_helper.api.AxeStrippingHelper {
/**
* @deprecated Use {@link net.szum123321.tool_action_helper.api.AxeStrippingHelper#getInstance()}
*/
@Deprecated
public final static AxeStrippingHelper INSTANCE = new AxeStrippingHelper();
private AxeStrippingHelper() {}
@Override
public void addNewStrippingPair(Block block1, Block block2) throws BadBlockException {
if(!(block1 instanceof PillarBlock))
throw new BadBlockException(block1, PillarBlock.class);
if(!(block2 instanceof PillarBlock))
throw new BadBlockException(block2, PillarBlock.class);
ImmutableMap.Builder<Block, Block> builder = ImmutableMap.builder();
builder.putAll(AxeItemAccessor.getStrippedBlocks());
builder.put(block1, block2);
AxeItemAccessor.setStrippedBlocks(builder.build());
}
}
| 36.676471 | 101 | 0.756215 |
fbb6559716491b5d6e614582ba1b3dbb37b8ff7d | 1,748 | package org.gbif.pipelines.tasks.validator.validate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import org.gbif.api.model.crawler.FinishReason;
import org.gbif.api.vocabulary.EndpointType;
import org.gbif.common.messaging.api.messages.PipelinesArchiveValidatorMessage;
import org.gbif.common.messaging.api.messages.PipelinesXmlMessage;
import org.gbif.common.messaging.api.messages.Platform;
import org.gbif.pipelines.tasks.validator.ArchiveValidatorConfiguration;
import org.junit.Test;
public class XmlArchiveValidatorTest {
@Test
public void createOutgoingMessageTest() {
// State
UUID key = UUID.fromString("7ef15372-1387-11e2-bb2e-00145eb45e9a");
ArchiveValidatorConfiguration config = new ArchiveValidatorConfiguration();
config.archiveRepository = this.getClass().getResource("/dataset/xml").getPath();
config.validatorOnly = true;
PipelinesArchiveValidatorMessage message = new PipelinesArchiveValidatorMessage();
message.setAttempt(1);
message.setDatasetUuid(key);
message.setExecutionId(1L);
// When
PipelinesXmlMessage result =
XmlArchiveValidator.builder()
.message(message)
.config(config)
.build()
.createOutgoingMessage();
// Should
assertEquals(key, result.getDatasetUuid());
assertEquals(Integer.valueOf(1), result.getAttempt());
assertTrue(result.isValidator());
assertEquals(message.getExecutionId(), result.getExecutionId());
assertEquals(FinishReason.NORMAL, result.getReason());
assertEquals(EndpointType.BIOCASE_XML_ARCHIVE, result.getEndpointType());
assertEquals(Platform.PIPELINES, result.getPlatform());
}
}
| 36.416667 | 86 | 0.756865 |
4fe9a299cab07862362227044a4a3434087462ca | 1,497 | package no.nav.foreldrepenger;
import static no.nav.foreldrepenger.boot.conditionals.Cluster.profiler;
import static org.springframework.context.annotation.FilterType.ASSIGNABLE_TYPE;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Import;
import org.springframework.retry.annotation.EnableRetry;
import no.nav.foreldrepenger.oppslag.OppslagApplication;
import no.nav.security.token.support.spring.api.EnableJwtTokenValidation;
import no.nav.security.token.support.test.spring.TokenGeneratorConfiguration;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication
@EnableRetry
@ConfigurationPropertiesScan("no.nav.foreldrepenger.oppslag")
@EnableJwtTokenValidation(ignore = { "org.springframework", "springfox.documentation" })
@ComponentScan(excludeFilters = { @Filter(type = ASSIGNABLE_TYPE, value = OppslagApplication.class) })
@EnableOpenApi
@Import(value = TokenGeneratorConfiguration.class)
public class OppslagApplicationLocal {
public static void main(String[] args) {
new SpringApplicationBuilder(OppslagApplicationLocal.class)
.profiles(profiler())
.run(args);
}
}
| 44.029412 | 102 | 0.824315 |
21910c0dc2633e3def78ecd070b0ada8ebc6f964 | 11,138 | package com.bitdubai.reference_niche_wallet.bitcoin_wallet.fragments.wallet_final_version;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu.OnMenuItemClickListener;
import com.bitdubai.android_fermat_ccp_wallet_bitcoin.R;
import com.bitdubai.fermat_android_api.ui.adapters.FermatAdapterNew;
import com.bitdubai.fermat_android_api.ui.enums.FermatRefreshTypes;
import com.bitdubai.fermat_android_api.ui.fragments.FermatListFragmentNew;
import com.bitdubai.fermat_android_api.ui.inflater.ViewInflater;
import com.bitdubai.fermat_android_api.ui.interfaces.FermatListItemListeners;
import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps;
import com.bitdubai.fermat_ccp_api.layer.wallet_module.crypto_wallet.interfaces.CryptoWallet;
import com.bitdubai.fermat_ccp_api.layer.wallet_module.crypto_wallet.interfaces.PaymentRequest;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedSubAppExceptionSeverity;
import com.bitdubai.reference_niche_wallet.bitcoin_wallet.common.adapters.PaymentRequestPendingAdapter;
import com.bitdubai.reference_niche_wallet.bitcoin_wallet.session.ReferenceWalletSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
*
*
* @author Matias Furszyfer
* @version 1.0
*/
public class RequestPaymentFragment extends FermatListFragmentNew<PaymentRequest>
implements FermatListItemListeners<PaymentRequest>, OnMenuItemClickListener {
/**
* MANAGERS
*/
private CryptoWallet cryptoWallet;
/**
* Session
*/
ReferenceWalletSession referenceWalletSession;
/**
* DATA
*/
private List<PaymentRequest> lstPaymentRequest;
private PaymentRequest selectedItem;
String walletPublicKey = "reference_wallet";
/**
* Executor Service
*/
private ExecutorService executor;
/**
* Create a new instance of this fragment
*
* @return InstalledFragment instance object
*/
public static RequestPaymentFragment newInstance() {
RequestPaymentFragment requestPaymentFragment = new RequestPaymentFragment();
return new RequestPaymentFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
referenceWalletSession = (ReferenceWalletSession)walletSession;
super.onCreate(savedInstanceState);
try {
cryptoWallet = referenceWalletSession.getModuleManager().getCryptoWallet();
lstPaymentRequest = getMoreDataAsync(FermatRefreshTypes.NEW, 0); // get init data
viewInflater = new ViewInflater(getActivity(),null);
View rootView = viewInflater.inflate("layout",null);
} catch (Exception ex) {
//CommonLogger.exception(TAG, ex.getMessage(), ex);
}
}
@Override
protected boolean hasMenu() {
return false;
}
@Override
protected String getLayoutResourceName() {
return "payment_request_base";//R.layout.wallet_store_fragment_main_activity;
}
@Override
protected String getSwipeRefreshLayoutName() {
return "swipe_refresh";
}
@Override
protected String getRecyclerLayoutName() {
return "payment_request_recycler_view";
}
@Override
protected boolean recyclerHasFixedSize() {
return true;
}
@Override
@SuppressWarnings("unchecked")
public FermatAdapterNew getAdapter() {
if (adapter == null) {
//WalletStoreItemPopupMenuListener listener = getWalletStoreItemPopupMenuListener();
adapter = new PaymentRequestPendingAdapter(getActivity(), lstPaymentRequest, viewInflater,(ReferenceWalletSession)walletSession);
adapter.setFermatListEventListener(this); // setting up event listeners
}
return adapter;
}
@Override
public RecyclerView.LayoutManager getLayoutManager() {
if (layoutManager == null) {
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
}
return layoutManager;
}
@Override
public List<PaymentRequest> getMoreDataAsync(FermatRefreshTypes refreshType, int pos) {
List<PaymentRequest> lstPaymentRequest = null;
try {
lstPaymentRequest = cryptoWallet.listPaymentRequestDateOrder(walletPublicKey,10,0);
} catch (Exception e) {
referenceWalletSession.getErrorManager().reportUnexpectedSubAppException(SubApps.CWP_WALLET_STORE,
UnexpectedSubAppExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_FRAGMENT, e);
// data = RequestPaymentListItem.getTestData(getResources());
}
return lstPaymentRequest;
}
@Override
public void onItemClickListener(PaymentRequest item, int position) {
selectedItem = item;
//showDetailsActivityFragment(selectedItem);
}
@Override
public void onLongItemClickListener(PaymentRequest data, int position) {
// do nothing
}
@Override
public void onPostExecute(Object... result) {
isRefreshing = false;
if (isAttached) {
swipeRefreshLayout.setRefreshing(false);
if (result != null && result.length > 0) {
lstPaymentRequest = (ArrayList) result[0];
if (adapter != null)
adapter.changeDataSet(lstPaymentRequest);
}
}
}
@Override
public void onErrorOccurred(Exception ex) {
isRefreshing = false;
if (isAttached) {
swipeRefreshLayout.setRefreshing(false);
//CommonLogger.exception(TAG, ex.getMessage(), ex);
}
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
// int menuItemItemId = menuItem.getItemId();
// if (menuItemItemId == R.id.menu_action_install_wallet) {
// if (selectedItem != null) {
// installSelectedWallet(selectedItem);
// }
// return true;
// }
// if (menuItemItemId == R.id.menu_action_wallet_details) {
// if (selectedItem != null) {
// showDetailsActivityFragment(selectedItem);
// }
// return true;
// }
// if (menuItemItemId == R.id.menu_action_open_wallet) {
// Toast.makeText(getActivity(), "Opening Wallet...", Toast.LENGTH_SHORT).show();
// return true;
// }
//
return false;
}
public void setReferenceWalletSession(ReferenceWalletSession referenceWalletSession) {
this.referenceWalletSession = referenceWalletSession;
}
// private void installSelectedWallet(WalletStoreListItem item) {
//
// final Activity activity = getActivity();
// FermatWorkerCallBack callBack = new FermatWorkerCallBack() {
// @Override
// public void onPostExecute(Object... result) {
// Toast.makeText(getActivity(), "Installing...", Toast.LENGTH_SHORT).show();
//
// InstallWalletWorkerCallback callback = new InstallWalletWorkerCallback(getActivity(), errorManager);
// InstallWalletWorker installWalletWorker = new InstallWalletWorker(getActivity(), callback, moduleManager, subAppsSession);
// if (executor != null)
// executor.shutdownNow();
// executor = installWalletWorker.execute();
// }
//
// @Override
// public void onErrorOccurred(Exception ex) {
// final ErrorManager errorManager = subAppsSession.getErrorManager();
// errorManager.reportUnexpectedSubAppException(SubApps.CWP_WALLET_STORE,
// UnexpectedSubAppExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_FRAGMENT, ex);
//
// Toast.makeText(activity, R.string.cannot_collect_wallet_details, Toast.LENGTH_SHORT).show();
// }
// };
//
// final DetailedCatalogItemWorker worker = new DetailedCatalogItemWorker(moduleManager, subAppsSession, item, activity, callBack);
// worker.execute();
// }
// private void showDetailsActivityFragment(WalletStoreListItem item) {
//
// final Activity activity = getActivity();
// FermatWorkerCallBack callBack = new FermatWorkerCallBack() {
// @Override
// public void onPostExecute(Object... result) {
//
// final DetailsActivityFragment fragment = DetailsActivityFragment.newInstance();
// fragment.setSubAppsSession(subAppsSession);
// fragment.setSubAppSettings(subAppSettings);
// fragment.setSubAppResourcesProviderManager(subAppResourcesProviderManager);
//
// final FragmentTransaction FT = activity.getFragmentManager().beginTransaction();
// FT.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// FT.replace(R.id.activity_container, fragment);
// FT.addToBackStack(null);
// FT.commit();
// }
//
// @Override
// public void onErrorOccurred(Exception ex) {
// final ErrorManager errorManager = subAppsSession.getErrorManager();
// errorManager.reportUnexpectedSubAppException(SubApps.CWP_WALLET_STORE,
// UnexpectedSubAppExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_FRAGMENT, ex);
//
// Toast.makeText(activity, R.string.cannot_collect_wallet_details, Toast.LENGTH_SHORT).show();
// }
// };
//
// final DetailedCatalogItemWorker worker = new DetailedCatalogItemWorker(moduleManager, subAppsSession, item, activity, callBack);
// worker.execute();
// }
// @NonNull
// private WalletStoreItemPopupMenuListener getWalletStoreItemPopupMenuListener() {
// return new WalletStoreItemPopupMenuListener() {
// @Override
// public void onMenuItemClickListener(View menuView, WalletStoreListItem item, int position) {
// selectedItem = item;
//
// PopupMenu popupMenu = new PopupMenu(getActivity(), menuView);
// MenuInflater menuInflater = popupMenu.getMenuInflater();
//
// InstallationStatus installationStatus = item.getInstallationStatus();
// int resId = UtilsFuncs.INSTANCE.getInstallationStatusStringResource(installationStatus);
//
// if (resId == R.string.wallet_status_install) {
// menuInflater.inflate(R.menu.menu_wallet_store, popupMenu.getMenu());
// } else {
// menuInflater.inflate(R.menu.menu_wallet_store_installed, popupMenu.getMenu());
// }
//
// popupMenu.setOnMenuItemClickListener(RequestPaymentFragment.this);
// popupMenu.show();
// }
// };
// }
}
| 37.126667 | 141 | 0.667265 |
b03fa38de36a0cdadf8b234b3dfe730cf90e5491 | 2,957 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.quarkus.it.kogito.jbpm;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.kie.kogito.Model;
import org.kie.kogito.process.Process;
import org.kie.kogito.process.ProcessInstance;
import org.kie.kogito.process.ProcessInstances;
import org.kie.kogito.process.WorkItem;
@Path("/runProcess")
public class OrdersProcessService {
@Inject
@Named("demo.orders")
Process<? extends Model> orderProcess;
@Inject
@Named("demo.orderItems")
Process<? extends Model> orderItemsProcess;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testOrderProcess() {
Model m = orderProcess.createModel();
Map<String, Object> parameters = new HashMap<>();
parameters.put("approver", "john");
parameters.put("order", new Order("12345", false, 0.0));
m.fromMap(parameters);
ProcessInstance<?> processInstance = orderProcess.createInstance(m);
processInstance.start();
assert (org.kie.api.runtime.process.ProcessInstance.STATE_ACTIVE == processInstance.status());
Model result = (Model) processInstance.variables();
assert (result.toMap().size() == 2);
assert (((Order) result.toMap().get("order")).getTotal() > 0);
ProcessInstances<? extends Model> orderItemProcesses = orderItemsProcess.instances();
assert (orderItemProcesses.values().size() == 1);
ProcessInstance<?> childProcessInstance = orderItemProcesses.values().iterator().next();
List<WorkItem> workItems = childProcessInstance.workItems();
assert (workItems.size()) == 1;
childProcessInstance.completeWorkItem(workItems.get(0).getId(), null);
assert (org.kie.api.runtime.process.ProcessInstance.STATE_COMPLETED == childProcessInstance.status());
assert (org.kie.api.runtime.process.ProcessInstance.STATE_COMPLETED == processInstance.status());
// no active process instances for both orders and order items processes
assert (orderProcess.instances().values().size() == 0);
assert (orderItemsProcess.instances().values().size() == 0);
return "OK";
}
}
| 35.202381 | 110 | 0.702401 |
81c0e023b21549a6db5d75db0f74e83ff2a1c02a | 2,742 | package me.mos.lnk.packet;
import java.util.Date;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
/**
* 用户信息修订报文定义.
*
* @author 刘飞 E-mail:[email protected]
*
* @version 1.0.0
* @since 2015年5月31日 下午11:21:27
*/
@XStreamAlias(Alias.REVISE_NAME)
public class InRevise extends AbstractInPacket {
/** 发起报文的用户的唯一ID */
@XStreamAlias("mid")
@XStreamAsAttribute
private long mid;
/** 第三方系统账号ID */
@XStreamAlias("party-id")
@XStreamAsAttribute
private String party_id;
/** 用户昵称 */
@XStreamAlias("nick")
private String nick;
/** 用户密码 */
@XStreamAlias("passwd")
private String passwd;
/** 用户头像 */
@XStreamAlias("avatar")
private String avatar;
/** 微信号 */
@XStreamAlias("weixin")
private String weixin;
/** QQ号 */
@XStreamAlias("qq")
private String qq;
/** EMail */
@XStreamAlias("email")
private String email;
/** 电话号码 */
@XStreamAlias("telephone")
private String telephone;
/** 固话 */
@XStreamAlias("phone")
private String phone;
public InRevise() {
super(Type.Revise.type);
}
@Override
public OutRevise toOutPacket() {
OutRevise outRevise = new OutRevise();
outRevise.setAvatar(avatar);
outRevise.setEmail(email);
outRevise.setNick(nick);
outRevise.setParty_id(party_id);
outRevise.setPhone(phone);
outRevise.setQq(qq);
outRevise.setTelephone(telephone);
outRevise.setWeixin(weixin);
outRevise.setMid(mid);
outRevise.setGmt_created(new Date().getTime());
return outRevise.ok();
}
@Override
public Type type() {
return Type.Revise;
}
public void setMid(long mid) {
this.mid = mid;
}
@Override
public long getMid() {
return mid;
}
public String getParty_id() {
return party_id;
}
public void setParty_id(String party_id) {
this.party_id = party_id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getWeixin() {
return weixin;
}
public void setWeixin(String weixin) {
this.weixin = weixin;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
} | 16.518072 | 63 | 0.689278 |
b2766a7dfb07b2e6117b97110ad48051daedae32 | 8,732 | package com.ruoyi.project.userbackground.rules.controller;
import java.util.*;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.userbackground.rules.domain.CpSheetScoringRules;
import com.ruoyi.project.userbackground.rules.service.ICpSheetScoringRulesService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
/**
* 计分规则Controller
*
* @author ruoyi
* @date 2021-09-06
*/
@Controller
@RequestMapping("/userbackground/rules")
public class CpSheetScoringRulesController extends BaseController
{
private String prefix = "userbackground/rules";
@Autowired
private ICpSheetScoringRulesService cpSheetScoringRulesService;
@RequiresPermissions("userbackground:rules:view")
@GetMapping()
public String rules()
{
return prefix + "/rules";
}
/**
* 查询计分规则列表
*/
@RequiresPermissions("userbackground:rules:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(CpSheetScoringRules cpSheetScoringRules)
{
startPage();
List<CpSheetScoringRules> list = cpSheetScoringRulesService.selectCpSheetScoringRulesList(cpSheetScoringRules);
return getDataTable(list);
}
/**
* 导出计分规则列表
*/
@RequiresPermissions("userbackground:rules:export")
@Log(title = "计分规则", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(CpSheetScoringRules cpSheetScoringRules)
{
List<CpSheetScoringRules> list = cpSheetScoringRulesService.selectCpSheetScoringRulesList(cpSheetScoringRules);
ExcelUtil<CpSheetScoringRules> util = new ExcelUtil<CpSheetScoringRules>(CpSheetScoringRules.class);
return util.exportExcel(list, "计分规则数据");
}
/**
* 新增计分规则
*/
@GetMapping("/add")
public String add()
{
return prefix + "/add";
}
/**
* 新增保存计分规则
*/
@RequiresPermissions("userbackground:rules:add")
@Log(title = "计分规则", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(CpSheetScoringRules cpSheetScoringRules)
{
return toAjax(cpSheetScoringRulesService.insertCpSheetScoringRules(cpSheetScoringRules));
}
/**
* 修改计分规则
*/
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") String id, ModelMap mmap)
{
CpSheetScoringRules cpSheetScoringRules = cpSheetScoringRulesService.selectCpSheetScoringRulesById(id);
mmap.put("cpSheetScoringRules", cpSheetScoringRules);
return prefix + "/edit";
}
/**
* 修改保存计分规则
*/
@RequiresPermissions("userbackground:rules:edit")
@Log(title = "计分规则", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(CpSheetScoringRules cpSheetScoringRules)
{
return toAjax(cpSheetScoringRulesService.updateCpSheetScoringRules(cpSheetScoringRules));
}
/**
* 删除计分规则
*/
//@RequiresPermissions("userbackground:rules:remove")
@Log(title = "计分规则", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
return toAjax(cpSheetScoringRulesService.deleteCpSheetScoringRulesByIds(ids));
}
@PostMapping("/batchaddjf")
@ResponseBody
public String batchaddjf(Long sheetid,String deptid,String rankids,String rankName,String points,Long aaaa,Long activityId)
{
//先删除原有数据
CpSheetScoringRules scoreRules = new CpSheetScoringRules(sheetid, deptid, aaaa, activityId,rankName);
cpSheetScoringRulesService.delSheetScoreRulesByMore(scoreRules);
List<String> lis = Arrays.asList(rankids.split(","));
if(lis.size() > 0){
for(int i = 0;i<lis.size();i++){
String id = UUID.randomUUID().toString();
CpSheetScoringRules c = new CpSheetScoringRules();
c.setId(id);
c.setSheetId(sheetid);
c.setDeptId(deptid);
c.setRankId(lis.get(i));
c.setGroupName(rankName);
c.setFraction(points);
c.setSheetType(aaaa);
c.setActivityId(activityId);
cpSheetScoringRulesService.insertCpSheetScoringRules(c);
}
}
return "success";
}
/**
* 获取计分规则列表
* @param sheetId
* @param sheetType
* @param activityId
* @return
*/
@PostMapping("/selectJfRulesList")
@ResponseBody
public TableDataInfo selectJfRulesList(Long sheetId,Long sheetType,Long activityId){
List<Map<String, Object>> list = cpSheetScoringRulesService.selectSheetScoreRulesBySheetIdTypeActId(sheetId, sheetType, activityId);
return getDataTable(list);
}
/**
* 删除计分规则列表选中的数
* @param sheetId
* @param deptId
* @param sheetType
* @param activityId
* @return
*/
@Log(title = "计分规则", businessType = BusinessType.DELETE)
@PostMapping( "/delSheetScoreRulesByMore")
@ResponseBody
public AjaxResult delSheetScoreRulesByMore(Long sheetId,String deptId,Long sheetType,Long activityId,String groupName){
CpSheetScoringRules scoreRules = new CpSheetScoringRules(sheetId, deptId, sheetType, activityId, groupName);
cpSheetScoringRulesService.delSheetScoreRulesByMore(scoreRules);
return success();
}
@PostMapping( "/selectrankbydeptidandactid")
@ResponseBody
public List<CpSheetScoringRules> selectrankbydeptidandactid(Long sheetId, String deptId, Long activityId){
List<CpSheetScoringRules> objUserIdList = cpSheetScoringRulesService.selectrankbydeptidandactid(sheetId,deptId,activityId);
return objUserIdList;
}
/**
* 循环保存职级计分
* @param scoreRulesListStr
* @return
*/
@PostMapping( "/batchSaveScoreRules")
@ResponseBody
public AjaxResult batchSaveScoreRules(String scoreRulesListStr){
List<CpSheetScoringRules> scoreRulesList = JSON.parseArray(scoreRulesListStr,CpSheetScoringRules.class);
for (CpSheetScoringRules scoreRules : scoreRulesList) {
String uuid = UUID.randomUUID().toString().replaceAll("-","");
scoreRules.setId(uuid);
scoreRules.setCreateTime(new Date());
cpSheetScoringRulesService.insertCpSheetScoringRules(scoreRules);
}
return success();
}
/**
* 循环修改职级计分
* @param scoreRulesListStr
* @return
*/
@PostMapping( "/batchEditScoreRules")
@ResponseBody
public AjaxResult batchEditScoreRules(String scoreRulesListStr){
List<CpSheetScoringRules> scoreRulesList = JSON.parseArray(scoreRulesListStr,CpSheetScoringRules.class);
for (CpSheetScoringRules scoreRules : scoreRulesList) {
cpSheetScoringRulesService.updateCpSheetScoringRules(scoreRules);
}
return success();
}
/**
* 计分规则又改了
* @param cpSheetScoringRules
* @return
*/
@PostMapping("/selectAllJfRulesList")
@ResponseBody
public TableDataInfo selectAllJfRulesList(CpSheetScoringRules cpSheetScoringRules){
List<Map<String, Object>> list = cpSheetScoringRulesService.selectRankScoreRulesByActIdSid(cpSheetScoringRules);
// List<Map<String, Object>> llist = new ArrayList<>();
// if(list.size() > 0){
// for(int i = 0;i<list.size();i++){
// if(list.get(i).size() == 2){
// list.get(i).put("fraction","点击设置");
// }
// llist.add(i,list.get(i));
// }
// }
return getDataTable(list);
}
}
| 35.068273 | 141 | 0.664567 |
1c2141ac29bdb0ac84ac69c0ac47ac93f7ed1e48 | 618 | package com.loveplusplus.update;
class Constants {
// json {"url":"http://192.168.205.33:8080/Hello/app_v3.0.1_Other_20150116.apk","versionCode":2,"updateMessage":"版本更新信息"}
static final String APK_DOWNLOAD_URL = "url";
static final String APK_UPDATE_CONTENT = "updateMessage";
static final String APK_VERSION_CODE = "versionCode";
static final int TYPE_NOTIFICATION = 2;
static final int TYPE_DIALOG = 1;
static final String TAG = "UpdateChecker";
//static final String UPDATE_URL = "https://raw.githubusercontent.com/feicien/android-auto-update/develop/extras/update.json";
}
| 29.428571 | 130 | 0.729773 |
d1899e0faf1fa671b3e9abdcd7b7c168ac0356fd | 1,638 |
package application;
import gui.ApplicationWindow;
import java.io.IOException;
import logging.Logger;
import main.EntryPoint;
/**
* Application serves as the entry point for
* the automation program. The main method of\
* this class starts and launches the GUI where the used can
* choose which automation to run.
*
* @author Matt Crow
*/
public class Application extends EntryPoint{
private final WebDriverLoader webDriverLoader;
private static Application instance;
private Application(){
super();
if(instance != null){
throw new RuntimeException("Cannot instantiate more than one instance of Application. Use Application.getInstance() instead");
}
webDriverLoader = new WebDriverLoader(this);
}
public static Application getInstance(){
if(instance == null){
instance = new Application();
}
return instance;
}
public WebDriverLoader getWebDriverLoader(){
return webDriverLoader;
}
@Override
public void doRun(){
try {
webDriverLoader.init();
} catch (IOException ex) {
Logger.logError("Application.doRun", ex);
}
ApplicationWindow w = new ApplicationWindow(this); //automatically listens to window
}
public static void main(String[] args) throws IOException{
Application app = getInstance();
Thread updater = new Thread(){
@Override
public void run(){
app.checkForUpdates();
}
};
updater.start();
app.run();
}
}
| 26.419355 | 138 | 0.619658 |
2909f9304071df3738366fae0d45f21792b55da5 | 26,487 | /*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* 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.iluwatar.commander;
import com.iluwatar.commander.Order.MessageSent;
import com.iluwatar.commander.Order.PaymentStatus;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.exceptions.PaymentDetailsErrorException;
import com.iluwatar.commander.exceptions.ShippingNotPossibleException;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.queue.QueueTask;
import com.iluwatar.commander.queue.QueueTask.TaskType;
import com.iluwatar.commander.shippingservice.ShippingService;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Commander pattern is used to handle all issues that can come up while making a
* distributed transaction. The idea is to have a commander, which coordinates the execution of all
* instructions and ensures proper completion using retries and taking care of idempotence. By
* queueing instructions while they haven't been done, we can ensure a state of 'eventual
* consistency'.</p>
* <p>In our example, we have an e-commerce application. When the user places an order,
* the shipping service is intimated first. If the service does not respond for some reason, the
* order is not placed. If response is received, the commander then calls for the payment service to
* be intimated. If this fails, the shipping still takes place (order converted to COD) and the item
* is queued. If the queue is also found to be unavailable, the payment is noted to be not done and
* this is added to an employee database. Three types of messages are sent to the user - one, if
* payment succeeds; two, if payment fails definitively; and three, if payment fails in the first
* attempt. If the message is not sent, this is also queued and is added to employee db. We also
* have a time limit for each instruction to be completed, after which, the instruction is not
* executed, thereby ensuring that resources are not held for too long. In the rare occasion in
* which everything fails, an individual would have to step in to figure out how to solve the
* issue.</p>
* <p>We have abstract classes {@link Database} and {@link Service} which are extended
* by all the databases and services. Each service has a database to be updated, and receives
* request from an outside user (the {@link Commander} class here). There are 5 microservices -
* {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle}
* and a {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class,
* and idempotence is ensured by going through some checks before making requests to services and
* making change in {@link Order} class fields if request succeeds or definitively fails. There are
* 5 classes - {@link AppShippingFailCases}, {@link AppPaymentFailCases}, {@link
* AppMessagingFailCases}, {@link AppQueueFailCases} and {@link AppEmployeeDbFailCases}, which look
* at the different scenarios that may be encountered during the placing of an order.</p>
*/
public class Commander {
private final QueueDatabase queue;
private final EmployeeHandle employeeDb;
private final PaymentService paymentService;
private final ShippingService shippingService;
private final MessagingService messagingService;
private int queueItems = 0; //keeping track here only so don't need access to queue db to get this
private final int numOfRetries;
private final long retryDuration;
private final long queueTime;
private final long queueTaskTime;
private final long paymentTime;
private final long messageTime;
private final long employeeTime;
private boolean finalSiteMsgShown;
private static final Logger LOG = LoggerFactory.getLogger(Commander.class);
//we could also have another db where it stores all orders
Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService,
MessagingService messagingService, QueueDatabase qdb, int numOfRetries,
long retryDuration, long queueTime, long queueTaskTime, long paymentTime,
long messageTime, long employeeTime) {
this.paymentService = paymentService;
this.shippingService = shippingService;
this.messagingService = messagingService;
this.employeeDb = empDb;
this.queue = qdb;
this.numOfRetries = numOfRetries;
this.retryDuration = retryDuration;
this.queueTime = queueTime;
this.queueTaskTime = queueTaskTime;
this.paymentTime = paymentTime;
this.messageTime = messageTime;
this.employeeTime = employeeTime;
this.finalSiteMsgShown = false;
}
void placeOrder(Order order) throws Exception {
sendShippingRequest(order);
}
private void sendShippingRequest(Order order) throws Exception {
var list = shippingService.exceptionsList;
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to shipping service, "
+ "trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating shipping request..");
}
throw l.remove(0);
}
String transactionId = shippingService.receiveRequest(order.item, order.user.address);
//could save this transaction id in a db too
LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: "
+ transactionId);
LOG.info("Order has been placed and will be shipped to you. Please wait while we make your"
+ " payment... ");
sendPaymentRequest(order);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) {
LOG.info("Shipping is currently not possible to your address. We are working on the problem"
+ " and will get back to you asap.");
finalSiteMsgShown = true;
LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem "
+ "to employee db..");
employeeHandleIssue(o);
} else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) {
LOG.info("This item is currently unavailable. We will inform you as soon as the item "
+ "becomes available again.");
finalSiteMsgShown = true;
LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add "
+ "problem to employee handle..");
employeeHandleIssue(o);
} else {
LOG.info("Sorry, there was a problem in creating your order. Please try later.");
LOG.error("Order " + order.id + ": Shipping service unavailable, order not placed..");
finalSiteMsgShown = true;
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
r.perform(list, order);
}
private void sendPaymentRequest(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) {
if (order.paid.equals(PaymentStatus.TRYING)) {
order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(order);
LOG.error("Order " + order.id + ": Payment time for order over, failed and returning..");
} //if succeeded or failed, would have been dequeued, no attempt to make payment
return;
}
var list = paymentService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
+ " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING)) {
var transactionId = paymentService.receiveRequest(order.price);
order.paid = PaymentStatus.DONE;
LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId);
if (!finalSiteMsgShown) {
LOG.info("Payment made successfully, thank you for shopping with us!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
o.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NONE_SENT)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + order.id + ": Payment error, going to queue..");
sendPaymentPossibleErrorMsg(o);
}
if (o.paid.equals(PaymentStatus.TRYING) && System
.currentTimeMillis() - o.createdTime < paymentTime) {
var qt = new QueueTask(o, TaskType.PAYMENT, -1);
updateQueue(qt);
}
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void updateQueue(QueueTask qt) {
if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) {
// since payment time is lesser than queuetime it would have already failed..
// additional check not needed
LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed..");
return;
} else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING)
|| qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1
&& !qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL))
|| qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) {
LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done..");
return;
}
var list = queue.exceptionsList;
Thread t = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn("Order " + qt.order.id + ": Error in connecting to queue db, trying again..");
throw list1.remove(0);
}
queue.add(qt);
queueItems++;
LOG.info("Order " + qt.order.id + ": " + qt.getType() + " task enqueued..");
tryDoingTasksInQueue();
};
Retry.HandleErrorIssue<QueueTask> handleError = (qt1, err) -> {
if (qt1.taskType.equals(TaskType.PAYMENT)) {
qt1.order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(qt1.order);
LOG.error("Order " + qt1.order.id + ": Unable to enqueue payment task,"
+ " payment failed..");
}
LOG.error("Order " + qt1.order.id + ": Unable to enqueue task of type " + qt1.getType()
+ ", trying to add to employee handle..");
employeeHandleIssue(qt1.order);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, qt);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void tryDoingTasksInQueue() { //commander controls operations done to queue
var list = queue.exceptionsList;
var t2 = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn("Error in accessing queue db to do tasks, trying again..");
throw list1.remove(0);
}
doTasksInQueue();
};
Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> {
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, null);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t2.start();
}
private void tryDequeue() {
var list = queue.exceptionsList;
var t3 = new Thread(() -> {
Retry.Operation op = (list1) -> {
if (!list1.isEmpty()) {
LOG.warn("Error in accessing queue db to dequeue task, trying again..");
throw list1.remove(0);
}
queue.dequeue();
queueItems--;
};
Retry.HandleErrorIssue<QueueTask> handleError = (o, err) -> {
};
var r = new Retry<QueueTask>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, null);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t3.start();
}
private void sendSuccessMessage(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Order " + order.id + ": Message time for order over, returning..");
return;
}
var list = messagingService.exceptionsList;
Thread t = new Thread(() -> {
Retry.Operation op = handleSuccessMessageRetryOperation(order);
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handleSuccessMessageErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handleSuccessMessageErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 2);
updateQueue(qt);
LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to"
+ " queue task and add to employee handle..");
employeeHandleIssue(order);
}
}
private Retry.Operation handleSuccessMessageRetryOperation(Order order) {
return (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Success msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Success"
+ " messaging request..");
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(2);
order.messageSent = MessageSent.PAYMENT_SUCCESSFUL;
LOG.info("Order " + order.id + ": Payment Success message sent,"
+ " request Id: " + requestId);
}
};
}
private void sendPaymentFailureMessage(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Order " + order.id + ": Message time for order over, returning..");
return;
}
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
handlePaymentFailureRetryOperation(order, l);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handlePaymentErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handlePaymentErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 0);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}
private void handlePaymentFailureRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Failure msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Failure"
+ " message request..");
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(0);
order.messageSent = MessageSent.PAYMENT_FAIL;
LOG.info("Order " + order.id + ": Payment Failure message sent successfully,"
+ " request Id: " + requestId);
}
}
private void sendPaymentPossibleErrorMsg(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Message time for order over, returning..");
return;
}
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
handlePaymentPossibleErrorMsgRetryOperation(order, l);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handlePaymentPossibleErrorMsgErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) {
if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid
.equals(PaymentStatus.TRYING)
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}
private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List<Exception> l)
throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Error msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Error"
+ " messaging request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent
.equals(MessageSent.NONE_SENT)) {
var requestId = messagingService.receiveRequest(1);
order.messageSent = MessageSent.PAYMENT_TRYING;
LOG.info("Order " + order.id + ": Payment Error message sent successfully,"
+ " request Id: " + requestId);
}
}
private void employeeHandleIssue(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) {
LOG.trace("Order " + order.id + ": Employee handle time for order over, returning..");
return;
}
var list = employeeDb.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
LOG.warn("Order " + order.id + ": Error in connecting to employee handle,"
+ " trying again..");
throw l.remove(0);
}
if (!order.addedToEmployeeHandle) {
employeeDb.receiveRequest(order);
order.addedToEmployeeHandle = true;
LOG.info("Order " + order.id + ": Added order to employee database");
}
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (!o.addedToEmployeeHandle && System
.currentTimeMillis() - order.createdTime < employeeTime) {
var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in adding to employee db,"
+ " trying to queue task..");
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void doTasksInQueue() throws Exception {
if (queueItems != 0) {
var qt = queue.peek(); //this should probably be cloned here
//this is why we have retry for doTasksInQueue
LOG.trace("Order " + qt.order.id + ": Started doing task of type " + qt.getType());
if (qt.firstAttemptTime == -1) {
qt.firstAttemptTime = System.currentTimeMillis();
}
if (System.currentTimeMillis() - qt.firstAttemptTime >= queueTaskTime) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType()
+ " does not need to be done anymore (timeout), dequeue..");
} else {
if (qt.taskType.equals(TaskType.PAYMENT)) {
if (!qt.order.paid.equals(PaymentStatus.TRYING)) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This payment task already done, dequeueing..");
} else {
sendPaymentRequest(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service..");
}
} else if (qt.taskType.equals(TaskType.MESSAGING)) {
if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This messaging task already done, dequeue..");
} else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| !qt.order.paid.equals(PaymentStatus.TRYING))) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done,"
+ " dequeue..");
} else if (qt.messageType == 0) {
sendPaymentFailureMessage(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service..");
} else if (qt.messageType == 1) {
sendPaymentPossibleErrorMsg(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service..");
} else if (qt.messageType == 2) {
sendSuccessMessage(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service..");
}
} else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) {
if (qt.order.addedToEmployeeHandle) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This employee handle task already done,"
+ " dequeue..");
} else {
employeeHandleIssue(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to employee handle..");
}
}
}
}
if (queueItems == 0) {
LOG.trace("Queue is empty, returning..");
} else {
Thread.sleep(queueTaskTime / 3);
tryDoingTasksInQueue();
}
}
}
| 44.218698 | 100 | 0.641636 |
f89089151e70a1e8f3557f3f3cb53a7b9b1b6fa8 | 2,658 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 herddb.server;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import herddb.client.ClientConfiguration;
import herddb.client.HDBClient;
import herddb.client.HDBConnection;
import herddb.model.TableSpace;
import herddb.utils.RawString;
/**
* Demonstates the usage of the update "newvalue" facility to implement atomic-counters
*
* @author enrico.olivelli
*/
public class AtomicCounterTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void test() throws Exception {
try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
server.start();
try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));
HDBConnection connection = client.openConnection()) {
client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT,
"CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, false, true, Collections.emptyList()).updateCount;
Assert.assertEquals(1, resultCreateTable);
Assert.assertEquals(1, connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", 0, false, true, Arrays.asList("test_0", 1, 2)).updateCount);
Map<RawString, Object> newValue = connection.executeUpdate(TableSpace.DEFAULT, "UPDATE mytable set n1= n1+1 where id=?", 0, true, true, Arrays.asList("test_0")).newvalue;
assertEquals(Long.valueOf(2), newValue.get(RawString.of("n1")));
}
}
}
}
| 38.521739 | 192 | 0.72009 |
694db5f0fbc7d310807b205effcf6de29c8e5f15 | 1,247 | package com.chubz.renderer;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* I recommend not using this class and only view it as a template on how to make input.
*/
public class InputHandler implements KeyListener {
public boolean up = false;
public boolean down = false;
public boolean left = false;
public boolean right = false;
public InputHandler(Game game) {
game.addKeyListener(this);
}
public void keyPressed(KeyEvent e) {
toggle(e, true);
}
public void keyReleased(KeyEvent e) {
toggle(e, false);
}
public void releaseAll() {
up = down = left = right = false;
}
private void toggle(KeyEvent e, boolean pressed) {
if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP)
up = pressed;
if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN)
down = pressed;
if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT)
left = pressed;
if (e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT)
right = pressed;
}
// unused
public void keyTyped(KeyEvent e) {}
}
| 25.979167 | 88 | 0.613472 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.