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 |
|---|---|---|---|---|---|
e7895c129ddedb875df5b99fbfa89d96c69f4b3f | 14,113 | package tracer.easings;
import processing.core.PApplet;
/**
*
* @author James Morrow [jamesmorrowdesign.com]
*
*/
public class Easings {
private static Linear linear = new Linear();
private static QuadEaseIn quadEaseIn;
private static QuadEaseOut quadEaseOut;
private static QuadEaseInOut quadEaseInOut;
private static CubicEaseIn cubicEaseIn;
private static CubicEaseOut cubicEaseOut;
private static CubicEaseInOut cubicEaseInOut;
private static CircEaseIn circEaseIn;
private static CircEaseOut circEaseOut;
private static CircEaseInOut circEaseInOut;
private static LinearBackAndForth linearBackAndForth;
private static QuadEaseInBackAndForth quadEaseInBackAndForth;
private static QuadEaseOutBackAndForth quadEaseOutBackAndForth;
private static QuadEaseInOutBackAndForth quadEaseInOutBackAndForth;
private static CubicEaseInBackAndForth cubicEaseInBackAndForth;
private static CubicEaseOutBackAndForth cubicEaseOutBackAndForth;
private static CubicEaseInOutBackAndForth cubicEaseInOutBackAndForth;
private static CircEaseInBackAndForth circEaseInBackAndForth;
private static CircEaseOutBackAndForth circEaseOutBackAndForth;
private static CircEaseInOutBackAndForth circEaseInOutBackAndForth;
public static class Linear implements Easing {
private Linear() {}
public float val(float t) {
return t;
}
}
public static class LinearBackAndForth implements Easing {
private LinearBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
return 2f * t;
}
else {
return 2f * (1f - t);
}
}
}
public static class QuadEaseIn implements Easing {
private QuadEaseIn() {}
public float val(float t) {
return t * t;
}
}
public static class QuadEaseInBackAndForth implements Easing {
private QuadEaseInBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
t *= 2;
return t * t;
}
else {
t = (t-0.5f) * 2;
return 1f - (t * t);
}
}
}
public static class QuadEaseOut implements Easing {
private QuadEaseOut() {}
public float val(float t) {
return -t * (t - 2);
}
}
public static class QuadEaseOutBackAndForth implements Easing {
private QuadEaseOutBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
t *= 2;
return -t * (t - 2);
}
else {
t = (t-0.5f) * 2;
return 1f + (t * (t - 2));
}
}
}
public static class QuadEaseInOut implements Easing {
private QuadEaseInOut() {}
public float val(float t) {
t *= 2;
if (t < 1) {
return 0.5f * t * t;
}
t--;
return -0.5f * (t * (t - 2) - 1);
}
}
public static class QuadEaseInOutBackAndForth implements Easing {
private QuadEaseInOutBackAndForth() {}
public float val(float t) {
if (t < 0.5) {
t *= 4;
if (t < 1) {
return 0.5f * t * t;
}
t--;
return -0.5f * (t * (t - 2) - 1);
}
else {
t = (t - 0.5f) * 4f;
if (t < 1) {
return 1f - (0.5f * t * t * t);
}
t -= 2;
return 1f - (0.5f * (t * t * t + 2));
}
}
}
public static class CubicEaseIn implements Easing {
private CubicEaseIn() {}
public float val(float t) {
return t * t * t;
}
}
public static class CubicEaseInBackAndForth implements Easing {
private CubicEaseInBackAndForth() {}
public float val(float t) {
if (t < 0.5) {
t *= 2;
return t * t * t;
}
else {
t = ((t - 0.5f) * 2f);
return 1f - (t * t * t);
}
}
}
public static class CubicEaseOut implements Easing {
private CubicEaseOut() {}
public float val(float t) {
t--;
return t * t * t + 1;
}
}
public static class CubicEaseOutBackAndForth implements Easing {
private CubicEaseOutBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
t = (2f * t) - 1f;
return t * t * t + 1;
}
else {
t = (2f * (t-0.5f)) - 1f;
return 1f - (t * t * t + 1);
}
}
}
public static class CubicEaseInOut implements Easing {
private CubicEaseInOut() {}
public float val(float t) {
t *= 2;
if (t < 1) {
return 0.5f * t * t * t;
}
t -= 2;
return 0.5f * (t * t * t + 2);
}
}
public static class CubicEaseInOutBackAndForth implements Easing {
private CubicEaseInOutBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
t *= 4f;
if (t < 1) {
return 0.5f * t * t * t;
}
t -= 2;
return 0.5f * (t * t * t + 2);
}
else {
t = (t-0.5f) * 4f;
if (t < 1) {
return 1f - (0.5f * t * t * t);
}
t -= 2;
return 1f - (0.5f * (t * t * t + 2));
}
}
}
public static class CircEaseIn implements Easing {
private CircEaseIn() {}
public float val(float t) {
return -(PApplet.sqrt(1 - t * t) - 1);
}
}
public static class CircEaseOut implements Easing {
private CircEaseOut() {}
public float val(float t) {
t--;
return PApplet.sqrt(1 - t * t);
}
}
public static class CircEaseInOut implements Easing {
private CircEaseInOut() {}
public float val(float t) {
t *= 2;
if (t < 1) {
return -0.5f * (PApplet.sqrt(1 - t * t) - 1);
}
t -= 2;
return 0.5f * (PApplet.sqrt(1 - t * t) + 1);
}
}
public static class CircEaseInBackAndForth implements Easing {
private CircEaseInBackAndForth () {}
public float val(float t) {
if (t < 0.5f) {
t *= 2;
return -(PApplet.sqrt(1 - t * t) - 1);
}
else {
t = 2f * (t-0.5f);
return 1f + (PApplet.sqrt(1 - t * t) - 1);
}
}
}
public static class CircEaseOutBackAndForth implements Easing {
private CircEaseOutBackAndForth () {}
public float val(float t) {
if (t < 0.5f) {
t = (2f * t) - 1f;
return PApplet.sqrt(1 - t * t);
}
else {
t = 2f * (t-0.5f) - 1f;
return 1f - PApplet.sqrt(1 - t * t);
}
}
}
public static class CircEaseInOutBackAndForth implements Easing {
private CircEaseInOutBackAndForth() {}
public float val(float t) {
if (t < 0.5f) {
t *= 4;
if (t < 1) {
return -0.5f * (PApplet.sqrt(1 - t * t) - 1);
}
t -= 2;
return 0.5f * (PApplet.sqrt(1 - t * t) + 1);
}
else {
t = (t - 0.5f) * 4f;
if (t < 1) {
return 1f + (0.5f * (PApplet.sqrt(1 - t * t) - 1));
}
t -= 2;
return 1f - (0.5f * (PApplet.sqrt(1 - t * t) + 1));
}
}
}
public static Linear getLinear() {
if (linear == null) {
linear = new Linear();
}
return linear;
}
public static LinearBackAndForth getLinearBackAndForth() {
if (linearBackAndForth == null) {
linearBackAndForth = new LinearBackAndForth();
}
return linearBackAndForth;
}
public static QuadEaseIn getQuadEaseIn() {
if (quadEaseIn == null) {
quadEaseIn = new QuadEaseIn();
}
return quadEaseIn;
}
public static QuadEaseOut getQuadEaseOut() {
if (quadEaseOut == null) {
quadEaseOut = new QuadEaseOut();
}
return quadEaseOut;
}
public static QuadEaseInOut getQuadEaseInOut() {
if (quadEaseInOut == null) {
quadEaseInOut = new QuadEaseInOut();
}
return quadEaseInOut;
}
public static QuadEaseInBackAndForth getQuadEaseInBackAndForth() {
if (quadEaseInBackAndForth == null) {
quadEaseInBackAndForth = new QuadEaseInBackAndForth();
}
return quadEaseInBackAndForth;
}
public static QuadEaseOutBackAndForth getQuadEaseOutBackAndForth() {
if (quadEaseOutBackAndForth == null) {
quadEaseOutBackAndForth = new QuadEaseOutBackAndForth();
}
return quadEaseOutBackAndForth;
}
public static QuadEaseInOutBackAndForth getQuadEaseInOutBackAndForth() {
if (quadEaseInOutBackAndForth == null) {
quadEaseInOutBackAndForth = new QuadEaseInOutBackAndForth();
}
return quadEaseInOutBackAndForth;
}
public static CubicEaseIn getCubicEaseIn() {
if (cubicEaseIn == null) {
cubicEaseIn = new CubicEaseIn();
}
return cubicEaseIn;
}
public static CubicEaseOut getCubicEaseOut() {
if (cubicEaseOut == null) {
cubicEaseOut = new CubicEaseOut();
}
return cubicEaseOut;
}
public static CubicEaseInOut getCubicEaseInOut() {
if (cubicEaseInOut == null) {
cubicEaseInOut = new CubicEaseInOut();
}
return cubicEaseInOut;
}
public static CubicEaseInBackAndForth getCubicEaseInBackAndForth() {
if (cubicEaseInBackAndForth == null) {
cubicEaseInBackAndForth = new CubicEaseInBackAndForth();
}
return cubicEaseInBackAndForth;
}
public static CubicEaseOutBackAndForth getCubicEaseOutBackAndForth() {
if (cubicEaseOutBackAndForth == null) {
cubicEaseOutBackAndForth = new CubicEaseOutBackAndForth();
}
return cubicEaseOutBackAndForth;
}
public static CubicEaseInOutBackAndForth getCubicEaseInOutBackAndForth() {
if (cubicEaseInOutBackAndForth == null) {
cubicEaseInOutBackAndForth = new CubicEaseInOutBackAndForth();
}
return cubicEaseInOutBackAndForth;
}
public static CircEaseIn getCircEaseIn() {
if (circEaseIn == null) {
circEaseIn = new CircEaseIn();
}
return circEaseIn;
}
public static CircEaseOut getCircEaseOut() {
if (circEaseOut == null) {
circEaseOut = new CircEaseOut();
}
return circEaseOut;
}
public static CircEaseInOut getCircEaseInOut() {
if (circEaseInOut == null) {
circEaseInOut = new CircEaseInOut();
}
return circEaseInOut;
}
public static CircEaseInBackAndForth getCircEaseInBackAndForth() {
if (circEaseInBackAndForth == null) {
circEaseInBackAndForth = new CircEaseInBackAndForth();
}
return circEaseInBackAndForth;
}
public static CircEaseOutBackAndForth getCircEaseOutBackAndForth() {
if (circEaseOutBackAndForth == null) {
circEaseOutBackAndForth = new CircEaseOutBackAndForth();
}
return circEaseOutBackAndForth;
}
public static CircEaseInOutBackAndForth getCircEaseInOutBackAndForth() {
if (circEaseInOutBackAndForth == null) {
circEaseInOutBackAndForth = new CircEaseInOutBackAndForth();
}
return circEaseInOutBackAndForth;
}
public static int getEasingCount() {
return 20;
}
public static Easing getEasing(int i) {
switch (i) {
case 0 : return getLinear();
case 1 : return getQuadEaseIn();
case 2 : return getQuadEaseOut();
case 3 : return getQuadEaseInOut();
case 4 : return getCubicEaseIn();
case 5 : return getCubicEaseOut();
case 6 : return getCubicEaseInOut();
case 7 : return getCircEaseIn();
case 8 : return getCircEaseOut();
case 9 : return getCircEaseInOut();
case 10: return getLinearBackAndForth();
case 11 : return getQuadEaseInBackAndForth();
case 12 : return getQuadEaseOutBackAndForth();
case 13 : return getQuadEaseInOutBackAndForth();
case 14 : return getCubicEaseInBackAndForth();
case 15 : return getCubicEaseOutBackAndForth();
case 16 : return getCubicEaseInOutBackAndForth();
case 17 : return getCircEaseInBackAndForth();
case 18 : return getCircEaseOutBackAndForth();
case 19 : return getCircEaseInOutBackAndForth();
default : throw new IndexOutOfBoundsException("Easing " + i + " does not exist.");
}
}
}
| 29.280083 | 94 | 0.508822 |
63bff3f8e0334031b73c901fe46f17cafcb8a978 | 1,240 | package rocks.inspectit.agent.java.proxy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation has to be placed on subtypes of {@link IProxySubject}, to define the proxy class.
* This way, the superclass and the implemented interfaces of the runtime generated proxy are
* defined, the actual proxied methods are defined using the {@link ProxyMethod} annotation.
* Additionally, this annotation can define the constructor of the superclass of the proxy which
* will be used.
*
* @author Jonas Kunz
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ProxyFor {
// NOCHKALL
/**
* @return the full qualified name of the super class of the proxy class. Defaults to
* "java.lang.Object"
*/
String superClass() default "java.lang.Object";
/**
* @return the full qualified name of all implemented interfaces of the proxy class.
*/
String[] implementedInterfaces() default {};
/**
* @return the signature of the superclass constructor to use. Default is the no-args
* constructor
*/
String[] constructorParameterTypes() default {};
}
| 31 | 100 | 0.741129 |
a99438a68770d4a9e8f2405a39be4518c07a0aed | 744 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.eldermoraes.apptest.beans;
/**
*
* @author eldermoraes
*/
public class TestData {
private String hostAddress;
private String canonicalHostName;
public String getHostAddress() {
return hostAddress;
}
public void setHostAddress(String hostAddress) {
this.hostAddress = hostAddress;
}
public String getCanonicalHostName() {
return canonicalHostName;
}
public void setCanonicalHostName(String canonicalHostName) {
this.canonicalHostName = canonicalHostName;
}
}
| 21.882353 | 79 | 0.696237 |
7b995b7473a9cca78545674cca93e4f7b96de9ac | 5,822 | package com.eventshop.eventshoplinux.util.datasourceUtil.wrapper;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.eventshop.eventshoplinux.domain.common.FrameParameters;
import com.eventshop.eventshoplinux.domain.datasource.emage.STTPoint;
import com.eventshop.eventshoplinux.domain.datasource.simulator.DataPoint;
import com.eventshop.eventshoplinux.util.commonUtil.Config;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
public class SimDataWrapperFromWS extends Wrapper implements Runnable {
protected static Log log = LogFactory.getLog(SimDataWrapperFromWS.class);
long dsid;
long curWindowEnd;
boolean isRunning;
LinkedBlockingQueue<STTPoint> sttStream;
int[][] count;
public SimDataWrapperFromWS(String url, String theme,
FrameParameters params, int dsid) {
super(url, theme, params);
this.dsid = dsid;
int numOfRows = params.getNumOfRows();
int numOfColumns = params.getNumOfColumns();
count = new int[numOfRows][numOfColumns];
for (int i = 0; i < numOfRows; i++)
for (int j = 0; j < numOfColumns; j++)
count[i][j] = 0;
curWindowEnd = 0;
sttStream = new LinkedBlockingQueue<STTPoint>();
}
private static URI getBaseURI() {
return UriBuilder.fromUri(Config.getProperty("esuri")).build();
}
@Override
public void run() {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
isRunning = true;
boolean firstEntry = true;
Gson gson = new Gson();
JsonParser jparser = new JsonParser();
while (isRunning) {
String json = service.path("rest").path("datasource/id/" + dsid)
.accept(MediaType.APPLICATION_JSON).get(String.class);
if (json.equals("null")) {
try {
Thread.sleep(Math.max(curWindowEnd + params.timeWindow
- System.currentTimeMillis(), 1000));
} catch (InterruptedException e) {
log.error(e.getMessage());
}
continue;
}
JsonObject datapoints = jparser.parse(json).getAsJsonObject();
JsonArray dataArray = datapoints.getAsJsonArray("dataPoint");
ArrayList<DataPoint> points = gson.fromJson(dataArray,
new TypeToken<ArrayList<DataPoint>>() {
}.getType());
log.info("Number of points is " + points.size());
for (int i = 0; i < points.size(); ++i) {
double lat = points.get(i).spatial.lat;
double lon = points.get(i).spatial.lon;
// if the first element arrives, update the end time of the
// current frame
if (firstEntry) {
long now = Long.valueOf(points.get(i).timevalue);
curWindowEnd = (long) Math.ceil(now / params.timeWindow)
* params.timeWindow + params.syncAtMilSec;
firstEntry = false;
}
MathContext context = new MathContext(5);
int r = (int) Math.floor(Math.abs((BigDecimal.valueOf(lat))
.subtract(BigDecimal.valueOf(params.swLat), context)
.divide(BigDecimal.valueOf(params.latUnit), context)
.doubleValue()));
int c = (int) Math.floor(Math.abs((BigDecimal.valueOf(lon))
.subtract(BigDecimal.valueOf(params.swLong), context)
.divide(BigDecimal.valueOf(params.longUnit), context)
.doubleValue()));
// update the value in the corresponding cell
count[r][c]++;
}
// Create the corresponding STT points
for (int i = 0; i < params.getNumOfRows(); i++) {
for (int j = 0; j < params.getNumOfColumns(); j++) {
double lat = params.swLat + (i + 0.5) * params.latUnit; // pick
// the
// center
double lon = params.swLong + (j + 0.5) * params.longUnit;
STTPoint stt = new STTPoint(count[i][j], new Date(
curWindowEnd - params.timeWindow), new Date(
curWindowEnd), params.latUnit, params.longUnit,
lat, lon, theme);
sttStream.add(stt);
// clear the count
count[i][j] = 0;
}
}
// Update the new window
curWindowEnd += params.timeWindow;
}
}
@Override
public boolean stop() {
isRunning = false;
Thread.currentThread().interrupt();
return true;
}
@Override
public boolean hasNext() {
return (sttStream.peek() != null);
}
@Override
public STTPoint next() {
try {
return sttStream.take();
} catch (InterruptedException e) {
log.error(e.getMessage());
}
return null;
}
@Override
public void remove() {
sttStream.remove();
}
public static void main(String[] args) {
try {
long timeWindow = 1000 * 30;
long sync = 0;
double latUnit = 1;
double longUnit = 1;
double swLat = 25;
double swLong = -125;
double neLat = 50;
double neLong = -65;
FrameParameters params = new FrameParameters(timeWindow, sync,
latUnit, longUnit, swLat, swLong, neLat, neLong);
String url = Config.getProperty("simURL");
SimDataWrapperFromWS wrapper = new SimDataWrapperFromWS(url, "flu",
params, 0);
// Start the wrapper
new Thread(wrapper).start();
while (true) {
while (wrapper.hasNext()) {
STTPoint point = wrapper.next();
SimDataWrapperFromWS.log.info(point.latitude + " " + point.longitude
+ " " + point.value + " , ");
}
Thread.sleep(1000);
}
} catch (Exception e) {
log.error(e.getMessage());
}
System.exit(0);
}
}
| 28.539216 | 74 | 0.683442 |
119ac48fbdb79c786b63accd2a4fa358c315a082 | 5,501 | /*
* Sematext Cloud API
* API Explorer provides access and documentation for Sematext REST API. The REST API requires the API Key to be sent as part of `Authorization` header. E.g.: `Authorization : apiKey e5f18450-205a-48eb-8589-7d49edaea813`.
*
* OpenAPI spec version: v3
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.sematext.cloud.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.IOException;
/**
* UserRole
*/
public class UserRole {
/**
* Gets or Sets role
*/
@JsonAdapter(RoleEnum.Adapter.class)
public enum RoleEnum {
SUPER_USER("SUPER_USER"),
OWNER("OWNER"),
ADMIN("ADMIN"),
USER("USER"),
DEMO("DEMO"),
ANONYMOUS("ANONYMOUS");
private String value;
RoleEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static RoleEnum fromValue(String input) {
for (RoleEnum b : RoleEnum.values()) {
if (b.value.equals(input)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<RoleEnum> {
@Override
public void write(final JsonWriter jsonWriter, final RoleEnum enumeration) throws IOException {
jsonWriter.value(String.valueOf(enumeration.getValue()));
}
@Override
public RoleEnum read(final JsonReader jsonReader) throws IOException {
Object value = jsonReader.nextString();
return RoleEnum.fromValue((String)(value));
}
}
} @SerializedName("role")
private RoleEnum role = null;
/**
* Gets or Sets roleStatus
*/
@JsonAdapter(RoleStatusEnum.Adapter.class)
public enum RoleStatusEnum {
INACTIVE("INACTIVE"),
ACTIVE("ACTIVE");
private String value;
RoleStatusEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static RoleStatusEnum fromValue(String input) {
for (RoleStatusEnum b : RoleStatusEnum.values()) {
if (b.value.equals(input)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<RoleStatusEnum> {
@Override
public void write(final JsonWriter jsonWriter, final RoleStatusEnum enumeration) throws IOException {
jsonWriter.value(String.valueOf(enumeration.getValue()));
}
@Override
public RoleStatusEnum read(final JsonReader jsonReader) throws IOException {
Object value = jsonReader.nextString();
return RoleStatusEnum.fromValue((String)(value));
}
}
} @SerializedName("roleStatus")
private RoleStatusEnum roleStatus = null;
@SerializedName("userEmail")
private String userEmail = null;
public UserRole role(RoleEnum role) {
this.role = role;
return this;
}
/**
* Get role
* @return role
**/
@Schema(description = "")
public RoleEnum getRole() {
return role;
}
public void setRole(RoleEnum role) {
this.role = role;
}
public UserRole roleStatus(RoleStatusEnum roleStatus) {
this.roleStatus = roleStatus;
return this;
}
/**
* Get roleStatus
* @return roleStatus
**/
@Schema(description = "")
public RoleStatusEnum getRoleStatus() {
return roleStatus;
}
public void setRoleStatus(RoleStatusEnum roleStatus) {
this.roleStatus = roleStatus;
}
public UserRole userEmail(String userEmail) {
this.userEmail = userEmail;
return this;
}
/**
* Get userEmail
* @return userEmail
**/
@Schema(description = "")
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UserRole userRole = (UserRole) o;
return Objects.equals(this.role, userRole.role) &&
Objects.equals(this.roleStatus, userRole.roleStatus) &&
Objects.equals(this.userEmail, userRole.userEmail);
}
@Override
public int hashCode() {
return Objects.hash(role, roleStatus, userEmail);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UserRole {\n");
sb.append(" role: ").append(toIndentedString(role)).append("\n");
sb.append(" roleStatus: ").append(toIndentedString(roleStatus)).append("\n");
sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 24.558036 | 221 | 0.652063 |
b242b0d6c0069528a75ff44ef2a1544a2eb7f652 | 1,770 | /*
* Copyright (c) 2018 Absolute Apogee Technologies Ltd. All rights reserved.
*
* =============================================================================
* Revision History:
* Date Author Detail
* ----------- -------------- ------------------------------------------------
* 2018-Dec-24 GShokar Created
* =============================================================================
*/
package ca.aatl.app.invoicebook.bl.rest;
import java.security.Principal;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
/**
*
* @author GShokar
*/
public class AppSecurity implements SecurityContext{
public static final String ROLE_ADMIN = "ADMIN";
private AppUserPrincipal user;
/**
* Get the value of user
*
* @return the value of user
*/
public AppUserPrincipal getUser() {
return user;
}
/**
* Set the value of user
*
* @param user new value of user
*/
public void setUser(AppUserPrincipal user) {
this.user = user;
}
public AppSecurity(AppUserPrincipal user, UriInfo uriInfo) {
this.user = user;
this.uriInfo = uriInfo;
}
private UriInfo uriInfo;
@Override
public Principal getUserPrincipal() {
return user;
}
@Override
public boolean isUserInRole(String role) {
return ROLE_ADMIN.equals(role);
}
@Override
public boolean isSecure() {
return uriInfo != null && uriInfo.getAbsolutePath().toString().startsWith("https");
}
@Override
public String getAuthenticationScheme() {
return "Token-Based-Auth-Scheme";
}
}
| 24.246575 | 92 | 0.510734 |
ceafb8d21e1e3e3005cf094bc243778c6a55c5c0 | 954 | package ua.ikonovalov;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* class Converter
* @autor ikonovalov
* @since 11.12.18
*/
public class Converter {
/**
* @param it iterator
* @return
*/
Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {
/**
* Anonymous class Iterator
*/
return new Iterator<Integer>() {
Iterator<Integer> instantIterator = it.next();
@Override
public boolean hasNext() {
while (!instantIterator.hasNext() && it.hasNext()) {
instantIterator = it.next();
}
return instantIterator.hasNext();
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return instantIterator.next();
}
};
}
}
| 22.186047 | 68 | 0.512579 |
63e82b156a7a8b49f1c25f5eccb447d2ed0e503a | 3,345 | package com.whichard.spring.boot.blog.controlller;
import java.util.ArrayList;
import java.util.List;
import com.whichard.spring.boot.blog.domain.User;
import com.whichard.spring.boot.blog.service.AuthorityService;
import com.whichard.spring.boot.blog.service.BadIpLoginService;
import com.whichard.spring.boot.blog.service.UserService;
import com.whichard.spring.boot.blog.util.ConstraintViolationExceptionHandler;
import com.whichard.spring.boot.blog.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.whichard.spring.boot.blog.domain.Authority;
import javax.validation.ConstraintViolationException;
/**
* 主页控制器.
*
* @author <a href="http://www.whichard.cn">Whichard</a>
* @since 1.0.0 2018年5月28日
*/
@Controller
public class MainController {
private static final Long ROLE_USER_AUTHORITY_ID = 3L;
@Autowired
private UserService userService;
@Autowired
private AuthorityService authorityService;
@GetMapping(path = {"/index", "/"})
public String index() {
return "redirect:/blogs";
}
@GetMapping("/test")
public String test() {
return "test";
}
@GetMapping("/login")
public String login() {
if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
&& !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().equals("anonymousUser")) {
return "redirect:/index";
} else
return "login";
}
@GetMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
model.addAttribute("errorMsg", "登陆失败,用户名或者密码错误!");
return "login";
}
@GetMapping("/register")
public String register() {
return "register";
}
/**
* 注册用户
*
* @param user
* @return
*/
@PostMapping("/register")
public ResponseEntity<Response> registerUser(User user) {
List<Authority> authorities = new ArrayList<>();
authorities.add(authorityService.getAuthorityById(ROLE_USER_AUTHORITY_ID));
user.setAuthorities(authorities);
user.setEncodePassword(user.getPassword());
try {
userService.registerUser(user);
} catch (ConstraintViolationException e) {
return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e)));
} catch (Exception e) {
return ResponseEntity.ok().body(new Response(false, e.getMessage()));
}
return ResponseEntity.ok().body(new Response(true, "注册成功", null));
}
}
| 33.45 | 150 | 0.715396 |
2e2b2eda74fc8c1f478efe44ba702452582d7f9c | 5,493 | package rpc.turbo.benchmark.bytebuf;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import rpc.turbo.util.UnsafeUtils;
@State(Scope.Thread)
public class ByteBufferBenchmark {
final byte[] bytes = new byte[1024];
final ByteBuffer heapByteBuffer = ByteBuffer.allocate(1024);
final ByteBuffer directByteBuffer = ByteBuffer.allocateDirect(1024);
final ByteBuf nettyByteBuf = PooledByteBufAllocator.DEFAULT.buffer(1024, 1024);
final long OFFSET = UnsafeUtils.unsafe().allocateMemory(1024);
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void _do_nothing() {
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToBytes() {
for (int i = 0; i < 1024; i++) {
bytes[i] = 1;
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToHeap() {
for (int i = 0; i < 1024; i++) {
heapByteBuffer.put(i, (byte) 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToDirect() {
for (int i = 0; i < 1024; i++) {
directByteBuffer.put(i, (byte) 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToNetty() {
for (int i = 0; i < 1024; i++) {
nettyByteBuf.setByte(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToDirectAndCopyToNetty() {
for (int i = 0; i < 1024; i++) {
directByteBuffer.put(i, (byte) 1);
}
nettyByteBuf.setBytes(0, directByteBuffer);
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeByteToUnsafe() {
for (int i = 0; i < 1024; i++) {
UnsafeUtils.unsafe().putByte(OFFSET + i, (byte) 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToBytes() {
for (int i = 0; i < 1024; i += 4) {
bytes[i] = 1;
bytes[i + 1] = 1;
bytes[i + 2] = 1;
bytes[i + 3] = 1;
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToHeap() {
for (int i = 0; i < 1024; i += 4) {
heapByteBuffer.putInt(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToDirect() {
for (int i = 0; i < 1024; i += 4) {
directByteBuffer.putInt(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToNetty() {
for (int i = 0; i < 1024; i += 4) {
nettyByteBuf.setInt(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToDirectAndCopyToNetty() {
for (int i = 0; i < 1024; i += 4) {
directByteBuffer.putInt(i, 1);
}
nettyByteBuf.setBytes(0, directByteBuffer);
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeIntToUnsafe() {
for (int i = 0; i < 1024; i += 4) {
UnsafeUtils.unsafe().putInt(OFFSET + i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToBytes() {
for (int i = 0; i < 1024; i += 8) {
bytes[i] = 1;
bytes[i + 1] = 1;
bytes[i + 2] = 1;
bytes[i + 3] = 1;
bytes[i + 4] = 1;
bytes[i + 5] = 1;
bytes[i + 6] = 1;
bytes[i + 7] = 1;
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToHeap() {
for (int i = 0; i < 1024; i += 8) {
heapByteBuffer.putLong(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToDirect() {
for (int i = 0; i < 1024; i += 8) {
directByteBuffer.putLong(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToNetty() {
for (int i = 0; i < 1024; i += 8) {
nettyByteBuf.setLong(i, 1);
}
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToDirectAndCopyToNetty() {
for (int i = 0; i < 1024; i += 8) {
directByteBuffer.putLong(i, 1);
}
nettyByteBuf.setBytes(0, directByteBuffer);
}
@Benchmark
@BenchmarkMode({ Mode.Throughput })
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void writeLongToUnsafe() {
for (int i = 0; i < 1024; i += 8) {
UnsafeUtils.unsafe().putInt(OFFSET + i, 1);
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()//
.include(ByteBufferBenchmark.class.getName())//
.warmupIterations(5)//
.measurementIterations(5)//
.threads(8)//
.forks(1)//
.build();
new Runner(opt).run();
}
}
| 24.198238 | 80 | 0.685964 |
05f0464e3bb59fc6fce4dca38cf82e3a18ae90f4 | 380 | package com.stylefeng.guns.film.common.persistence.dao;
import com.stylefeng.guns.film.common.persistence.model.MoocBannerT;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* banner信息表 Mapper 接口
* </p>
*
* @author wyw
* @since 2018-12-27
*/
public interface MoocBannerTMapper extends BaseMapper<MoocBannerT> {
}
| 21.111111 | 68 | 0.760526 |
e0da33e79b68df3695ee331ce1118b6963e35290 | 927 | package jcf.extproc.process;
import java.io.Serializable;
/**
*
* 외부 프로세스 정의
* @author setq
*
*/
public interface ExternalProcess extends Serializable {
/**
* 작업 명. (파일시스템 디렉토리 이름).
* <p>
* 작업 명이 같은 것은 동시 수행이 되지 않음.
* <p>
* 디렉토리 구조로 여러 계층을 둘 수 있지만, 일부 계층을 공유하는 작업들 끼리는 계층 수준이 같아야 한다.
* 예를 들어 a/b/c 와 a/b/d 는 허용되지만 a/b는 계층이 다르기 때문에 디렉토리 관리상의 이유로 (삭제 할 경우 타 작업 훼손 등) 허용되지 않는다.
* @return
*/
String getName();
/**
* 작업 설명
* @return
*/
String getDescription();
void accept(ExternalProcessVisitor visitor);
/**
* 프로세스 유형에 따라 exit value가 아닌 콘솔 출력 내용으로 성공/실패 여부를 갈라야할 경우가 있다.
* 이 경우 특정 라인 검출시 실패로 해야하는 경우의 로직 제공.
* @param line
* @return
*/
boolean checkForFailure(String line);
/**
* 프로세스 등록자. 프로세스 실행시 사용자 명이 지정되지 않은 경우 등록자 값으로 들어가게 된다. (스케쥴러에 의한 트리거 등)
* @return
*/
String getUser();
LogFileKeepingPolicy getLogFileKeepingPolicy();
String getWorkDirectory();
}
| 17.490566 | 94 | 0.632147 |
0d493e4941c1fba9525ca83e5355c425a88b92da | 500 | package ormmp;
import java.io.IOException;
import java.lang.reflect.Field;
public class pruebaORM {
public static void main(String[] args) throws IOException{
try {
Class cls = Class.forName("com.millenniumprogrammers.neocomer.model.Roles");
Field[]campos = cls.getDeclaredFields();
for(Field cam : campos)
System.out.println(cam.getName().toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 19.230769 | 79 | 0.692 |
60b2c0d4da60ec10811e68ba89f53f574707c4d4 | 986 | package com.amplifino.obelix.segments;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.IntStream;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
public class FlatStreamTest {
private int invocationCount;
public boolean tryAdd(String string) {
invocationCount++;
return true;
}
@Test
@Ignore
public void test() {
System.out.println(System.getProperty("java.version"));
Stream<String> stream = new StreamProvider().stream();
Optional<String> result = stream.filter(this::tryAdd).findFirst();
assertEquals("a", result.get());
assertEquals(1, invocationCount);
}
private class StreamProvider {
Stream<String> stream() {
return Stream.of("aaaaaaaaaaaaaa").flatMap(this::flatten);
}
private Stream<String> flatten(String in) {
return IntStream.range(1, in.length())
.mapToObj(val -> in.substring(0,val));
}
}
}
| 21.434783 | 69 | 0.678499 |
ac20ce1f934414cd49e863e249204e1b7f7debf2 | 1,770 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-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.kuali.kra.budget.document;
import org.junit.Test;
import org.kuali.coeus.common.budget.framework.period.BudgetPeriod;
import org.kuali.kra.test.infrastructure.KcIntegrationTestBase;
import org.kuali.rice.krad.util.ObjectUtils;
import static org.junit.Assert.*;
/**
* Testing ObjectUtils equalsByKey logic change
*
* @author Kuali Rice Team (kuali-rice@googlegroups.com)
*/
public class ObjectUtilsTest extends KcIntegrationTestBase {
@Test
public void testObjectUtils_equalsByKey() throws Exception {
BudgetPeriod periodDB = new BudgetPeriod();
periodDB.setBudgetPeriodId(new Long(268));
// periodDB.setProposalNumber("103");
// periodDB.setBudgetVersionNumber(1);
periodDB.setBudgetPeriod(3);
BudgetPeriod periodNew = new BudgetPeriod();
periodNew.setBudgetPeriodId(null);
// periodNew.setProposalNumber(null);
// periodNew.setBudgetVersionNumber(null);
periodNew.setBudgetPeriod(3);
boolean equalsResult = false;
equalsResult = ObjectUtils.equalByKeys(periodDB, periodNew);
assertFalse(equalsResult);
}
}
| 36.875 | 81 | 0.727119 |
a45644d38f02c914a216afc9f6b9f30380f5359b | 841 | /*
* Copyright (c) 2017. Ryan Davis <Ryandavis84@gmail.com> Swagger Diff java CLI
*/
package com.rdavis.swagger.parsers.impl;
import com.rdavis.swagger.parsers.SwaggerDiffParser;
import com.rdavis.swagger.rules.BrokenRule;
import com.rdavis.swagger.rules.Rule;
import v2.io.swagger.models.Swagger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SwaggerDiffParserV1 implements SwaggerDiffParser {
@Override
public List<BrokenRule> applyRules(Swagger currentSwagger, Swagger deployedSwagger, Map<String, Rule> rules) {
List<BrokenRule> brokenRules = new ArrayList<>();
for (Map.Entry<String, Rule> ruleEntry : rules.entrySet()) {
brokenRules.addAll(ruleEntry.getValue().validate(currentSwagger, deployedSwagger));
}
return brokenRules;
}
}
| 30.035714 | 114 | 0.737218 |
39e299e06ff2785582b1ae8209ecb5ced4febb9c | 9,530 | /*
* Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xuexiang.xpush.mqtt;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.xuexiang.xpush.XPush;
import com.xuexiang.xpush.core.IPushClient;
import com.xuexiang.xpush.core.XPushManager;
import com.xuexiang.xpush.logs.PushLog;
import com.xuexiang.xpush.mqtt.agent.MqttPersistence;
import com.xuexiang.xpush.mqtt.agent.MqttPushAgent;
import com.xuexiang.xpush.mqtt.core.MqttCore;
import com.xuexiang.xpush.mqtt.core.callback.MqttEventListenerAdapter;
import com.xuexiang.xpush.mqtt.core.callback.OnMqttActionListener;
import com.xuexiang.xpush.mqtt.core.callback.OnMqttEventListener;
import com.xuexiang.xpush.mqtt.core.entity.ConnectionStatus;
import com.xuexiang.xpush.mqtt.core.entity.MqttAction;
import com.xuexiang.xpush.mqtt.core.entity.Subscription;
import com.xuexiang.xpush.util.PushUtils;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.util.Set;
import static com.xuexiang.xpush.core.annotation.CommandType.TYPE_ADD_TAG;
import static com.xuexiang.xpush.core.annotation.CommandType.TYPE_DEL_TAG;
import static com.xuexiang.xpush.core.annotation.CommandType.TYPE_GET_TAG;
import static com.xuexiang.xpush.core.annotation.CommandType.TYPE_REGISTER;
import static com.xuexiang.xpush.core.annotation.CommandType.TYPE_UNREGISTER;
import static com.xuexiang.xpush.core.annotation.ConnectStatus.CONNECTED;
import static com.xuexiang.xpush.core.annotation.ConnectStatus.CONNECTING;
import static com.xuexiang.xpush.core.annotation.ConnectStatus.DISCONNECT;
import static com.xuexiang.xpush.core.annotation.ResultCode.RESULT_ERROR;
import static com.xuexiang.xpush.core.annotation.ResultCode.RESULT_OK;
import static com.xuexiang.xpush.mqtt.core.entity.MqttAction.SUBSCRIBE;
/**
* MQTT实现的消息推送
*
* @author xuexiang
* @since 2019-12-11 22:38
*/
public class MqttPushClient implements IPushClient {
public static final String MQTT_PUSH_PLATFORM_NAME = "MqttPush";
public static final int MQTT_PUSH_PLATFORM_CODE = 1010;
private static final String MQTT_HOST = "MQTT_HOST";
private static final String MQTT_PORT = "MQTT_PORT";
/**
* 反射构造方法
*/
public MqttPushClient() {
}
/**
* 主动构造方法
*
* @param builder
*/
public MqttPushClient(MqttCore.Builder builder) {
MqttPushAgent.getInstance().init(builder);
}
@Override
public void init(Context context) {
if (!MqttPushAgent.isInitialized()) {
//我将读取AndroidManifest.xml中port和host改为读取SP中的
//读取MQTT连接服务器对应的host和port
// try {
// Bundle metaData = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData;
// String host = metaData.getString(MQTT_HOST).trim();
// int port = metaData.getInt(MQTT_PORT, MqttCore.DEFAULT_MQTT_PORT);
// String host = MqttPersistence.getServerHost();
// int port = MqttPersistence.getServerPort();
// MqttPushAgent.getInstance().init(context, host, port);
MqttPushAgent.getInstance().init(context);
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// PushLog.e("can't find MQTT_HOST or MQTT_PORT in AndroidManifest.xml");
// } catch (NullPointerException e) {
// e.printStackTrace();
// PushLog.e("can't find MQTT_HOST or MQTT_PORT in AndroidManifest.xml");
// }
}
}
@Override
public void register() {
if (MqttPushAgent.getInstance().register(mOnMqttActionListener)) {
MqttPushAgent.getInstance().setOnMqttEventListener(mOnMqttEventListener);
} else {
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_REGISTER, RESULT_ERROR, null, null, "推送已注册");
}
}
@Override
public void unRegister() {
if (MqttPushAgent.getInstance().unRegister()) {
MqttPushAgent.getInstance().setOnMqttEventListener(null);
} else {
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_UNREGISTER, RESULT_ERROR, null, null, "推送尚未注册");
}
}
@Override
public void bindAlias(String alias) {
}
@Override
public void unBindAlias(String alias) {
}
@Override
public void getAlias() {
}
@Override
public void addTags(String... tag) {
if (!MqttPushAgent.getInstance().addTags(tag)) {
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_ADD_TAG, RESULT_ERROR, null, null, "推送尚未连接");
}
}
@Override
public void deleteTags(String... tag) {
if (!MqttPushAgent.getInstance().deleteTags(tag)) {
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_DEL_TAG, RESULT_ERROR, null, null, "推送尚未连接");
}
}
@Override
public void getTags() {
Set<String> tags = MqttPushAgent.getInstance().getTags();
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_GET_TAG, RESULT_OK, PushUtils.collection2String(tags), null, null);
}
@Override
public String getPushToken() {
return MqttPushAgent.getPushToken();
}
@Override
public int getPlatformCode() {
return MQTT_PUSH_PLATFORM_CODE;
}
@Override
public String getPlatformName() {
return MQTT_PUSH_PLATFORM_NAME;
}
/**
* 动作监听
*/
private OnMqttActionListener mOnMqttActionListener = new OnMqttActionListener() {
@Override
public void onActionSuccess(MqttAction action, IMqttToken actionToken) {
switch (action) {
case CONNECT:
MqttPushAgent.getInstance().updateToken();
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_REGISTER, RESULT_OK, MqttPushAgent.getPushToken(), null, "");
break;
case DISCONNECT:
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_UNREGISTER, RESULT_OK, null, null, "");
break;
case SUBSCRIBE:
case UNSUBSCRIBE:
MqttPushAgent.getInstance().updateTags();
Subscription subscription = action.args != null ? (Subscription) action.args : null;
XPush.transmitCommandResult(MqttPushAgent.getContext(), SUBSCRIBE.equals(action) ? TYPE_ADD_TAG : TYPE_DEL_TAG, RESULT_OK, subscription != null ? subscription.getTopic() : "", null, "");
break;
default:
break;
}
}
@Override
public void onActionFailure(MqttAction action, IMqttToken actionToken, Throwable exception) {
String errorMessage = exception != null ? exception.getMessage() : "";
switch (action) {
case CONNECT:
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_REGISTER, RESULT_ERROR, null, null, errorMessage);
break;
case DISCONNECT:
XPush.transmitCommandResult(MqttPushAgent.getContext(), TYPE_UNREGISTER, RESULT_ERROR, null, null, errorMessage);
break;
case SUBSCRIBE:
case UNSUBSCRIBE:
XPush.transmitCommandResult(MqttPushAgent.getContext(), SUBSCRIBE.equals(action) ? TYPE_ADD_TAG : TYPE_DEL_TAG, RESULT_ERROR, null, null, errorMessage);
break;
default:
break;
}
}
};
/**
* 事件监听
*/
private OnMqttEventListener mOnMqttEventListener = new MqttEventListenerAdapter() {
@Override
public void onMessageReceived(String topic, MqttMessage message) {
XPush.transmitMessage(MqttPushAgent.getContext(), message.toString(), null, null);
}
@Override
public void onConnectComplete(boolean reconnect, String serverUri) {
super.onConnectComplete(reconnect, serverUri);
}
@Override
public void onConnectionStatusChanged(ConnectionStatus oldStatus, ConnectionStatus newStatus) {
super.onConnectionStatusChanged(oldStatus, newStatus);
if (newStatus.equals(ConnectionStatus.CONNECTED)) {
XPushManager.get().notifyConnectStatusChanged(CONNECTED);
} else if (newStatus.equals(ConnectionStatus.CONNECTING)) {
XPushManager.get().notifyConnectStatusChanged(CONNECTING);
} else if (newStatus.equals(ConnectionStatus.DISCONNECTED) || newStatus.equals(ConnectionStatus.ERROR)) {
XPushManager.get().notifyConnectStatusChanged(DISCONNECT);
}
}
};
}
| 37.372549 | 206 | 0.666212 |
7d68682a1384f8cbaf1c118957e7dfd61ed62896 | 4,597 | /*
Copyright (c) 2019 LinkedIn Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.linkedin.restli.tools.errors;
import com.linkedin.restli.common.HttpStatus;
import com.linkedin.restli.server.CreateResponse;
import com.linkedin.restli.server.UpdateResponse;
import com.linkedin.restli.server.annotations.Action;
import com.linkedin.restli.server.annotations.Finder;
import com.linkedin.restli.server.annotations.ParamError;
import com.linkedin.restli.server.annotations.QueryParam;
import com.linkedin.restli.server.annotations.RestLiCollection;
import com.linkedin.restli.server.annotations.RestMethod;
import com.linkedin.restli.server.annotations.ServiceErrorDef;
import com.linkedin.restli.server.annotations.ServiceErrors;
import com.linkedin.restli.server.resources.CollectionResourceTemplate;
import com.linkedin.restli.tools.DummyRecord;
import java.util.ArrayList;
import java.util.List;
import static com.linkedin.restli.tools.errors.DummyServiceError.Codes.*;
/**
* Collection resource to test IDL generation with defined service errors.
* This resource also tests that service errors can be defined only at the method level.
*
* @author Evan Williams
*/
@RestLiCollection(name = "collection")
@ServiceErrorDef(DummyServiceError.class)
public class ServiceErrorCollectionResource extends CollectionResourceTemplate<Long, DummyRecord>
{
/**
* This ensures that template CRUD methods can specify a method-level service error.
*/
@Override
@ServiceErrors(METHOD_LEVEL_ERROR)
public DummyRecord get(Long id)
{
return null;
}
/**
* This ensures that annotation-specified CRUD methods can specify method-level service errors.
* It also ensures that multiple method-level service errors can be specified.
*/
@RestMethod.Create
@ServiceErrors({ METHOD_LEVEL_ERROR, YET_ANOTHER_METHOD_LEVEL_ERROR })
public CreateResponse create(DummyRecord dummyRecord)
{
return new CreateResponse(2147L);
}
/**
* This is included as a template CRUD method with no service errors.
*/
@Override
public UpdateResponse delete(Long id)
{
return new UpdateResponse(HttpStatus.S_204_NO_CONTENT);
}
/**
* This is included as an annotation-specified CRUD method with no service errors.
*/
@RestMethod.GetAll
public List<DummyRecord> getAll()
{
return new ArrayList<>();
}
/**
* This is included as an action method with no service errors.
*/
@Action(name = "errorProneAction")
public String errorProneAction()
{
return "Protect from errors: [on] off";
}
/**
* This ensures that a method-level service error can specify one parameter.
* It also ensures that a subset of parameters can be specified.
*/
@Finder(value = "ctrlF")
@ParamError(code = PARAMETER_ERROR, parameterNames = { "param" })
public List<DummyRecord> finder(@QueryParam("param") String param, @QueryParam("ignoreMe") Integer ignoreMe)
{
return new ArrayList<>();
}
/**
* This ensures that a method-level service error can specify multiple parameters.
* It also ensures that service error parameter names are matched against the
* {@link QueryParam} annotation rather than the actual method arguments.
*/
@Finder(value = "altF4")
@ParamError(code = DOUBLE_PARAMETER_ERROR, parameterNames = { "param1", "param2" })
public List<DummyRecord> finder2(@QueryParam("param1") String akaParamA, @QueryParam("param2") String akaParamB)
{
return new ArrayList<>();
}
/**
* This ensures that two method-level service errors specifying parameters can be used in conjunction
* with a method-level service error with no parameters.
*/
@Finder(value = "ctrlAltDelete")
@ServiceErrors({ METHOD_LEVEL_ERROR })
@ParamError(code = PARAMETER_ERROR, parameterNames = { "param" })
@ParamError(code = DOUBLE_PARAMETER_ERROR, parameterNames = { "param1", "param2" })
public List<DummyRecord> finder3(@QueryParam("param") String param, @QueryParam("param1") String param1,
@QueryParam("param2") String param2)
{
return new ArrayList<>();
}
}
| 34.56391 | 114 | 0.746574 |
a6501ce8e5bf5b5edd369738a4acf4b0f11acf18 | 2,187 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
/**
* Servlet responsible for authenticating a user before they can comment
*/
@WebServlet("/auth-check")
public class AuthenticationServlet extends DataServlet {
class LoginStatus {
private boolean loggedIn;
private String loginURL;
private String logoutURL;
public LoginStatus(boolean loggedIn) {
this.loggedIn = loggedIn;
this.loginURL = userService.createLoginURL(REDIRECT_URL_HOME);
this.logoutURL = userService.createLogoutURL(REDIRECT_URL_HOME);
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
}
// create class variables so we don't have to create a URL every request
private UserService userService = UserServiceFactory.getUserService();
private LoginStatus loginStatus = new LoginStatus(userService.isUserLoggedIn());
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType(JSON_CONTENT_TYPE);
loginStatus.setLoggedIn(userService.isUserLoggedIn());
Gson gson = new Gson();
response.getWriter().println(gson.toJson(loginStatus));
}
} | 33.646154 | 98 | 0.763146 |
e8468a5be013a0f17bd8b13fd6cba6fdee4e8c7e | 521 | package apidemo3.model;
import java.util.Date;
public class UserValidateDo {
/** */
public long user_id;
/** 1 认证中 2 认证完成 */
public int id_status;
/** */
public int base_status;
/** */
public int sup_status;
/** */
public int bank_status;
/** 闪云验证信息 */
public String validate_info;
/** yyyyMMdd */
public int log_date;
/** */
public Date log_fulltime;
/** yyyyMMdd */
public int update_date;
/** */
public Date update_fulltime;
}
| 17.366667 | 32 | 0.570058 |
0bb81d4659a2d9ff036dcef61e0adac7c5f06cee | 957 | package net.mh.kafkabrowser.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by markus on 09.04.17.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class BrowserConsumerRequest {
private String keyDeserializer;
private String valueDeserializer;
public BrowserConsumerRequest() {
//JSON
}
public BrowserConsumerRequest(String keyDeserializer, String valueDeserializer) {
this.keyDeserializer = keyDeserializer;
this.valueDeserializer = valueDeserializer;
}
public String getKeyDeserializer() {
return keyDeserializer;
}
public void setKeyDeserializer(String keyDeserializer) {
this.keyDeserializer = keyDeserializer;
}
public String getValueDeserializer() {
return valueDeserializer;
}
public void setValueDeserializer(String valueDeserializer) {
this.valueDeserializer = valueDeserializer;
}
}
| 24.538462 | 85 | 0.722048 |
f28f80fa48db630cb9fb023de176cf578f96f2b0 | 260 | package com.ssafy.ssafience.model.notice;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString
@Setter
@Getter
public class NoticeWriteRequest {
private String memberId;
private String noticeTitle;
private String noticeContent;
}
| 17.333333 | 41 | 0.811538 |
35027d0cc39c38d9f25a4b2bd8673ec605c8d23f | 3,574 | package ru.job4j.tracker;
import java.util.Arrays;
/**
* The Tracker collects tickets.
* The singleton version. .Private static final class. Lazy loading.
* @author RomanM
* @version 1.0 May 23, 2019
*/
public class TrackerSingleton3 {
private final Item[] items = new Item[100];
private int position = 0;
private TrackerSingleton3() {
}
private static final class Holder {
private static final TrackerSingleton3 INSTANCE = new TrackerSingleton3();
}
public static TrackerSingleton3 getInstance() {
return Holder.INSTANCE;
}
/**
* The method adds a new ticket
* @param item - contains parameters of the ticket
* @return - return the ticket
*/
public Item add(Item item) {
item.setId(this.generateId());
this.items[this.position++] = item;
return item;
}
/**
* The method generetes a unique ID for tickets
* @return - the unique ID
*/
private String generateId() {
long time = System.currentTimeMillis();
long random = (long) (Math.random() * 100000);
return Long.toString(time + random);
}
/**
* the method replaces the parameters of one ticket with another
* @param id - the unique ID of the ticket for replacement
* @param item - a new parameters
* @return true - the operations completed successful
*/
public boolean replace(String id, Item item) {
boolean result = false;
for (int i = 0; i < this.position; i++) {
if (this.items[i].getId().equals(id)) {
this.items[i] = item;
this.items[i].setId(id);
result = true;
break;
}
}
return result;
}
/**
* the method deletes the ticket with the forwarded ID
* @param id - forwarded ID
* @return true if the operation is completed successful
*/
public boolean delete(String id) {
boolean result = false;
for (int i = 0; i < this.position; i++) {
if (this.items[i].getId().equals(id)) {
System.arraycopy(this.items, (i + 1), this.items, i, (this.items.length - 1 - i));
this.items[this.items.length - 1] = null;
this.position--;
result = true;
break;
}
}
return result;
}
/**
* the method returns the array with all tickets
* @return - the array with all tickets
*/
public Item[] findAll() {
return Arrays.copyOf(this.items, position);
}
/**
* the method searches the tickets with the forwarded name.
* @param key - forwarded key-word
* @return - the array with founded tickets
*/
public Item[] findByName(String key) {
Item[] itemsKey = new Item[this.position];
int index = 0;
for (int i = 0; i < this.position; i++) {
if (this.items[i].getName().equals(key)) {
itemsKey[index++] = this.items[i];
}
}
return Arrays.copyOf(itemsKey, index);
}
/**
* the method searches the ticket with forwarded ID
* @param id - forwarded ID
* @return - the founded ticket
*/
public Item findById(String id) {
Item itemReturn = null;
for (int i = 0; i < this.position; i++) {
if (this.items[i].getId().equals(id)) {
itemReturn = this.items[i];
break;
}
}
return itemReturn;
}
}
| 28.141732 | 98 | 0.552602 |
cff7adb4474fcccd12a887c3aa5e4e08ef94a271 | 293 | package com.mikuac.bot.bean.saucenao;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author Zero
* @date 2020/12/3 13:32
*/
@Data
@Component
public class SauceNaoBean {
private Header header;
private List<Results> results;
} | 14.65 | 48 | 0.726962 |
085802b91c8470e6083a24c91bbd1edfec658da6 | 8,362 | package com.dropbox.core.examples.android.internal;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import androidx.appcompat.widget.Toolbar;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.dropbox.core.android.Auth;
import com.dropbox.core.android.DbxOfficialAppConnector;
import com.dropbox.core.android.DropboxParseException;
import com.dropbox.core.android.DropboxUidNotInitializedException;
import com.dropbox.core.examples.android.DropboxActivity;
import com.dropbox.core.examples.android.R;
/**
* This example is only for 3rd party apps who registered OpenWith feature at our server side who use
* intent action {@value DbxOfficialAppConnector#ACTION_DBXC_EDIT} and
* {@value DbxOfficialAppConnector#ACTION_DBXC_VIEW} to jump to their apps. Don't follow this if
* you don't need openwith or if you use regular {@value Intent#ACTION_EDIT} and
* {@value Intent#ACTION_VIEW}.
*/
public class OpenWithActivity extends DropboxActivity {
private DbxOfficialAppConnector mDoac;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_with);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
Button generateIntentButton = (Button)findViewById(R.id.generate_intent);
generateIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.editText);
String path = editText.getText().toString();
//fake OpenWithIntent with some dummy parameters
Intent fakeOpenWithIntent = generateOpenWithIntent(path);
//encode the fake OpenWithIntent into UtmContent
String encodedFakeIntent = encodeOpenWithIntent(fakeOpenWithIntent);
try {
//test that decoding utmcontent works
Intent decodedIntent = DbxOfficialAppConnector
.generateOpenWithIntentFromUtmContent(encodedFakeIntent);
//start that fake OpenWithIntent. This will lead us to a new OpenWithActivity.
startActivity(decodedIntent);
} catch (DropboxParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button mInstalled = (Button)findViewById(R.id.is_installed);
mInstalled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DbxOfficialAppConnector.DbxOfficialAppInstallInfo installInfo =
DbxOfficialAppConnector.isInstalled(OpenWithActivity.this);
showToast((installInfo != null)?installInfo.toString():"Not installed!");
}
});
Button mGenLinked = (Button)findViewById(R.id.is_linked_any_button);
mGenLinked.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSigned = DbxOfficialAppConnector.isAnySignedIn(OpenWithActivity.this);
showToast("Any Signed in?:" + isSigned);
}
});
Button mSpecLinked = (Button)findViewById(R.id.is_linked_spec_button);
mSpecLinked.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSigned = mDoac.isSignedIn(OpenWithActivity.this);
showToast("Signed in?:" + isSigned);
}
});
Button mPreview = (Button)findViewById(R.id.preview_button);
mPreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.editText);
String path = editText.getText().toString();
Intent pIntent = mDoac.getPreviewFileIntent(OpenWithActivity.this, path, "");
startActivity(pIntent);
}
});
Button mUpgrade = (Button)findViewById(R.id.upgrade_button);
mUpgrade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent uIntent = mDoac.getUpgradeAccountIntent(OpenWithActivity.this);
startActivity(uIntent);
}
});
}
/* Because it's just a fake intent, we just print it in Toast and do nothing here. As third
* party app you should take the intent from Dropbox official app and potentially go through
* the auth flow. Finally handle that file sent with this intent.
*/
private void handleFakeOpenWithIntent(Intent intent) {
if (intent.getAction() == DbxOfficialAppConnector.ACTION_DBXC_EDIT ||
intent.getAction() == DbxOfficialAppConnector.ACTION_DBXC_VIEW) {
String path = intent.getStringExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_PATH);
String uid = intent.getStringExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_UID);
boolean read_only = intent.getBooleanExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_READ_ONLY, false);
String session_id = intent.getStringExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_SESSION_ID);
showToast(path + uid + read_only + session_id);
}
}
protected Intent generateOpenWithIntent(String path) {
/*
* Generate an OpenWithIntent.
* Real 3rd party apps should never run this function as DropboxApp does this entirely
*/
String uid = Auth.getUid();
// fake the URI
// WARNING: URI FORMAT IS NOT FINALIZED AND MAY CHANGE AT ANY TIME
Uri.Builder builder = new Uri.Builder();
builder.scheme("content");
builder.authority("com.dropbox.android.FileCache");
builder.appendPath("filecache");
builder.appendPath(uid);
for (String component : path.substring(1).split("/")) {
builder.appendPath(component);
}
Uri uri = builder.build();
// end URI fakery
Intent owpIntent = new Intent(DbxOfficialAppConnector.ACTION_DBXC_EDIT, uri);
// extras
owpIntent.putExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_PATH, path);
owpIntent.putExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_UID, uid);
owpIntent.putExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_READ_ONLY, false);
owpIntent.putExtra(DbxOfficialAppConnector.EXTRA_DROPBOX_SESSION_ID, "generated");
owpIntent.setDataAndType(uri, "text/plain");
return owpIntent;
}
protected String encodeOpenWithIntent(Intent owpIntent) {
/*
* Encode OpenWith intent
* Real 3rd party apps should never run this function as DropboxApp does this entirely
*/
Bundle extras = owpIntent.getExtras();
extras.putString("_action", owpIntent.getAction());
extras.putParcelable("_uri", owpIntent.getData());
extras.putString("_type", owpIntent.getType());
// marshall it!
final Parcel parcel = Parcel.obtain();
parcel.writeBundle(extras);
byte[] b = parcel.marshall();
parcel.recycle();
return new String(Base64.encode(b, 0));
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
@Override
protected void loadData() {
try {
String uid = Auth.getUid();
if (uid == null) {
SharedPreferences prefs = getSharedPreferences("dropbox-sample", MODE_PRIVATE);
uid = prefs.getString("user-id", null);
}
this.mDoac = new DbxOfficialAppConnector(uid);
} catch (DropboxUidNotInitializedException e) {
e.printStackTrace();
return;
}
handleFakeOpenWithIntent(getIntent());
}
}
| 41.192118 | 111 | 0.65104 |
17abf355266365f9da2c7c2623127354b48920df | 26,005 | package com.bskms.bean;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class PayExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public PayExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andBaseIsNull() {
addCriterion("base is null");
return (Criteria) this;
}
public Criteria andBaseIsNotNull() {
addCriterion("base is not null");
return (Criteria) this;
}
public Criteria andBaseEqualTo(Double value) {
addCriterion("base =", value, "base");
return (Criteria) this;
}
public Criteria andBaseNotEqualTo(Double value) {
addCriterion("base <>", value, "base");
return (Criteria) this;
}
public Criteria andBaseGreaterThan(Double value) {
addCriterion("base >", value, "base");
return (Criteria) this;
}
public Criteria andBaseGreaterThanOrEqualTo(Double value) {
addCriterion("base >=", value, "base");
return (Criteria) this;
}
public Criteria andBaseLessThan(Double value) {
addCriterion("base <", value, "base");
return (Criteria) this;
}
public Criteria andBaseLessThanOrEqualTo(Double value) {
addCriterion("base <=", value, "base");
return (Criteria) this;
}
public Criteria andBaseIn(List<Double> values) {
addCriterion("base in", values, "base");
return (Criteria) this;
}
public Criteria andBaseNotIn(List<Double> values) {
addCriterion("base not in", values, "base");
return (Criteria) this;
}
public Criteria andBaseBetween(Double value1, Double value2) {
addCriterion("base between", value1, value2, "base");
return (Criteria) this;
}
public Criteria andBaseNotBetween(Double value1, Double value2) {
addCriterion("base not between", value1, value2, "base");
return (Criteria) this;
}
public Criteria andOvertimeIsNull() {
addCriterion("overtime is null");
return (Criteria) this;
}
public Criteria andOvertimeIsNotNull() {
addCriterion("overtime is not null");
return (Criteria) this;
}
public Criteria andOvertimeEqualTo(Double value) {
addCriterion("overtime =", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeNotEqualTo(Double value) {
addCriterion("overtime <>", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeGreaterThan(Double value) {
addCriterion("overtime >", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeGreaterThanOrEqualTo(Double value) {
addCriterion("overtime >=", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeLessThan(Double value) {
addCriterion("overtime <", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeLessThanOrEqualTo(Double value) {
addCriterion("overtime <=", value, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeIn(List<Double> values) {
addCriterion("overtime in", values, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeNotIn(List<Double> values) {
addCriterion("overtime not in", values, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeBetween(Double value1, Double value2) {
addCriterion("overtime between", value1, value2, "overtime");
return (Criteria) this;
}
public Criteria andOvertimeNotBetween(Double value1, Double value2) {
addCriterion("overtime not between", value1, value2, "overtime");
return (Criteria) this;
}
public Criteria andTrafficIsNull() {
addCriterion("traffic is null");
return (Criteria) this;
}
public Criteria andTrafficIsNotNull() {
addCriterion("traffic is not null");
return (Criteria) this;
}
public Criteria andTrafficEqualTo(Double value) {
addCriterion("traffic =", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficNotEqualTo(Double value) {
addCriterion("traffic <>", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficGreaterThan(Double value) {
addCriterion("traffic >", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficGreaterThanOrEqualTo(Double value) {
addCriterion("traffic >=", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficLessThan(Double value) {
addCriterion("traffic <", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficLessThanOrEqualTo(Double value) {
addCriterion("traffic <=", value, "traffic");
return (Criteria) this;
}
public Criteria andTrafficIn(List<Double> values) {
addCriterion("traffic in", values, "traffic");
return (Criteria) this;
}
public Criteria andTrafficNotIn(List<Double> values) {
addCriterion("traffic not in", values, "traffic");
return (Criteria) this;
}
public Criteria andTrafficBetween(Double value1, Double value2) {
addCriterion("traffic between", value1, value2, "traffic");
return (Criteria) this;
}
public Criteria andTrafficNotBetween(Double value1, Double value2) {
addCriterion("traffic not between", value1, value2, "traffic");
return (Criteria) this;
}
public Criteria andMealIsNull() {
addCriterion("meal is null");
return (Criteria) this;
}
public Criteria andMealIsNotNull() {
addCriterion("meal is not null");
return (Criteria) this;
}
public Criteria andMealEqualTo(Double value) {
addCriterion("meal =", value, "meal");
return (Criteria) this;
}
public Criteria andMealNotEqualTo(Double value) {
addCriterion("meal <>", value, "meal");
return (Criteria) this;
}
public Criteria andMealGreaterThan(Double value) {
addCriterion("meal >", value, "meal");
return (Criteria) this;
}
public Criteria andMealGreaterThanOrEqualTo(Double value) {
addCriterion("meal >=", value, "meal");
return (Criteria) this;
}
public Criteria andMealLessThan(Double value) {
addCriterion("meal <", value, "meal");
return (Criteria) this;
}
public Criteria andMealLessThanOrEqualTo(Double value) {
addCriterion("meal <=", value, "meal");
return (Criteria) this;
}
public Criteria andMealIn(List<Double> values) {
addCriterion("meal in", values, "meal");
return (Criteria) this;
}
public Criteria andMealNotIn(List<Double> values) {
addCriterion("meal not in", values, "meal");
return (Criteria) this;
}
public Criteria andMealBetween(Double value1, Double value2) {
addCriterion("meal between", value1, value2, "meal");
return (Criteria) this;
}
public Criteria andMealNotBetween(Double value1, Double value2) {
addCriterion("meal not between", value1, value2, "meal");
return (Criteria) this;
}
public Criteria andVacationIsNull() {
addCriterion("vacation is null");
return (Criteria) this;
}
public Criteria andVacationIsNotNull() {
addCriterion("vacation is not null");
return (Criteria) this;
}
public Criteria andVacationEqualTo(Double value) {
addCriterion("vacation =", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationNotEqualTo(Double value) {
addCriterion("vacation <>", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationGreaterThan(Double value) {
addCriterion("vacation >", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationGreaterThanOrEqualTo(Double value) {
addCriterion("vacation >=", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationLessThan(Double value) {
addCriterion("vacation <", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationLessThanOrEqualTo(Double value) {
addCriterion("vacation <=", value, "vacation");
return (Criteria) this;
}
public Criteria andVacationIn(List<Double> values) {
addCriterion("vacation in", values, "vacation");
return (Criteria) this;
}
public Criteria andVacationNotIn(List<Double> values) {
addCriterion("vacation not in", values, "vacation");
return (Criteria) this;
}
public Criteria andVacationBetween(Double value1, Double value2) {
addCriterion("vacation between", value1, value2, "vacation");
return (Criteria) this;
}
public Criteria andVacationNotBetween(Double value1, Double value2) {
addCriterion("vacation not between", value1, value2, "vacation");
return (Criteria) this;
}
public Criteria andBonusIsNull() {
addCriterion("bonus is null");
return (Criteria) this;
}
public Criteria andBonusIsNotNull() {
addCriterion("bonus is not null");
return (Criteria) this;
}
public Criteria andBonusEqualTo(Double value) {
addCriterion("bonus =", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusNotEqualTo(Double value) {
addCriterion("bonus <>", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusGreaterThan(Double value) {
addCriterion("bonus >", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusGreaterThanOrEqualTo(Double value) {
addCriterion("bonus >=", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusLessThan(Double value) {
addCriterion("bonus <", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusLessThanOrEqualTo(Double value) {
addCriterion("bonus <=", value, "bonus");
return (Criteria) this;
}
public Criteria andBonusIn(List<Double> values) {
addCriterion("bonus in", values, "bonus");
return (Criteria) this;
}
public Criteria andBonusNotIn(List<Double> values) {
addCriterion("bonus not in", values, "bonus");
return (Criteria) this;
}
public Criteria andBonusBetween(Double value1, Double value2) {
addCriterion("bonus between", value1, value2, "bonus");
return (Criteria) this;
}
public Criteria andBonusNotBetween(Double value1, Double value2) {
addCriterion("bonus not between", value1, value2, "bonus");
return (Criteria) this;
}
public Criteria andOtherIsNull() {
addCriterion("other is null");
return (Criteria) this;
}
public Criteria andOtherIsNotNull() {
addCriterion("other is not null");
return (Criteria) this;
}
public Criteria andOtherEqualTo(Double value) {
addCriterion("other =", value, "other");
return (Criteria) this;
}
public Criteria andOtherNotEqualTo(Double value) {
addCriterion("other <>", value, "other");
return (Criteria) this;
}
public Criteria andOtherGreaterThan(Double value) {
addCriterion("other >", value, "other");
return (Criteria) this;
}
public Criteria andOtherGreaterThanOrEqualTo(Double value) {
addCriterion("other >=", value, "other");
return (Criteria) this;
}
public Criteria andOtherLessThan(Double value) {
addCriterion("other <", value, "other");
return (Criteria) this;
}
public Criteria andOtherLessThanOrEqualTo(Double value) {
addCriterion("other <=", value, "other");
return (Criteria) this;
}
public Criteria andOtherIn(List<Double> values) {
addCriterion("other in", values, "other");
return (Criteria) this;
}
public Criteria andOtherNotIn(List<Double> values) {
addCriterion("other not in", values, "other");
return (Criteria) this;
}
public Criteria andOtherBetween(Double value1, Double value2) {
addCriterion("other between", value1, value2, "other");
return (Criteria) this;
}
public Criteria andOtherNotBetween(Double value1, Double value2) {
addCriterion("other not between", value1, value2, "other");
return (Criteria) this;
}
public Criteria andPaymentTimeIsNull() {
addCriterion("payment_time is null");
return (Criteria) this;
}
public Criteria andPaymentTimeIsNotNull() {
addCriterion("payment_time is not null");
return (Criteria) this;
}
public Criteria andPaymentTimeEqualTo(Date value) {
addCriterion("payment_time =", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotEqualTo(Date value) {
addCriterion("payment_time <>", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeGreaterThan(Date value) {
addCriterion("payment_time >", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeGreaterThanOrEqualTo(Date value) {
addCriterion("payment_time >=", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeLessThan(Date value) {
addCriterion("payment_time <", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeLessThanOrEqualTo(Date value) {
addCriterion("payment_time <=", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeIn(List<Date> values) {
addCriterion("payment_time in", values, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotIn(List<Date> values) {
addCriterion("payment_time not in", values, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeBetween(Date value1, Date value2) {
addCriterion("payment_time between", value1, value2, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotBetween(Date value1, Date value2) {
addCriterion("payment_time not between", value1, value2, "paymentTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | 32.065351 | 103 | 0.550817 |
61ccc961c2d1346f041a7f767db0f571f7ccd013 | 2,398 | /**
*/
package org.sheepy.lily.vulkan.model.process.graphic;
import org.joml.Vector4fc;
import org.sheepy.lily.vulkan.model.VulkanEngine;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Image Attachment</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.sheepy.lily.vulkan.model.process.graphic.ImageAttachment#getClearValue <em>Clear Value</em>}</li>
* <li>{@link org.sheepy.lily.vulkan.model.process.graphic.ImageAttachment#getImageRef <em>Image Ref</em>}</li>
* </ul>
*
* @see org.sheepy.lily.vulkan.model.process.graphic.GraphicPackage#getImageAttachment()
* @model
* @generated
*/
public interface ImageAttachment extends ExtraAttachment
{
/**
* Returns the value of the '<em><b>Clear Value</b></em>' attribute.
* The default value is <code>"0;0;0;0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Clear Value</em>' attribute.
* @see #setClearValue(Vector4fc)
* @see org.sheepy.lily.vulkan.model.process.graphic.GraphicPackage#getImageAttachment_ClearValue()
* @model default="0;0;0;0" unique="false" dataType="org.sheepy.lily.core.model.types.Color4f"
* @generated
*/
Vector4fc getClearValue();
/**
* Sets the value of the '{@link org.sheepy.lily.vulkan.model.process.graphic.ImageAttachment#getClearValue <em>Clear Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Clear Value</em>' attribute.
* @see #getClearValue()
* @generated
*/
void setClearValue(Vector4fc value);
/**
* Returns the value of the '<em><b>Image Ref</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Image Ref</em>' reference.
* @see #setImageRef(VulkanEngine)
* @see org.sheepy.lily.vulkan.model.process.graphic.GraphicPackage#getImageAttachment_ImageRef()
* @model
* @generated
*/
VulkanEngine getImageRef();
/**
* Sets the value of the '{@link org.sheepy.lily.vulkan.model.process.graphic.ImageAttachment#getImageRef <em>Image Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Image Ref</em>' reference.
* @see #getImageRef()
* @generated
*/
void setImageRef(VulkanEngine value);
} // ImageAttachment
| 32.849315 | 142 | 0.67181 |
a0b11daf283ae77b5bf406d7439b94078313f5f7 | 2,691 | package com.eyelinecom.whoisd.sads2.telegram.interceptors;
import com.eyelinecom.whoisd.sads2.RequestDispatcher;
import com.eyelinecom.whoisd.sads2.common.InitUtils;
import com.eyelinecom.whoisd.sads2.common.Initable;
import com.eyelinecom.whoisd.sads2.common.SADSInitUtils;
import com.eyelinecom.whoisd.sads2.common.SADSLogger;
import com.eyelinecom.whoisd.sads2.connector.SADSRequest;
import com.eyelinecom.whoisd.sads2.exception.InterceptionException;
import com.eyelinecom.whoisd.sads2.interceptor.BlankInterceptor;
import com.eyelinecom.whoisd.sads2.profile.Profile;
import com.eyelinecom.whoisd.sads2.profile.ProfileStorage;
import org.apache.commons.logging.Log;
import java.util.Properties;
import static org.apache.commons.lang.StringUtils.isBlank;
public class MsisdnRedirectInterceptor extends BlankInterceptor implements Initable {
public static final String CONF_MSISDN_CONFIRMATION_FORCED = "telegram.msisdn.verification";
private ProfileStorage profileStorage;
@Override
public void onRequest(SADSRequest request, RequestDispatcher dispatcher) throws InterceptionException {
if (InitUtils.getBoolean(CONF_MSISDN_CONFIRMATION_FORCED, false, request.getServiceScenario().getAttributes())) {
final Log log = SADSLogger.getLogger(request.getServiceId(), getClass());
if (!isEnabled(request) || request.getProfile() == null) {
return;
}
try {
final Profile profile = request.getProfile();
final String msisdn = getMsisdn(profile);
if (log.isDebugEnabled()) {
log.debug("Processing wnumber = [" + profile.getWnumber() + "], stored msisdn = [" + msisdn + "]");
}
if (isBlank(msisdn)) {
String redirectURL = request.getServiceScenario().getAttributes().getProperty("msisdn-redirect-uri");
request.setResourceURI(redirectURL);
if (log.isInfoEnabled()) {
log.info("Request redirected to "+redirectURL);
}
}
} catch (Exception e) {
throw new InterceptionException(e);
}
}
}
private boolean isEnabled(SADSRequest request) {
return InitUtils.getBoolean(CONF_MSISDN_CONFIRMATION_FORCED, false, request.getServiceScenario().getAttributes());
}
private String getMsisdn(Profile profile) {
if (profile == null) {
return null;
}
final Profile.Property msisdn = profile
.property("mobile", "msisdn")
.get();
return msisdn == null ? null : msisdn.getValue();
}
@Override
public void init(Properties config) throws Exception {
profileStorage = SADSInitUtils.getResource("profile-storage", config);
}
@Override
public void destroy() {
}
}
| 35.407895 | 118 | 0.722408 |
55fe6b2599b8946dc0f7b43f8041f78d2fba662b | 5,968 | /*
package com.apsidepoei.projetpoeitest.restTest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import com.apsidepoei.projetpoei.ZbleuginApplication;
import com.apsidepoei.projetpoei.database.repositories.AcquiredMattersRepository;
import com.apsidepoei.projetpoei.entities.AcquiredMatters;
import com.apsidepoei.projetpoei.entities.Appointment;
import com.apsidepoei.projetpoei.entities.Candidate;
import com.apsidepoei.projetpoei.entities.Matter;
import com.apsidepoei.projetpoei.entities.Person;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
*/
/**
*
* @author clemb Tests for AcquiredMatters Entity.
*//*
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@ContextConfiguration(classes = ZbleuginApplication.class)
public class AcquiredMattersRestControllerTest extends BaseRestControllerTest<AcquiredMatters, Integer> {
@Autowired
private AcquiredMattersRepository repository;
*/
/**
* Empty Constructor.
*//*
public AcquiredMattersRestControllerTest() {
super("/acquiredmatters");
}
*/
/**
* Create repository.
*//*
@Override
protected JpaRepository<AcquiredMatters, Integer> getRepository() {
return repository;
}
*/
/**
* Parse Json to List for test.
*//*
@Override
protected List<AcquiredMatters> parseJsonToList(StringBuilder builder)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(builder.toString(), new TypeReference<List<AcquiredMatters>>() {
});
}
*/
/**
* Compare if data is the same.
*//*
@Override
protected boolean compareTo(AcquiredMatters item1, AcquiredMatters item2) {
return item1.getId().equals(item2.getId()) && item1.getMatter().equals(item2.getMatter())
&& item1.getCandidate().equals(item2.getCandidate());
}
*/
/**
* Parse Json to a Object for run test.
*//*
@Override
protected AcquiredMatters parseJsonToObject(StringBuilder builder)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(Person.class);
return mapper.readValue(builder.toString(), new TypeReference<AcquiredMatters>() {
});
}
*/
/**
* Generate a Id for run test.
*//*
@Override
protected Integer getItemIdToTest() {
return 1;
}
*/
/**
* Create a object for run test.
*//*
@Override
protected AcquiredMatters getObjectTest() throws ParseException {
AcquiredMatters item = new AcquiredMatters();
return item;
}
*/
/**
* Return Id of Object for run test.
*//*
@Override
protected Integer getItemIdTest(AcquiredMatters item) {
return item.getId();
}
*/
/**
* Create a string for POST method API.
*//*
@Override
protected String getObjectToStringToPost() {
String urlParameters = "score=12&validationDate=2019/02/24";
return urlParameters;
}
*/
/**
* Method to compare list.
*//*
@Override
protected boolean compareToList(List<AcquiredMatters> items, List<AcquiredMatters> dbItems) {
return false;
}
*/
/**
* Test function via HTTP
*
* @throws Exception
*//*
@Test
public void test() throws Exception {
// Make objects
Matter matter = new Matter();
matter.setName("Diplomatie spaciale");
Candidate candidate = new Candidate();
candidate.setFirstname("Jean");
candidate.setLastname("Dupont");
candidate.setEmail("amatter@gmail.com");
candidate.setCellPhone("0987789878");
AcquiredMatters sess = new AcquiredMatters();
sess.setMatter(matter);
sess.setCandidate(candidate);
;
// Transform to JSON
String objJson = this.objectMapper.writeValueAsString(sess);
// Prepare Request
MockHttpServletRequestBuilder request = post(BASE_API + entityPath + "/test").contentType("application/json")
.content(objJson);
MvcResult result = this.mockMvc.perform(request).andExpect(status().isOk()).andReturn();
System.out.println(result.getResponse().getStatus());
System.out.println(result.getResponse().getContentAsString());
// Transform to Object
AcquiredMatters newSess = this.objectMapper.readValue(result.getResponse().getContentAsString(), AcquiredMatters.class);
// Tests
assertNotNull(newSess);
assertThat(sess.getMatter().getName()).isEqualTo(newSess.getMatter().getName());
assertThat(sess.getCandidate().getFirstname()).isEqualTo(newSess.getCandidate().getFirstname());
}
}
*/
| 27.502304 | 124 | 0.745979 |
50cc7545adab6514261ab6dbefa5d060fe396be7 | 608 | package org.hl7.davinci.atr.server.service;
import java.util.Date;
import java.util.List;
import org.hl7.davinci.atr.server.model.DafInsurancePlan;
import org.hl7.fhir.r4.model.InsurancePlan;
public interface InsurancePlanService {
InsurancePlan getInsurancePlanById(int id);
InsurancePlan getInsurancePlanByVersionId(int theId, String versionId);
DafInsurancePlan updateInsurancePlanById(int id, InsurancePlan theInsurancePlan);
DafInsurancePlan createInsurancePlan(InsurancePlan theInsurancePlan);
List<InsurancePlan> getInsurancePlanForBulkData(List<String> patients, Date start, Date end);
}
| 30.4 | 94 | 0.835526 |
4bb9ad79b28ebb4b2bf14e87b393967359bbd6f2 | 943 | package com.quorum.tessera.junixsocket.adapter;
import org.junit.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultUnixSocketFactoryTest {
private final DefaultUnixSocketFactory factory = new DefaultUnixSocketFactory();
@Test
public void serverSocketGetsCreated() throws IOException {
final Path serverPath = Files.createTempDirectory("tmp").resolve("sock.sock");
ServerSocket serverSocket = factory.createServerSocket(serverPath);
assertThat(Files.exists(serverPath)).isTrue();
}
@Test
public void clientCanConnectToSocket() throws IOException {
final Path clientPath = Files.createTempDirectory("tmp").resolve("sock.sock");
factory.createServerSocket(clientPath);
factory.createSocket(clientPath);
}
}
| 24.179487 | 86 | 0.741251 |
734b611fbab8b2c74cbec47192bd3512d1281572 | 4,727 | /*
* Copyright 2013 Jon Iles
*
* 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.rtfparserkit.utils;
import java.io.OutputStream;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import com.rtfparserkit.parser.IRtfListener;
import com.rtfparserkit.rtf.Command;
/**
* Trivial class used to convert events generated by an RTF parser into an XML document.
* The primary purpose of this code is to debug the parser output, and provide a
* convenient method for comparing expected and actual parser behaviour in test cases.
*/
public class RtfDumpListener implements IRtfListener
{
/**
* Constructor.
*/
public RtfDumpListener(OutputStream stream)
throws XMLStreamException
{
writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream, "UTF-8");
}
/**
* Create the document header.
*/
@Override
public void processDocumentStart()
{
try
{
writer.writeStartDocument("UTF-8", "1.0");
writer.writeStartElement("rtf");
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Create the document trailer.
*/
@Override
public void processDocumentEnd()
{
try
{
writer.writeEndElement();
writer.writeEndDocument();
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write character bytes - note that we cheat, we just convert them
* directly to a string for output with no regard to the encoding.
*/
@Override
public void processCharacterBytes(byte[] data)
{
try
{
if (data.length != 0)
{
writer.writeStartElement("chars");
writer.writeCharacters(new String(data));
writer.writeEndElement();
}
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write binary data as hex.
*/
@Override
public void processBinaryBytes(byte[] data)
{
try
{
writer.writeStartElement("bytes");
for (byte b : data)
{
writer.writeCharacters(Integer.toHexString(b));
}
writer.writeEndElement();
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write a group start tag.
*/
@Override
public void processGroupStart()
{
try
{
writer.writeStartElement("group");
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write a group end tag.
*/
@Override
public void processGroupEnd()
{
try
{
writer.writeEndElement();
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write a command tag.
*/
@Override
public void processCommand(Command command, int parameter, boolean hasParameter, boolean optional)
{
try
{
writer.writeEmptyElement("command");
writer.writeAttribute("name", command.getCommandName());
if (hasParameter)
{
writer.writeAttribute("parameter", Integer.toString(parameter));
}
if (optional)
{
writer.writeAttribute("optional", "true");
}
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
/**
* Write string data.
*/
@Override
public void processString(String string)
{
try
{
writer.writeStartElement("chars");
writer.writeCharacters(string);
writer.writeEndElement();
}
catch (XMLStreamException ex)
{
throw new RuntimeException(ex);
}
}
private final XMLStreamWriter writer;
}
| 23.171569 | 102 | 0.577322 |
52ac82077cfb84c16fecd536202e72ec91618ad0 | 180 | package it.smartcommunitylab.mobile_attendance.model;
import java.util.Date;
public interface Rating {
String getAccount();
Date getTimestamp();
int getValue();
}
| 13.846154 | 53 | 0.722222 |
771e938d09ecbbc4ee709118c032529f1ea8cdb3 | 20,370 | package io.muserver.rest;
import io.muserver.*;
import io.netty.handler.codec.http.HttpHeaderNames;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.RuntimeDelegate;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toMap;
class JaxRSResponse extends Response implements ContainerResponseContext, WriterInterceptorContext {
static {
MuRuntimeDelegate.ensureSet();
}
private final MultivaluedMap<String, Object> headers;
private StatusType status;
private ObjWithType objWithType;
private final NewCookie[] cookies;
private final List<Link> links;
private Annotation[] annotations;
private OutputStream outputStream;
private JaxRSRequest requestContext;
private List<WriterInterceptor> writerInterceptors;
private int nextWriter = 0;
JaxRSResponse(StatusType status, MultivaluedMap<String, Object> headers, ObjWithType entity, NewCookie[] cookies, List<Link> links, Annotation[] annotations) {
this.status = status;
this.headers = headers;
this.objWithType = entity;
this.cookies = cookies;
this.links = links;
this.annotations = annotations;
}
public Annotation[] getAnnotations() {
return annotations;
}
@Override
public void setAnnotations(Annotation[] annotations) {
if (annotations == null) {
throw new NullPointerException("The 'annotations' parameter must not be null");
}
this.annotations = annotations;
}
@Override
public Class<?> getType() {
return objWithType.type;
}
@Override
public void setType(Class<?> type) {
objWithType = new ObjWithType(type, objWithType.genericType, objWithType.response, objWithType.entity);
}
@Override
public Type getGenericType() {
return objWithType.genericType;
}
@Override
public void setGenericType(Type genericType) {
objWithType = new ObjWithType(objWithType.type, genericType, objWithType.response, objWithType.entity);
}
@Override
public int getStatus() {
return status.getStatusCode();
}
@Override
public void setStatus(int code) {
this.status = Status.fromStatusCode(code);
}
@Override
public StatusType getStatusInfo() {
return status;
}
@Override
public void setStatusInfo(StatusType statusInfo) {
this.status = statusInfo;
}
@Override
public Object getEntity() {
return objWithType.entity;
}
@Override
public Class<?> getEntityClass() {
return getType();
}
@Override
public Type getEntityType() {
return getGenericType();
}
@Override
public void setEntity(Object entity) {
objWithType = ObjWithType.objType(entity);
if (entity instanceof Response) {
Response resp = (Response) entity;
setStatusInfo(resp.getStatusInfo());
}
}
@Override
public OutputStream getOutputStream() {
return outputStream;
}
@Override
public void setOutputStream(OutputStream os) {
this.outputStream = os;
}
@Override
public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType) {
setEntity(entity);
setAnnotations(annotations);
setMediaType(mediaType);
}
@Override
public Annotation[] getEntityAnnotations() {
return getAnnotations();
}
@Override
public OutputStream getEntityStream() {
return outputStream;
}
@Override
public void setEntityStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public <T> T readEntity(Class<T> entityType) {
throw NotImplementedException.willNot();
}
@Override
public <T> T readEntity(GenericType<T> entityType) {
throw NotImplementedException.willNot();
}
@Override
public <T> T readEntity(Class<T> entityType, Annotation[] annotations) {
throw NotImplementedException.willNot();
}
@Override
public <T> T readEntity(GenericType<T> entityType, Annotation[] annotations) {
throw NotImplementedException.willNot();
}
@Override
public boolean hasEntity() {
return objWithType.entity != null;
}
@Override
public boolean bufferEntity() {
throw NotImplementedException.willNot();
}
@Override
public void close() {
throw NotImplementedException.notYet();
}
@Override
public MediaType getMediaType() {
String h = getHeaderString("content-type");
return h == null ? null : MediaTypeParser.fromString(h);
}
@Override
public void setMediaType(MediaType mediaType) {
if (mediaType == null) {
headers.remove("content-type");
} else {
headers.putSingle("content-type", MediaTypeParser.toString(mediaType));
}
}
@Override
public Locale getLanguage() {
String h = getHeaderString(HeaderNames.CONTENT_LANGUAGE.toString());
if (h == null) return null;
return Locale.forLanguageTag(h);
}
@Override
public int getLength() {
String l = getHeaderString(HeaderNames.CONTENT_LENGTH.toString());
if (l == null) return -1;
try {
return Integer.parseInt(l);
} catch (NumberFormatException e) {
return -1;
}
}
@Override
public Set<String> getAllowedMethods() {
String allow = getHeaderString(HeaderNames.ALLOW.toString());
return allow == null ? Collections.emptySet() : new HashSet<>(asList(allow.split(",")));
}
@Override
public Map<String, NewCookie> getCookies() {
return Stream.of(cookies).collect(toMap(Cookie::getName, c -> c));
}
@Override
public EntityTag getEntityTag() {
Object first = headers.getFirst(HeaderNames.ETAG.toString());
if (first == null || first instanceof EntityTag) return (EntityTag)first;
return EntityTag.valueOf(first.toString());
}
@Override
public Date getDate() {
return dateFromHeader("date");
}
private Date dateFromHeader(String name) {
Object date = headers.getFirst(name);
if (date == null || date.getClass().isAssignableFrom(Date.class)) return (Date)date;
return Mutils.fromHttpDate(date.toString());
}
@Override
public Date getLastModified() {
return dateFromHeader("last-modified");
}
@Override
public URI getLocation() {
String s = getHeaderString("location");
return s == null ? null : URI.create(s);
}
@Override
public Set<Link> getLinks() {
return new HashSet<>(links);
}
@Override
public boolean hasLink(String relation) {
return links.stream().anyMatch(link -> link.getRels().contains(relation));
}
@Override
public Link getLink(String relation) {
return links.stream().filter(link -> link.getRels().contains(relation)).findFirst().orElse(null);
}
@Override
public Link.Builder getLinkBuilder(String relation) {
Link link = getLink(relation);
if (link == null) {
return null;
}
return Link.fromLink(link);
}
@Override
public MultivaluedMap<String, Object> getMetadata() {
return headers;
}
@Override
public MultivaluedMap<String, String> getStringHeaders() {
MultivaluedMap<String, String> map = new LowercasedMultivaluedHashMap<>();
for (Map.Entry<String, List<Object>> entry : headers.entrySet()) {
map.put(entry.getKey(), entry.getValue()
.stream()
.map(JaxRSResponse::headerValueToString)
.collect(Collectors.toList())
);
}
return map;
}
static MultivaluedMap<String, Object> muHeadersToJaxObj(Headers headers) {
MultivaluedMap<String, Object> map = new LowercasedMultivaluedHashMap<>();
for (String name : headers.names()) {
map.addAll(name, headers.getAll(name));
}
return map;
}
@Override
public String getHeaderString(String name) {
return headerValueToString(headers.getFirst(name));
}
private static String headerValueToString(Object value) {
if (value == null || value instanceof String) {
return (String)value;
}
if (value.getClass().isAssignableFrom(Date.class)) {
return Mutils.toHttpDate((Date)value);
}
try {
RuntimeDelegate.HeaderDelegate headerDelegate = MuRuntimeDelegate.getInstance().createHeaderDelegate(value.getClass());
return headerDelegate.toString(value);
} catch (MuException e) {
return value.toString();
}
}
// Start interceptor specific things
void executeInterceptors(List<WriterInterceptor> writerInterceptors) throws IOException {
this.nextWriter = 0;
this.writerInterceptors = writerInterceptors;
proceed();
}
@Override
public void proceed() throws IOException, WebApplicationException {
if (nextWriter < writerInterceptors.size()) {
nextWriter++;
WriterInterceptor nextInterceptor = writerInterceptors.get(nextWriter - 1);
List<Class<? extends Annotation>> filterBindings = ResourceClass.getNameBindingAnnotations(nextInterceptor.getClass());
if (requestContext.methodHasAnnotations(filterBindings)) {
nextInterceptor.aroundWriteTo(this);
}
}
}
@Override
public Object getProperty(String name) {
return requestContext.getProperty(name);
}
@Override
public Collection<String> getPropertyNames() {
return requestContext.getPropertyNames();
}
@Override
public void setProperty(String name, Object object) {
requestContext.setProperty(name, object);
}
@Override
public void removeProperty(String name) {
requestContext.removeProperty(name);
}
public void setRequestContext(JaxRSRequest requestContext) {
this.requestContext = requestContext;
}
// End interceptor specific things
@Override
public String toString() {
return getStatusInfo().toString();
}
public static class Builder extends Response.ResponseBuilder {
static {
MuRuntimeDelegate.ensureSet();
}
static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
private final MultivaluedMap<String, Object> headers = new LowercasedMultivaluedHashMap<>();
private final List<Link> linkHeaders = new ArrayList<>();
private StatusType status;
private Object entity;
private Annotation[] annotations = EMPTY_ANNOTATIONS;
private NewCookie[] cookies = new NewCookie[0];
private MediaType type;
@Override
public Response build() {
for (Link linkHeader : linkHeaders) {
headers.add(HeaderNames.LINK.toString(), linkHeader.toString());
}
if (this.type != null) {
headers.putSingle(HeaderNames.CONTENT_TYPE.toString(), this.type.toString());
}
return new JaxRSResponse(status, headers, ObjWithType.objType(entity), cookies, linkHeaders, annotations);
}
@Override
public ResponseBuilder clone() {
throw NotImplementedException.notYet();
}
@Override
public ResponseBuilder status(int code) {
return status(code, null);
}
@Override
public ResponseBuilder status(int code, String reasonPhrase) {
if (code < 100 || code > 599) {
throw new IllegalArgumentException("Status must be between 100 and 599, but was " + code);
}
this.status = Status.fromStatusCode(code);
if (this.status == null || reasonPhrase != null) {
this.status = new CustomStatus(Status.Family.familyOf(code), code, reasonPhrase);
}
return this;
}
@Override
public ResponseBuilder entity(Object entity) {
return entity(entity, EMPTY_ANNOTATIONS);
}
@Override
public ResponseBuilder entity(Object entity, Annotation[] annotations) {
this.entity = entity;
this.annotations = annotations;
return this;
}
@Override
public ResponseBuilder allow(String... methods) {
if (methods == null || (methods.length == 1 && methods[0] == null)) {
return allow((Set<String>) null);
} else {
return allow(new HashSet<>(Arrays.asList(methods)));
}
}
@Override
public ResponseBuilder allow(Set<String> methods) {
if (methods == null) {
return setHeader(HttpHeaderNames.ALLOW, null, true);
}
StringBuilder allow = new StringBuilder();
for (String m : methods) {
append(allow, true, m);
}
return setHeader(HttpHeaderNames.ALLOW, allow.toString(), true);
}
private void append(StringBuilder sb, boolean v, String s) {
if (v) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(s);
}
}
@Override
public ResponseBuilder cacheControl(CacheControl cacheControl) {
return setHeader(HeaderNames.CACHE_CONTROL, cacheControl.toString(), false);
}
@Override
public ResponseBuilder encoding(String encoding) {
return setHeader(HeaderNames.CONTENT_ENCODING, encoding, false);
}
private ResponseBuilder setHeader(CharSequence name, Object value, boolean append) {
if (value instanceof Iterable) {
((Iterable) value).forEach(v -> setHeader(name, v, append));
} else {
if (value == null) {
headers.remove(name.toString());
} else {
if (append) {
headers.add(name.toString(), value);
} else {
headers.putSingle(name.toString(), value);
}
}
}
return this;
}
@Override
public ResponseBuilder header(String name, Object value) {
return setHeader(name, value, true); // TODO should this actually be false?
}
@Override
public ResponseBuilder replaceAll(MultivaluedMap<String, Object> headers) {
this.headers.clear();
if (headers != null) {
for (Map.Entry<String, List<Object>> entry : headers.entrySet()) {
this.headers.add(entry.getKey(), entry.getValue());
}
}
return this;
}
@Override
public ResponseBuilder language(String language) {
return setHeader(HeaderNames.CONTENT_LANGUAGE, language, false);
}
@Override
public ResponseBuilder language(Locale language) {
return language(language == null ? null : language.toLanguageTag());
}
@Override
public ResponseBuilder type(MediaType type) {
this.type = type;
return this;
}
@Override
public ResponseBuilder type(String type) {
if (type == null) {
this.type = null;
return this;
}
return type(MediaType.valueOf(type));
}
@Override
public ResponseBuilder variant(Variant variant) {
language(variant == null ? null : variant.getLanguage());
type(variant == null ? null : variant.getMediaType());
encoding(variant == null ? null : variant.getEncoding());
return this;
}
@Override
public ResponseBuilder contentLocation(URI location) {
return setHeader(HeaderNames.CONTENT_LOCATION, location, false);
}
@Override
public ResponseBuilder cookie(NewCookie... cookies) {
this.cookies = cookies;
if (cookies == null) {
headers.remove(HeaderNames.SET_COOKIE.toString());
}
return this;
}
@Override
public ResponseBuilder expires(Date expires) {
return setHeader(HeaderNames.EXPIRES, expires, false);
}
@Override
public ResponseBuilder lastModified(Date lastModified) {
return setHeader(HeaderNames.LAST_MODIFIED, lastModified, false);
}
@Override
public ResponseBuilder location(URI location) {
return setHeader(HeaderNames.LOCATION, location, false);
}
@Override
public ResponseBuilder tag(EntityTag tag) {
return setHeader(HeaderNames.ETAG, tag, false);
}
@Override
public ResponseBuilder tag(String tag) {
return tag(new EntityTag(tag));
}
@Override
public ResponseBuilder variants(Variant... variants) {
return variants(asList(variants));
}
@Override
public ResponseBuilder variants(List<Variant> variants) {
for (Variant variant : variants) {
if (variant == null) {
this.headers.remove("vary");
} else {
List<Object> existing = this.headers.get("vary");
if (existing == null) {
existing = emptyList();
}
if (variant.getMediaType() != null && !existing.contains("content-type")) {
this.headers.add("vary", "content-type");
}
if (variant.getLanguage() != null && !existing.contains("content-language")) {
this.headers.add("vary", "content-language");
}
if (variant.getEncoding() != null && !existing.contains("content-encoding")) {
this.headers.add("vary", "content-encoding");
}
}
}
return this;
}
@Override
public ResponseBuilder links(Link... links) {
if (links == null) {
linkHeaders.clear();
} else {
linkHeaders.addAll(asList(links));
}
return this;
}
@Override
public ResponseBuilder link(URI uri, String rel) {
Link link = Link.fromUri(uri).rel(rel).build();
linkHeaders.add(link);
return this;
}
@Override
public ResponseBuilder link(String uri, String rel) {
return link(URI.create(uri), rel);
}
}
private static class CustomStatus implements StatusType {
private final String reason;
private final Status.Family family;
private final int code;
private CustomStatus(Status.Family family, int code, String reason) {
this.reason = reason;
this.family = family;
this.code = code;
}
@Override
public int getStatusCode() {
return code;
}
@Override
public Status.Family getFamily() {
return family;
}
@Override
public String getReasonPhrase() {
return reason;
}
}
}
| 30.177778 | 163 | 0.593029 |
b814ba050dcad425c7d4ee44d7b1c967133eb049 | 1,682 | package ru.job4j.tdd;
import org.junit.Test;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* @author Alexander Abramov (alllexe@mail.ru)
* @version 1
* @since 03.07.2019
*/
public class SimpleGeneratorTest {
@Test
public void whenTwoKeysShouldRightPhrase() {
String template = "I am a ${name}, Who are ${subject}?";
Map<String, String> values = Map.of("name", "Petr", "subject", "you");
String expected = "I am a Petr, Who are you?";
assertThat(SimpleGenerator.formatString(template, values), is(expected));
}
@Test
public void whenOneKeyThreeTimesShouldRightPhrase() {
String template = "Help, ${sos}, ${sos}, ${sos}";
Map<String, String> values = Map.of("sos", "Aaa");
String expected = "Help, Aaa, Aaa, Aaa";
assertThat(SimpleGenerator.formatString(template, values), is(expected));
}
@Test(expected = RuntimeException.class)
public void whenLessKeysShouldExceptions() {
String template = "I am a ${name}, Who are ${subject}?";
Map<String, String> values = Map.of("name", "Petr");
String expected = "I am Petr, Who are you?";
assertThat(SimpleGenerator.formatString(template, values), is(expected));
}
@Test(expected = RuntimeException.class)
public void whenMoreKeysShouldExceptions() {
String template = "I am a ${name}, Who are you?";
Map<String, String> values = Map.of("name", "Petr", "subject", "you");
String expected = "I am Petr, Who are you?";
assertThat(SimpleGenerator.formatString(template, values), is(expected));
}
} | 33.64 | 81 | 0.642093 |
9481db292cbb0e25db99f135297596f5d172c675 | 7,620 | package com.o3dr.services.android.lib.drone.companion.solo.tlv;
import com.MAVLink.enums.GOPRO_COMMAND;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Unit test for the TLVMessageParser class.
*/
public class TLVMessageParserTest {
@Test
public void testParseTLVPacket_nullParams() throws Exception {
List<TLVPacket> results;
//Test for invalid parameters
results = TLVMessageParser.parseTLVPacket((byte[]) null);
assertNull(results);
}
@Test
public void testParseTLVPacket_emptyParams() {
List<TLVPacket> results;
results = TLVMessageParser.parseTLVPacket(new byte[0]);
assertNull(results);
}
@Test
public void testParseTLVPacket_singleMessage() {
List<TLVPacket> results;
//Single message parsing test
SoloMessageLocation messageLoc = new SoloMessageLocation(5.3488066, -4.0499032, 10);
byte[] messageLocBytes = messageLoc.toBytes();
results = TLVMessageParser.parseTLVPacket(messageLocBytes);
assertNotNull(results);
assertTrue(results.size() == 1);
TLVPacket resultPacket = results.get(0);
assertTrue(resultPacket.getMessageLength() == messageLoc.getMessageLength());
assertTrue(resultPacket.getMessageType() == messageLoc.getMessageType());
assertTrue(resultPacket instanceof SoloMessageLocation);
SoloMessageLocation castedResult = (SoloMessageLocation) resultPacket;
assertTrue(castedResult.getCoordinate().equals(messageLoc.getCoordinate()));
}
@Test
public void testParseTLVPacket_multipleMessages() {
List<TLVPacket> results;
SoloMessageLocation messageLoc = new SoloMessageLocation(5.3488066, -4.0499032, 10);
//Multiple message parsing test
//1.
ByteBuffer inputData = ByteBuffer.allocate(46);
SoloMessageShotGetter shotGetter = new SoloMessageShotGetter(SoloMessageShot.SHOT_CABLECAM);
TLVPacket[] inputPackets = {messageLoc, shotGetter};
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertTrue(results.size() == inputPackets.length);
assertTrue(inputData.remaining() == 6);
for (int i = 0; i < inputPackets.length; i++) {
TLVPacket inputPacket = inputPackets[i];
TLVPacket outputPacket = results.get(i);
assertTrue(inputPacket.equals(outputPacket));
}
}
@Test
public void testParseTLVPacket_multipleMessages2() {
List<TLVPacket> results;
//2.
SoloMessageShotGetter shotGetter = new SoloMessageShotGetter(SoloMessageShot.SHOT_CABLECAM);
SoloMessageLocation messageLoc = new SoloMessageLocation(5.3488066, -4.0499032, 10);
ByteBuffer inputData = ByteBuffer.allocate(40);
TLVPacket[] inputPackets = {messageLoc, shotGetter};
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertTrue(results.size() == inputPackets.length);
assertTrue(inputData.remaining() == 0);
for (int i = 0; i < inputPackets.length; i++) {
TLVPacket inputPacket = inputPackets[i];
TLVPacket outputPacket = results.get(i);
assertTrue(inputPacket.equals(outputPacket));
}
}
@Test
public void testParseTLVPacket_goProSetExtended() {
byte[] values = new byte[4];
SoloGoproSetExtendedRequest extendedRequest =
new SoloGoproSetExtendedRequest((short) GOPRO_COMMAND.GOPRO_COMMAND_CAPTURE_MODE, values);
TLVPacket[] inputPackets = {extendedRequest};
ByteBuffer inputData = ByteBuffer.allocate(14);
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
List<TLVPacket> results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertEquals(inputPackets.length, results.size());
assertEquals(0, inputData.remaining());
assertEquals(extendedRequest, results.get(0));
}
@Test
public void testParseTLVPacket_goProSetRequest() {
SoloGoproSetRequest setRequest =
new SoloGoproSetRequest((short) GOPRO_COMMAND.GOPRO_COMMAND_CAPTURE_MODE, SoloGoproConstants.CAPTURE_MODE_PHOTO);
TLVPacket[] inputPackets = {setRequest};
ByteBuffer inputData = ByteBuffer.allocate(12);
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
List<TLVPacket> results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertEquals(inputPackets.length, results.size());
assertEquals(0, inputData.remaining());
assertEquals(setRequest, results.get(0));
}
@Test
public void testParseTLVPacket_goProRecord() {
SoloGoproRecord record =
new SoloGoproRecord(SoloGoproConstants.STOP_RECORDING);
TLVPacket[] inputPackets = {record};
ByteBuffer inputData = ByteBuffer.allocate(12);
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
List<TLVPacket> results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertEquals(0, inputData.remaining());
assertEquals(record, results.get(0));
}
@Test
public void testParseTLVPacket_goProState() {
SoloGoproState state =
new SoloGoproState(
(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1,
(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1,
(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1,
(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1);
TLVPacket[] inputPackets = {state};
ByteBuffer inputData = ByteBuffer.allocate(44);
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
List<TLVPacket> results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertEquals(inputPackets.length, results.size());
assertEquals(0, inputData.remaining());
assertEquals(state, results.get(0));
}
@Test
public void testParseTLVPacket_goProRequestState() {
SoloGoproRequestState requestState =
new SoloGoproRequestState();
TLVPacket[] inputPackets = {requestState};
ByteBuffer inputData = ByteBuffer.allocate(8);
for (TLVPacket packet : inputPackets) {
inputData.put(packet.toBytes());
}
inputData.rewind();
List<TLVPacket> results = TLVMessageParser.parseTLVPacket(inputData);
assertNotNull(results);
assertEquals(inputPackets.length, results.size());
assertEquals(0, inputData.remaining());
assertEquals(requestState, results.get(0));
}
} | 34.479638 | 125 | 0.652756 |
1ef934d91fdf95b29ec2a97e7edb9faac95431a8 | 11,113 | package chariot;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.prefs.Preferences;
import chariot.api.*;
import chariot.api.Builders.*;
import chariot.internal.Config;
/**
* Provides access to the <a href="https://lichess.org/api">Lichess API</a>.
*
* <p>
* There are two types of factory methods to create basic non-authenticated clients, {@link chariot.Client}, and authenticated clients, {@link chariot.ClientAuth}.
*
* <p>
* Examples of how to create a client
*
* <p>
* For accessing non-authenticated parts of the <a href="https://lichess.org/api">Lichess API</a>:
*
* <pre>{@code
* Client client = Client.basic();
*
* // Tada!
*
* // And then use it...
* var user = client.users().byId("lichess");
* }</pre>
*
* <p>
* For accessing authenticated parts of the <a href="https://lichess.org/api">Lichess API</a>:<br>
* <i>
* Note, a valid token must be acquired in order to use the endpoints exposed by
* {@link chariot.ClientAuth}, either by obtaining a <a
* href="https://lichess.org/account/oauth/token">Personal Access Token</a> or by
* integrating a <a href="https://oauth.net/2/pkce/">PKCE Authorization Code flow</a> in the application - see {@link
* chariot.api.Account} for more information.
* </i>
*
* <pre>{@code
* var token = ... // Token with scope email:read
* ClientAuth client = Client.auth(token);
*
* var email = client.account().emailAddress();
* }</pre>
*
* <p>
* The responses from the APIs are modelled with a {@link chariot.model.Result}{@literal <T>} "container".<br>
* Its documentation covers the types of responses (Result) and various ways of accessing their values (T).<br>
* The types of the values (T) used in the APIs are bundled in the {@link chariot.model} package - simple data holders / records.
*
* <p>
* An additional way of creating a client is via the
* {@link #load(Preferences) load(prefs)}/{@link #store(Preferences) store(prefs)} methods, keeping
* the configuration in {@link java.util.prefs.Preferences},
* <pre>{@code
* Preferences prefs = Preferences.userPrefs("myprefs");
* Client client = Client.load(prefs);
* if (client instanceof ClientAuth clientAuth) {
* // We've managed to restore our previously stored configuration,
* // so let's get right down to business.
* clientAuth.account().setKidModeStatus(true); // lol
* } else {
* // It seems this was the first time we ran this program,
* // we have yet to store its configuration.
* // Let's perform the heavy-lifting now.
* var urlToken = client.account().oauthPKCE(Scope.preferences_write);
* System.out.println("Please grant this application access at Lichess: " + urlToken.url());
*
* // Wait for the user to go to Lichess and click Grant. (They wouldn't click Deny, right?)
* var token = urlToken.token().get();
*
* var clientAuth = Client.auth(token);
*
* // Now we can store the configuration for quick access next time.
* clientAuth.store(prefs);
*
* // Oh yeah, and...
* clientAuth.account().setKidModeStatus(true); // lol
* }
* }</pre>
*
* <p>
* There are also customizable variants,
* <pre>{@code
* // http://localhost:9663
* var client = Client.basic(c -> c.local());
*
* var clientAuth = Client.auth(c -> c.api("https://lichess.dev").auth("mytoken"));
* }</pre>
*/
public sealed interface Client permits ClientAuth, Client.Basic {
sealed interface Basic extends Client permits chariot.internal.BasicClient {}
/**
* Creates a default client
*/
static Client basic() {
return basic(Config.basic(c -> c.production()));
}
/**
* Creates a default client using the provided token to use the authenticated parts of the API
* @param token A token to use for the authenticated parts of the API
*/
static ClientAuth auth(String token) {
return auth(c -> c.production().auth(token));
}
/**
* Helps to perform a OAuth 2 PKCE flow or prepare a URL to create a Personal API Token with specified Scope/s.
*/
Account account();
/**
* Access Lichess cloud evaluations database.
*/
Analysis analysis();
/**
* Access Lichess online bots.<br/>
* For more bot operations, see {@link chariot.ClientAuth#bot}
*/
Bot bot();
/**
* Relay chess events on Lichess.
* <p>Official broadcasts are maintained by Lichess, but you can create your own
* broadcasts to cover any live game or chess event. You will need to publish
* PGN on a public URL so that Lichess can pull updates from it.
* Alternatively, you can push PGN updates to Lichess using this API.
* <p>Broadcasts are organized in tournaments, which have several rounds, which
* have several games. You must first create a tournament, then you can add
* rounds to them.
*/
Broadcasts broadcasts();
/**
* Open-ended challenges. For authenticated challenges, see {@link chariot.api.ChallengesAuth}
*/
Challenges challenges();
/**
* Access games and TV channels, played on Lichess.
*/
Games games();
/**
* Access Lichess puzzle history and dashboard.
*/
Puzzles puzzles();
/**
* Access simuls played on Lichess.
*/
Simuls simuls();
/**
* Access Lichess studies.
*/
Studies studies();
/**
* Access and manage Lichess teams and their members.
*/
Teams teams();
/**
* Access Arena and Swiss tournaments played on Lichess.<br/>
*/
Tournaments tournaments();
/**
* Access registered users on Lichess.
*/
Users users();
/**
* Creates a customized client
* @param params A configuration parameters builder
*/
static Client basic(Consumer<Builder> params){
return basic(Config.basic(params));
}
/**
* Creates a customizable client using the provided configuration parameters builder.<br>
* Note, make sure to supply a token using the withToken* methods, or a IllegalArgumentException will be thrown.
* @param params A configuration parameters builder
*/
static ClientAuth auth(Consumer<TokenBuilder> params) {
return auth(Config.auth(params));
}
/**
* Creates a default client using the provided token to use the authenticated parts of the API
* @param token A token to use for the authenticated parts of the API
*/
static ClientAuth auth(Supplier<char[]> token) {
return auth(c -> c.production().auth(token));
}
/**
* Creates a customized client from a preferences node<br>
* See {@link Client#store(Preferences)}
* @param prefs A configuration preferences node<br>
* {@code if (client instanceof ClientAuth auth) ...}
*/
static Client load(Preferences prefs) {
return load(Config.load(prefs));
}
/**
* Stores the client configuration into the provided preferences node<br>
* See {@link Client#load(Preferences)}
* @param prefs The preferences node to store this client configuration to
*/
boolean store(Preferences prefs);
/**
* Creates an authenticated customized client from a preferences node with provided token<br>
* @param prefs A configuration preferences node
* @param token A token to use for the authenticated parts of the API
*/
static ClientAuth load(Preferences prefs, Consumer<AuthBuilder> token) {
return auth(Config.load(prefs, token));
}
/**
* Retrieves an Optional containing a {@code ClientAuth} if this is such a client, otherwise empty.
*/
default Optional<ClientAuth> asAuth() {
return this instanceof chariot.internal.AuthClient auth ? Optional.of(auth) : Optional.empty();
}
/**
* Configure logging levels
*/
default void levels(Consumer<LogSetter> params) {
var builder = new Config.LBuilderImpl(false);
params.accept(builder);
}
private static Client load(Config config) {
// --enable-preview
//return switch(config) {
// case Config.Auth auth -> new AuthClient(auth);
// case Config.Basic basic -> new BasicClient(basic);
//};
if (config instanceof Config.Basic b) {
return new chariot.internal.BasicClient(b);
} else if (config instanceof Config.Auth a) {
return new chariot.internal.AuthClient(a);
}
throw new RuntimeException("Unknown config type: " + config);
}
private static Client basic(Config.Basic config) {
return new chariot.internal.BasicClient(config);
}
private static ClientAuth auth(Config.Auth config) {
return new chariot.internal.AuthClient(config);
}
/**
* OAuth scopes representing different permissions
*/
public enum Scope {
/**
* Read your preferences
*/
preference_read,
/**
* Write your preferences
*/
preference_write,
/**
* Read your email address
*/
email_read,
/**
* Read incoming challenges
*/
challenge_read,
/**
* Create, accept, decline challenges
*/
challenge_write,
/**
* Create, delete, query bulk pairings
*/
challenge_bulk,
/**
* Read private studies and broadcasts
*/
study_read,
/**
* Create, update, delete studies and broadcasts
*/
study_write,
/**
* Create tournaments
*/
tournament_write,
/**
* Read puzzle activity
*/
puzzle_read,
/**
* Read private team information
*/
team_read,
/**
* Join, leave, and manage teams
*/
team_write,
/**
* Send private messages to other players
*/
msg_write,
/**
* Play with the Board API
*/
board_play,
/**
* Play with the Bot API. Only for Bot accounts
*/
bot_play,
/**
* Follow and Unfollow players
*/
follow_write,
/**
* Create authenticated website sessions (grants full access!)
*/
web_login,
web_mod,
any;
public String asString() {
return switch (this) {
case any -> "*";
default -> name().replace("_", ":");
};
}
public static Optional<Scope> fromString(String scope) {
try {
// preferences:read -> preferences_read
return Optional.of(valueOf(scope.replace(":", "_")));
} catch (Exception e) {
return Optional.empty();
}
}
}
}
| 29.015666 | 163 | 0.602987 |
9df63645b583f1857923fd60663f8225c3c3364d | 2,191 | package com.example.DemoGraphQL.service;
import com.example.DemoGraphQL.model.Person;
import com.example.DemoGraphQL.model.Skill;
import com.example.DemoGraphQL.repository.PersonRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
@Service
public class PersonService {
private final PersonRepository personRepository;
public PersonService(final PersonRepository personRepository) {
this.personRepository = personRepository;
}
public Optional<Person> getPerson(final long id) {
return this.personRepository.findById(id);
}
public Person getRandomPerson() {
List<Person> givenList = this.personRepository.findAll();
Random rand = new Random();
return givenList.get(rand.nextInt(givenList.size()));
}
public List<Person> getPersons(Optional<Long> id) {
List<Person> persons = new ArrayList<>();
return id.map(v -> {
this.personRepository.findById(v).ifPresent(persons::add);
return persons;
}).orElse(this.personRepository.findAll());
}
public Optional<Person> getPerson(Optional<Long> id) {
return id.map(v -> this.personRepository.findById(v)).orElse(null);
}
public List<Person> getFriends(Person person, Optional<Long> friendId) {
List<Person> friends = new ArrayList<>();
return friendId.map(v -> {
person.getFriends().stream()
.filter(myFriend -> myFriend.getId().equals(v))
.findFirst()
.ifPresent(friends::add);
return friends;
}).orElse(new ArrayList<>(person.getFriends()));
}
public List<Skill> getSkills(Person person, Optional<Long> skillId) {
List<Skill> skills = new ArrayList<>();
return skillId.map(v -> {
person.getSkills().stream()
.filter(mySkill -> mySkill.getId().equals(v))
.findFirst()
.ifPresent(skills::add);
return skills;
}).orElse(new ArrayList<>(person.getSkills()));
}
}
| 33.19697 | 76 | 0.635783 |
1d465662ac66283a9d165137167f249a49df0e1c | 1,010 | package epicara.UI;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by nishant on 16-05-09.
*/
public class CardImageView extends ImageView {
private float mAspectRatio;
public CardImageView(Context context) {
super(context);
}
public CardImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CardImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setAspectRatio(float aspectRatio) {
mAspectRatio = aspectRatio;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int)((float)width / mAspectRatio);
setMeasuredDimension(width, height);
}
}
| 27.297297 | 81 | 0.631683 |
6dae12f01393f6f7f47cb631d4e837af0a544a78 | 720 | package com.jesus.lunape.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Perfiles")
public class Perfil {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String perfil;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPerfil() {
return perfil;
}
public void setPerfil(String perfil) {
this.perfil = perfil;
}
@Override
public String toString() {
return "Perfil [id=" + id + ", perfil=" + perfil + "]";
}
}
| 19.459459 | 58 | 0.683333 |
8378ad19f541f16abb4dd8b8a57730a0dd27aa7f | 859 | package org.togglz.core.spi;
import java.util.Collection;
import org.togglz.core.manager.TogglzConfig;
/**
*
* This SPI is used by Tooglz to lookup beans that are managed by bean containers like CDI or Spring. Currently Togglz uses this
* feature only for finding the {@link TogglzConfig} implementation.
*
* @author Christian Kaltepoth
*
*/
public interface BeanFinder {
/**
* Retrieve a list of all beans of the given type.
*
* @param clazz The type to lookup. In most cases this will be an interface.
* @param context An optional context that may help the implementation to interact with the bean container. In Servlet
* environments this context object is the ServletContext.
* @return A list of beans, never <code>null</code>
*/
<E> Collection<E> find(Class<E> clazz, Object context);
}
| 29.62069 | 128 | 0.701979 |
610c71f9b9e6cb32cdd84778b6e8e4d611b2756e | 633 | package org.arun.cucumber.sharingstate.entity;
import java.time.LocalDate;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name = "employee")
public class EmployeeEntity {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private LocalDate joinDate;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<ContactEntity> contacts;
}
| 22.607143 | 61 | 0.794629 |
a112b8b3dc5524c15eb73d4b89cf2c14ba4cfdeb | 923 | package deltix.qsrv.hf.pub.codec.intp;
import deltix.qsrv.hf.pub.codec.*;
import deltix.qsrv.hf.pub.md.IntegerDataType;
import deltix.util.text.CharSequenceParser;
/**
*
*/
class IntTimeIntervalFieldEncoder extends IntegerFieldEncoder {
public IntTimeIntervalFieldEncoder (NonStaticFieldLayout f) {
super (f);
}
@Override
void writeNull(EncodingContext ctxt) {
setLong(IntegerDataType.PINTERVAL_NULL, ctxt);
}
@Override
protected boolean isNull(long value) {
return value == IntegerDataType.PINTERVAL_NULL;
}
@Override
void setString (CharSequence value, EncodingContext ctxt) {
setLong (CharSequenceParser.parseInt (value), ctxt);
}
@Override
void setLongImpl (long value, EncodingContext ctxt) {
deltix.qsrv.hf.pub.codec.TimeIntervalCodec.write(value, ctxt.out);
}
}
| 26.371429 | 82 | 0.665222 |
a4a03c9ff6096079bbc73519c931ece266415251 | 4,356 | package atas.model.statistics;
import java.util.HashSet;
import java.util.Set;
import atas.model.session.Session;
/**
* Represents a set of statistical data of students in a session.
*/
public class SessionStatistics {
private final Set<Statistics> stats;
/**
* A constructor which initializes with default statistical values.
*/
public SessionStatistics() {
this.stats = new HashSet<>();
this.stats.add(new PresenceStatistics());
this.stats.add(new ParticipationStatistics());
}
/**
* A constructor which initializes with given sample size.
*/
public SessionStatistics(int sampleSize) {
this.stats = new HashSet<>();
this.stats.add(new PresenceStatistics(0, sampleSize));
this.stats.add(new ParticipationStatistics(0, sampleSize));
}
/**
* Adds the given statistic to the current set of statistics in the session.
*/
public void addStatistics(Statistics statistics) {
stats.add(statistics);
}
/**
* Adds the given statistics to the current set of statistics in the session.
*/
public void addStatistics(Statistics... statistics) {
// do not change this to Collections.addAll, they are not the same.
for (Statistics stat: statistics) {
stats.add(stat);
}
}
/**
* Replaces statistic in the set with the given one.
* If there is already a statistic of the same type, it will be replaced with the new one. Or else
* if there isn't a static of the same type, it will be added to the set.
*/
public void replaceStatistics(Statistics statistics) {
stats.removeIf(statistics::isSameStats);
stats.add(statistics);
}
/**
* Replaces statistics in the set with the given collection of statistics.
* Statistic type that already exists in the set will be removed and replaced with the new one.
* A new one will be added to the set if does not exist.
*/
public void replaceStatistics(Statistics... statistics) {
for (Statistics stat: statistics) {
stats.removeIf(stat::isSameStats);
stats.add(stat);
}
}
/**
* Updates the current participation statistic data with the given session.
*/
public void updateParticipationStatistics(Session session) {
replaceStatistics(new ParticipationStatistics().getSessionStatistics(session));
}
/**
* Updates the current presence statistic data with the given session.
*/
public void updatePresenceStatistics(Session session) {
replaceStatistics(new PresenceStatistics().getSessionStatistics(session));
}
/**
* Searches the set of statistics for a {@code ParticipationStatistics}.
*/
public Statistics getParticipationStatistics() {
Statistics participationStatistics = null;
for (Statistics statistics: stats) {
if (statistics instanceof ParticipationStatistics) {
participationStatistics = statistics;
break;
}
}
return participationStatistics;
}
/**
* Searches the set of statistics for a {@code PresenceStatistics}.
*/
public Statistics getPresenceStatistics() {
Statistics presenceStatistics = null;
for (Statistics statistics: stats) {
if (statistics instanceof PresenceStatistics) {
presenceStatistics = statistics;
break;
}
}
return presenceStatistics;
}
public Set<Statistics> getStats() {
return stats;
}
/**
* Checks if the set of statistics contain the same type of given statistics.
*/
public boolean contains(Statistics statistics) {
for (Statistics stat: stats) {
if (statistics.getClass() == stat.getClass()) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass()) {
return false;
} else {
for (Statistics stat: ((SessionStatistics) o).getStats()) {
if (!contains(stat)) {
return false;
}
}
return true;
}
}
}
| 30.041379 | 102 | 0.614784 |
620b855b6380adb6fb75047c79d3aba92146fa16 | 378 | package com.pleiterson.ecommerce.checkoutpaymentecommerce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CheckoutPaymentEcommerceApplication {
public static void main(String[] args) {
SpringApplication.run(CheckoutPaymentEcommerceApplication.class, args);
}
}
| 27 | 73 | 0.849206 |
6b2190a4cf115c9358a95ac4d09e001e5d29aa81 | 889 | package in.srain.cube.views.banner;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.viewpager.widget.PagerAdapter;
public abstract class BannerAdapter extends PagerAdapter {
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = getView(LayoutInflater.from(container.getContext()), position);
container.addView(view);
return view;
}
public int getPositionForIndicator(int position) {
return position;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
public abstract View getView(LayoutInflater layoutInflater, int position);
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
}
| 26.147059 | 83 | 0.715411 |
b2960d539ae08fe5562da12b19ed89047050cc1b | 2,035 | package krasa.grepconsole.filter;
import com.intellij.execution.filters.InputFilter;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import krasa.grepconsole.filter.support.FilterState;
import krasa.grepconsole.filter.support.GrepProcessor;
import krasa.grepconsole.model.GrepExpressionItem;
import krasa.grepconsole.model.Profile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GrepInputFilter extends AbstractGrepFilter implements InputFilter {
public GrepInputFilter(Project project) {
super(project);
}
public GrepInputFilter(Profile profile, List<GrepProcessor> grepProcessors) {
super(profile, grepProcessors);
}
@Override
public List<Pair<String, ConsoleViewContentType>> applyFilter(String s,
ConsoleViewContentType consoleViewContentType) {
FilterState state = super.filter(s, -1);
return prepareResult(state);
}
@Override
protected boolean continueFiltering(FilterState state) {
return !state.isMatchesSomething();
}
private List<Pair<String, ConsoleViewContentType>> prepareResult(FilterState state) {
Pair<String, ConsoleViewContentType> result = null;
if (state != null) {
if (state.isExclude()) {
result = new Pair<>(null, null);
}
}
if (result == null) {
return null;// input is not changed
} else {
return Arrays.asList(result);
}
}
@Override
protected void initProcessors() {
grepProcessors = new ArrayList<>();
if (profile.isEnabledInputFiltering()) {
boolean inputFilterExists = false;
for (GrepExpressionItem grepExpressionItem : profile.getAllGrepExpressionItems()) {
grepProcessors.add(createProcessor(grepExpressionItem));
if (grepExpressionItem.isInputFilter()) {
inputFilterExists = true;
}
}
if (!inputFilterExists) {
grepProcessors.clear();
}
}
}
@Override
protected boolean shouldAdd(GrepExpressionItem item) {
throw new UnsupportedOperationException();
}
}
| 27.133333 | 86 | 0.759214 |
97a99103b94e6d5eec43860762a25d143562ff6d | 957 | package org.jdbcdslog;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class DriverLoggingProxyTest extends TestCase {
public DriverLoggingProxyTest(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(DriverLoggingProxyTest.class);
}
public void test() throws Exception {
DriverLoggingProxy proxy = new DriverLoggingProxy();
Properties pr = new Properties();
pr.put("user", "sa");
Connection con = proxy.connect("jdbc:jdbcdslog:hsqldb:mem:mymemdb;targetDriver=org.hsqldb.jdbcDriver", pr);
con.createStatement().execute("create table test_dr (a integer)");
con.createStatement().execute("insert into test_dr values(1)");
ResultSet rs = con.createStatement().executeQuery("select * from test_dr");
rs.close();
con.close();
}
}
| 29.90625 | 110 | 0.730408 |
c6feda92370fe092689e09c66416231813fb4f0c | 5,062 | /*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.iris.oculus.modules.behaviors;
import java.awt.event.ActionEvent;
import java.util.concurrent.CancellationException;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
import javax.swing.Action;
import com.google.inject.Inject;
import com.iris.client.IrisClient;
import com.iris.client.capability.CareSubsystem;
import com.iris.client.capability.CareSubsystem.ListBehaviorsRequest;
import com.iris.client.capability.CareSubsystem.ListBehaviorsResponse;
import com.iris.client.capability.CareSubsystem.RemoveBehaviorRequest;
import com.iris.client.event.Listener;
import com.iris.client.event.ListenerRegistration;
import com.iris.client.bean.CareBehavior;
import com.iris.oculus.Oculus;
import com.iris.oculus.modules.session.OculusSession;
import com.iris.oculus.modules.session.SessionAwareController;
import com.iris.oculus.modules.session.OculusSession;
import com.iris.oculus.util.DefaultSelectionModel;
import com.iris.oculus.view.SimpleViewModel;
import com.iris.oculus.view.ViewModel;
/**
*
*/
public class BehaviorController extends SessionAwareController {
SimpleViewModel<CareBehavior> behaviors = new SimpleViewModel<>();
private DefaultSelectionModel<CareBehavior> behaviorSelection = new DefaultSelectionModel<>();
private IrisClient client;
@SuppressWarnings("serial")
private final Action refreshAction = new AbstractAction("Refresh") {
@Override
public void actionPerformed(ActionEvent e) {
refreshBehaviors();
}
};
@SuppressWarnings("serial")
private final Action deleteAction = new AbstractAction("Delete") {
@Override
public void actionPerformed(ActionEvent e) {
removeBehavior();
}
};
@Inject
public BehaviorController(IrisClient client) {
this.client = client;
}
public ListenerRegistration addBehaviorSelectedListener(Listener<CareBehavior> l) {
return behaviorSelection.addNullableSelectionListener(l);
}
public DefaultSelectionModel<CareBehavior> getSelectionModel() {
return behaviorSelection;
}
@Override
protected void onSessionInitialized(OculusSession info) {
refreshBehaviors();
}
@Override
protected void onPlaceChanged(String newPlaceId) {
refreshBehaviors();
}
@Override
protected void onSessionExpired() {
behaviors.removeAll();
}
protected void onRefresh(ListBehaviorsResponse response) {
onBehaviorsLoaded(response);
}
protected void onBehaviorsLoaded(ListBehaviorsResponse response) {
behaviors.removeAll();
behaviors.addAll(response.getBehaviors().stream().map(CareBehavior::new).collect(Collectors.toList()));
}
protected void doLoadBehaviors(Listener<ListBehaviorsResponse> l) {
if (!isSessionActive()) {
return;
}
OculusSession info = getSessionInfo();
if (info.getPlaceId() == null) {
return;
}
ListBehaviorsRequest request = new ListBehaviorsRequest();
request.setAddress("SERV:" + CareSubsystem.NAMESPACE + ":" + getPlaceId());
client.request(request)
.onSuccess((e) -> l.onEvent(new ListBehaviorsResponse(e)))
.onFailure((error) -> {
if (error instanceof CancellationException){
//timeout not sure what to do here. but lets be quiet
}
else{
Oculus.error("Unable to load behavior entries", error);
}
});
}
public Action refreshAction() {
return refreshAction;
}
public Action deleteAction() {
return deleteAction;
}
public void refreshBehaviors() {
doLoadBehaviors((r) -> onRefresh(r));
}
public void removeBehavior() {
if (behaviorSelection.hasSelection()) {
RemoveBehaviorRequest request = new RemoveBehaviorRequest();
request.setAddress("SERV:" + CareSubsystem.NAMESPACE + ":" + getPlaceId());
request.setAttribute(RemoveBehaviorRequest.ATTR_ID, behaviorSelection.getSelectedItem().get().getId());
client.request(request)
.onSuccess((e) -> {
behaviorSelection.clearSelection();
Oculus.info("Behavior Removed");
})
.onFailure((error) -> Oculus.error("Unable to remove behavior", error));
}
}
public ViewModel<CareBehavior> getBehaviors() {
return this.behaviors;
}
}
| 31.440994 | 112 | 0.696563 |
4743c0c33c2892cfc9d73a01edbfad5eeef22082 | 816 | package infrastructure.dao;
import java.sql.Connection;
import core.abstractions.DAOFactoryMethod;
import core.interfaces.dao.IDietaDAO;
import core.interfaces.dao.IPorcaoDeAlimentoDAO;
import core.interfaces.dao.IRegistroDeAtividadeDAO;
import core.interfaces.dao.IUsuarioDAO;
public class DAOFactory extends DAOFactoryMethod{
@Override
public IDietaDAO createDietaDAO(Connection conn) {
return new DietaDAO(conn);
}
@Override
public IPorcaoDeAlimentoDAO createPorcaoDeAlimentoDAO(Connection conn) {
return new PorcaoDeAlimentoDAO(conn);
}
@Override
public IRegistroDeAtividadeDAO createRegistroDeAtividadeDAO() {
return new RegistroDeAtividadeDAO();
}
@Override
public IUsuarioDAO createUsuarioDAO(Connection conn) {
// TODO Auto-generated method stub
return new UsuarioDAO(conn);
}
} | 24.727273 | 73 | 0.811275 |
6c42b9c4bf2e2d55ccd66be3d4a83050c4f70c0a | 1,239 | package com.guagua.qiqi.gifteffect.animation.algorithm;
/**
* Created by yujintao on 15/7/4.
*/
public class RandomRangeAWhile extends RandomRange {
private float record;
private float last;
private float curValue;
private float lastTime;
private boolean refresh;
/**
* 妙为单位
* @param b
* @param y
* @param last
*/
private RandomRangeAWhile(int b, int y, float last) {
super(b, y);
if (last <= 0) {
throw new IllegalArgumentException("last must not liiter 0");
}
this.last = last*1000;
record = 0;
lastTime=0;
refresh=true;
}
@Override
public float caculate(int time) {
float left = time-lastTime;
lastTime=time;
if(refresh){
curValue=super.caculate(time);
refresh=false;
}
if((record+=left)>last){
record-=last;
refresh=true;
}
return curValue;
}
/**
* @param b 起始值
* @param y 最大值
* @param time 单位是秒
* @return
* @return: RandomRange
*/
public static RandomRange build(int b, int y, float time) {
return new RandomRangeAWhile(b, y, time);
}
}
| 21.736842 | 73 | 0.54883 |
2bd3fda2a384183c2539e8179fc7476f22a1c028 | 4,097 | /*
This program is to find the Path from a Node of the Binary Tree to Root of that Binary Tree
1. We are given a partially written BinaryTree class.
2. We are given an element.
3. We are required to complete the body of find and nodeToRoot function. The functions are expected to
3.1. find -> return true or false depending on if the data is found in binary tree.
3.2. nodeToRoot -> returns the path from node (correspoding to data) to root in
form of an arraylist (root being the last element)
*/
import java.io.*;
import java.util.*;
public class nodetorootpath_ {
// This class can be used as a reference to create a new Node in a Binary Tree
public static class Node {
int data;
Node left;
Node right;
Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public static class Pair {
Node node;
int state;
Pair(Node node, int state) {
this.node = node;
this.state = state;
}
}
// This function pushes all Node values into a stack
public static Node construct(Integer[] arr) {
Node root = new Node(arr[0], null, null);
Pair rtp = new Pair(root, 1);
Stack<Pair> st = new Stack<>();
st.push(rtp);
int idx = 0;
while (st.size() > 0) {
Pair top = st.peek();
if (top.state == 1) {
idx++;
if (arr[idx] != null) {
top.node.left = new Node(arr[idx], null, null);
Pair lp = new Pair(top.node.left, 1);
st.push(lp);
} else {
top.node.left = null;
}
top.state++;
} else if (top.state == 2) {
idx++;
if (arr[idx] != null) {
top.node.right = new Node(arr[idx], null, null);
Pair rp = new Pair(top.node.right, 1);
st.push(rp);
} else {
top.node.right = null;
}
top.state++;
} else {
st.pop();
}
}
return root;
}
// This function will help to display the binary tree
public static void display(Node node) {
if (node == null) {
return;
}
String str = "";
str += node.left == null ? "." : node.left.data + "";
str += " <- " + node.data + " -> ";
str += node.right == null ? "." : node.right.data + "";
System.out.println(str);
display(node.left);
display(node.right);
}
// to check if the data is present in the tree or not
public static boolean find(Node node, int data) {
// write your code here
if (node == null)
return false;
boolean res = node.data == data;
return res || find(node.left, data) || find(node.right, data);
}
static ArrayList<Integer> path = new ArrayList<>();
public static boolean Helper(Node node, int data) {
if (node == null)
return false;
boolean res = (node.data == data) || Helper(node.left, data) || Helper(node.right, data);
if (res) {
path.add(node.data);
}
return res;
}
public static ArrayList<Integer> nodeToRootPath(Node node, int data) {
// write your code here
path = new ArrayList<>(); // reinitialisation of the arraylist
Helper(node, data);
return path;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
if (values[i].equals("n") == false) {
arr[i] = Integer.parseInt(values[i]);
} else {
arr[i] = null;
}
}
int data = Integer.parseInt(br.readLine());
Node root = construct(arr);
boolean found = find(root, data);
System.out.println(found);
ArrayList<Integer> path = nodeToRootPath(root, data);
System.out.println(path);
}
}
/*
I/P:
19
50 25 12 n n 37 30 n n n 75 62 n 70 n n 87 n n
30
O/P:
true
[30, 37, 25, 50]
Worst Case Time Complexity : O(n)
Space Complexity : O(1)
*/
| 24.532934 | 105 | 0.575055 |
e7cf8c911dacf48046e03376dccbf953807fd76b | 390 | package com.luna.common.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 禁止重复提交
*
* @author luna_mac
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotRepeatSubmit {
/** 过期时间,单位毫秒 **/
long value() default 5000;
} | 20.526316 | 44 | 0.751282 |
5364d3765c46327319ef9c7ae56b18152bea25f9 | 2,432 | /*
* Copyright 2017, Flávio Keglevich
*
* 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.fkeglevich.rawdumper.camera.feature.restriction.chain;
import com.fkeglevich.rawdumper.camera.feature.VirtualFeature;
import com.fkeglevich.rawdumper.camera.feature.WritableFeature;
import com.fkeglevich.rawdumper.camera.feature.restriction.chain.fixer.FeatureValueFixer;
import com.fkeglevich.rawdumper.camera.feature.restriction.chain.validator.ValidatorFactory;
import com.fkeglevich.rawdumper.camera.parameter.value.ValueValidator;
/**
* TODO: Add class header
* <p>
* Created by Flávio Keglevich on 31/10/17.
*/
class ChainNode<M, S, L>
{
private final VirtualFeature master;
private final ValidatorFactory<M, S, L> validatorFactory;
private final FeatureValueFixer<M, S, L> featureValueFixer;
private final WritableFeature<S, L> slave;
ChainNode(VirtualFeature master, ValidatorFactory<M, S, L> validatorFactory, FeatureValueFixer<M, S, L> featureValueFixer, WritableFeature<S, L> slave)
{
this.master = master;
this.validatorFactory = validatorFactory;
this.featureValueFixer = featureValueFixer;
this.slave = slave;
}
void propagateChange(M newMasterValue)
{
getMaster().performUpdate();
S slaveValue = slave.getValue();
if (slave.isMutable())
{
ValueValidator<S, L> newSlaveValidator = validatorFactory.create(newMasterValue);
if (!newSlaveValidator.isValid(slaveValue))
slaveValue = featureValueFixer.fixValue(newSlaveValidator, slaveValue, newMasterValue);
slave.changeValidator(newSlaveValidator, slaveValue);
}
else
{
slave.setValue(featureValueFixer.fixValue(slave.getValidator(), slaveValue, newMasterValue));
}
}
public VirtualFeature getMaster()
{
return master;
}
}
| 33.777778 | 155 | 0.715872 |
82658c6ec22680e9c4751da012d1d65cfedf9c88 | 632 |
package com.houarizegai.quizappfx.dao.vo;
public class QuestionVo {
private String question;
private String[] response;
private String solution;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getResponse() {
return response;
}
public void setResponse(String[] response) {
this.response = response;
}
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
}
| 18.588235 | 48 | 0.625 |
6c6f6c82ab036305804be8321b05b737c3f98c5b | 7,850 | package org.crazycake.formSqlBuilder;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.Table;
import org.crazycake.formSqlBuilder.annotation.DefaultSort;
import org.crazycake.formSqlBuilder.exception.FormIsNullException;
import org.crazycake.formSqlBuilder.model.Rule;
import org.crazycake.formSqlBuilder.model.Sort;
import org.crazycake.formSqlBuilder.model.SqlAndParams;
import org.crazycake.formSqlBuilder.prop.RuleSchemeLoader;
import org.crazycake.formSqlBuilder.ruleGenerator.DefaultRuleSchemeGenerator;
import org.crazycake.formSqlBuilder.ruleGenerator.IRuleSchemeGenerator;
import org.crazycake.utils.CamelNameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 将表单
* @author Administrator
*
*/
public class FormSqlBuilder {
private static Logger logger = LoggerFactory.getLogger(FormSqlBuilder.class);
/**
* 要查询的表名
*/
private String tableName;
/**
* 排序的条件
*/
private List<Sort> sorts = new ArrayList<Sort>();
/**
* 单页最大记录数
*/
private int rows;
/**
* 当前到第几页
*/
private int page;
/**
* 查询表单
*/
private Object form;
/**
* 动态传入的ruleScheme,如果有这个,优先使用
* 如果没有就使用 IRuleSchemeGenerator 创建
* 如果没有IRuleSchemeGenerator,就在HbJsonRuleScheme里面找
*/
private Map<String, Rule> ruleScheme;
/**
* ruleScheme生成器
* 如果没有 IRuleSchemeGenerator 就在 HbJsonRuleScheme里面找
*/
private IRuleSchemeGenerator ruleSchemeGenerator;
/**
* json文件里面的 rule scheme (映射规则) 的id
*/
private String ruleId;
public FormSqlBuilder(Object form, String ruleId){
this.form = form;
this.ruleId = ruleId;
}
/**
* 添加排序
* @param sorts
* @return
*/
public FormSqlBuilder addSort(Sort sort){
this.sorts.add(sort);
return this;
}
/**
* 添加翻页
* @param pageCount 单页最大记录数
* @param pageNum 当前到第几页
* @return
*/
public FormSqlBuilder addLimit(int page, int rows){
this.rows = rows;
this.page = page;
return this;
}
/**
* 获取查询规则的MAP queryRule
* @return
*/
private Map<String, Rule> generateRuleScheme() {
Map<String, Rule> ruleScheme;
if(this.ruleSchemeGenerator != null){
//如果有配置ruleSchemeGenerator,就用这个生成
ruleScheme = this.ruleSchemeGenerator.generateRuleScheme(this.form);
}else if(ruleId != null && !"".equals(ruleId)){
//如果有配置 ruleId
ruleScheme = RuleSchemeLoader.get(ruleId);
}else{
//如果全部没有就采用默认的DefaultRuleSchemeGenerator
DefaultRuleSchemeGenerator defaultRuleSchemeGenerator = new DefaultRuleSchemeGenerator();
ruleScheme = defaultRuleSchemeGenerator.generateRuleScheme(this.form);
}
return ruleScheme;
}
/**
* 构建出的PreparedStatement对象专门用于统计行数
* @param session
* @return
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws HqlBuildException
*/
public SqlAndParams buildCount() throws FormIsNullException, SQLException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchFieldException{
if(this.form == null){
throw new FormIsNullException("form cannot be null!");
}
//如果表名没有设置:1.根据注解获取表名 2.根据类名自动猜测
if(tableName == null){
tableName = guessTableName(form);
}
/*
* 1. 生成查询规则
*/
ruleScheme = generateRuleScheme();
/*
* 2. 生成sql语句和参数列表
*/
SqlGenerator sqlGenerator = new SqlGenerator();
SqlAndParams sqlAndParams = sqlGenerator.generateCountSqlAndParams(this.form, ruleScheme,tableName);
String sql = sqlAndParams.getSql();
/**
* 4. 添加Sort条件
*/
sql = SqlGenerator.appendSort(sql,this.form,this.sorts);
/**
* 5. 添加分页条件
*/
sql = SqlGenerator.appendPage(sql,this.page,this.rows);
logger.debug("sql: " + sql);
sqlAndParams.setSql(sql);
return sqlAndParams;
}
/**
* 使用session 构建出query对象
* 最核心的方法
* @param session
* @param isCount
* @return
* @throws SQLException
* @throws FormIsNullException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws HqlBuildException
*/
public SqlAndParams build() throws SQLException, FormIsNullException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchFieldException{
if(this.form == null){
throw new FormIsNullException("form cannot be null!");
}
//如果表名没有设置:1.根据注解获取表名 2.根据类名自动猜测
if(tableName == null){
tableName = guessTableName(form);
}
/*
* 1. 生成查询规则
*/
ruleScheme = generateRuleScheme();
//如果没有设置排序用默认排序
useDefaultSortIfNotSet();
/*
* 2. 生成sql语句和参数列表
*/
SqlGenerator sqlGenerator = new SqlGenerator();
SqlAndParams sqlAndParams = sqlGenerator.generateSqlAndParams(this.form, ruleScheme,tableName);
String sql = sqlAndParams.getSql();
/**
* 4. 添加Sort条件
*/
sql = SqlGenerator.appendSort(sql,this.form,this.sorts);
/**
* 5. 添加分页条件
*/
sql = SqlGenerator.appendPage(sql,this.page,this.rows);
logger.debug("sql: " + sql);
sqlAndParams.setSql(sql);
return sqlAndParams;
}
/**
* 如果没有设置排序字段用默认排序
* @throws NoSuchMethodException
*/
private void useDefaultSortIfNotSet() throws NoSuchMethodException {
if(this.sorts == null || this.sorts.size() == 0){
List<Sort> sortsList = new ArrayList<Sort>();
Field[] fields = form.getClass().getDeclaredFields();
for(Field f:fields){
String getterName = "get" + CamelNameUtils.capitalize(f.getName());
Method getter = form.getClass().getMethod(getterName);
DefaultSort defaultSortAnno = getter.getAnnotation(DefaultSort.class);
if(defaultSortAnno!=null){
boolean asc = defaultSortAnno.asc();
String orderStr = "";
if(asc){
orderStr = "asc";
}else{
orderStr = "desc";
}
Sort sort = new Sort(f.getName(), orderStr);
sortsList.add(sort);
}
}
this.sorts = sortsList;
}
}
/**
* 通过form类猜测表名
* @param form
* @return
*/
private String guessTableName(Object form) {
String tableName = "";
Table tableAnno = form.getClass().getAnnotation(Table.class);
if(tableAnno != null){
tableName = tableAnno.name();
}else{
String className = form.getClass().getName();
String camelName = className.substring(className.lastIndexOf(".")+1);
tableName = CamelNameUtils.camel2underscore(camelName);
}
return tableName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public Object getForm() {
return form;
}
public void setForm(Object form) {
this.form = form;
}
public String getRuleId() {
return ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public IRuleSchemeGenerator getRuleSchemeGenerator() {
return ruleSchemeGenerator;
}
public void setRuleSchemeGenerator(IRuleSchemeGenerator ruleSchemeGenerator) {
this.ruleSchemeGenerator = ruleSchemeGenerator;
}
public Map<String, Rule> getRuleScheme() {
return ruleScheme;
}
public void setRuleScheme(Map<String, Rule> ruleScheme) {
this.ruleScheme = ruleScheme;
}
}
| 24.153846 | 217 | 0.683694 |
68798fd6ce4cf94b039327cc2adc4e0bd56a5af3 | 858 | package com.hribol.bromium.common.browsers;
import com.google.common.collect.ImmutableMap;
import com.hribol.bromium.replay.settings.DriverServiceSupplier;
import org.openqa.selenium.remote.service.DriverService;
import java.io.File;
import java.io.IOException;
/**
* A base class for providing driver services for different browsers
*/
public abstract class DriverServiceSupplierBase implements DriverServiceSupplier {
@Override
public DriverService getDriverService(String pathToDriverExecutable, String screenToUse) throws IOException {
return getBuilder()
.usingDriverExecutable(new File(pathToDriverExecutable))
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY", screenToUse))
.build();
}
protected abstract DriverService.Builder getBuilder();
}
| 34.32 | 113 | 0.744755 |
ac9488e1ed8975c1669becbcff710f85ea667379 | 1,800 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.fielddata.util;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
/**
*/
public class BytesRefArrayRef {
public static final BytesRefArrayRef EMPTY = new BytesRefArrayRef(new BytesRef[0]);
public BytesRef[] values;
public int start;
public int end;
public BytesRefArrayRef(BytesRef[] values) {
this(values, 0, values.length);
}
public BytesRefArrayRef(BytesRef[] values, int length) {
this(values, 0, length);
}
public BytesRefArrayRef(BytesRef[] values, int start, int end) {
this.values = values;
this.start = start;
this.end = end;
}
public void reset(int newLength) {
assert start == 0; // NOTE: senseless if offset != 0
end = 0;
if (values.length < newLength) {
values = new BytesRef[ArrayUtil.oversize(newLength, 32)];
}
}
public int size() {
return end - start;
}
}
| 30 | 87 | 0.683333 |
017094b0bda97796dc0f1465875119aa69550cef | 8,503 | package com.viktor.e_commerce;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.viktor.e_commerce.Util.Util;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import java.util.ArrayList;
import java.util.List;
public class MainFragment extends Fragment implements View.OnClickListener{
private static final String TAG = "MainFragment";
private CheckBox add;
private SwipeRefreshLayout swipeRefreshLayout;
private FloatingActionButton floatingActionButton;
private PopupMenu popupMenu;
private Banner banner;
private List<String> bannerImage;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
//取控件
add = (CheckBox) view.findViewById(R.id.add);
Button home = (Button)view.findViewById(R.id.home);
Button scan = (Button)view.findViewById(R.id.scan);
Button search = (Button)view.findViewById(R.id.search);
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipe_refresh);
floatingActionButton = (FloatingActionButton)view.findViewById(R.id.float_button);
banner = (Banner)view.findViewById(R.id.banner);
//设置数据
bannerImage = new ArrayList<>();
bannerImage.add("http://www.mallproject.cn:8000/media/item/previewImage/%E6%A0%A1%E5%9B%AD%E6%95%85%E4%BA%8B%E9%A6%86-33%E5%95%86%E5%8A%A1%E9%BB%91%E8%89%B2_pLjcEaH.jpg");
bannerImage.add("http://www.mallproject.cn:8000/media/item/previewImage/itemDefault.jpg");
bannerImage.add("http://www.mallproject.cn:8000/media/item/previewImage/%E6%A0%A1%E5%9B%AD%E6%95%85%E4%BA%8B%E9%A6%86-33%E5%95%86%E5%8A%A1%E9%BB%91%E8%89%B2_pLjcEaH.jpg");
banner.setImageLoader(new GlideImageLoader());
banner.setImages(bannerImage);
banner.start();
//监听
home.setOnClickListener(this);
scan.setOnClickListener(this);
search.setOnClickListener(this);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
add.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()){
case R.id.add:
if(isChecked){
// RotateAnimation rotateAnimation = new RotateAnimation(0.0f, 45.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// rotateAnimation.setDuration(500);
// rotateAnimation.setFillAfter(true);
// add.startAnimation(rotateAnimation);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.add_check_box_rotate_start);
animation.setFillAfter(true);
add.startAnimation(animation);
showPopupMenu(add);
}else{
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.add_check_box_rotate_recover);
animation.setFillAfter(true);
add.startAnimation(animation);
}
}
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
Snackbar.make(swipeRefreshLayout, "Refresh", Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.WHITE)
.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
}
}).show();
}
});
}
}).start();
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "TEST", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.home:
if(getActivity() instanceof MainActivity){
((MainActivity)getActivity()).drawerLayout.openDrawer(GravityCompat.START);
}
break;
case R.id.search:
SearchActivity.actionStart(getContext());
break;
case R.id.scan:
if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(), new String[]{ Manifest.permission.CAMERA }, Util.START_QRCODE_SCAN);
}else{
Util.startQRCodeScan(getActivity());
}
break;
}
}
private void showPopupMenu(View view){
if(popupMenu == null){
popupMenu = new PopupMenu(getContext(), view);
popupMenu.getMenuInflater().inflate(R.menu.main_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.settings:
SettingActivity.actionStart(getContext());
break;
}
return true;
}
});
popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu popupMenu) {
add.setChecked(false);
}
});
}
popupMenu.show();
}
@Override
public void onDestroy() {
super.onDestroy();
if(popupMenu != null){
popupMenu.dismiss();
popupMenu = null;
}
}
private String temp(){
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i <= 100; i++){
stringBuilder.append("XXXXXXXXXXXXXXXXXXXXXXXXX");
}
return stringBuilder.toString();
}
}
| 40.490476 | 179 | 0.580736 |
4e3cedf6c615125385411b630ed6e65d4f3b8344 | 1,100 | /*
* 文件名称:CategoryServiceImpl.java
* 系统名称:[系统名称]
* 模块名称:[模块名称]
* 软件版权:Copyright (c) 2011-2018, liming20110711@163.com All Rights Reserved.
* 功能说明:[请在此处输入功能说明]
* 开发人员:Rushing0711
* 创建日期:20180726 07:39
* 修改记录:
* <Version> <DateSerial> <Author> <Description>
* 1.0.0 20180726-01 Rushing0711 M201807260739 新建文件
********************************************************************************/
package com.coding.product.service.impl;
import com.coding.product.dataobject.ProductCategory;
import com.coding.product.repository.ProductCategoryRepository;
import com.coding.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired private ProductCategoryRepository repository;
@Override
public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) {
return repository.findByCategoryTypeIn(categoryTypeList);
}
}
| 33.333333 | 87 | 0.697273 |
486cf4b2a4e6400b7d0a20c2262197ac0fb856fa | 207 | package tk.jcseahawks.ocja.day_twenty_one.chapterthree.exercise;
class One {
//Create a float number type of any value, and assign it to a short using casting
//
float f = 234.56F;
short s = (short)f;
}
| 20.7 | 81 | 0.7343 |
c7db2e62fd939d6fb5f757e141097d882553405b | 1,803 | package es.uned.lsi.eped.DataStructures;
/* Representa un multiconjunto, que es un contenedor que *
* permite almacenar elementos de los que puede haber múltiples *
* instancias dentro del multiconjunto. */
public interface MultiSetIF<E> extends ContainerIF<E> {
/* Añade varias instancias de un elemento al multiconjunto *
* @pre: n > 0 && premult = multiplicity(e) *
* @post: multiplicity(e) = premult + n */
public void addMultiple (E e, int n);
/* Elimina varias instancias de un elemento del *
* multiconjunto *
* @pre: 0<n<= multiplicity(e) && premult = multiplicity(e) *
* @post: multiplicity(e) = premult - n */
public void removeMultiple (E e, int n);
/* Devuelve la multiplicidad de un elemento dentro del *
* multiconjunto. *
* @return: multiplicidad de e (0 si no está contenido) */
public int multiplicity (E e);
/* Realiza la unión del multiconjunto llamante con el *
* parámetro */
public void union (MultiSetIF<E> s);
/* Realiza la intersección del multiconjunto llamante con *
* el parámetro */
public void intersection (MultiSetIF<E> s);
/* Realiza la diferencia del multiconjunto llamante con el *
* parámetro (los elementos que están en el llamante pero *
* no en el parámetro */
public void difference (MultiSetIF<E> s);
/* Devuelve cierto sii el parámetro es un submulticonjunto *
* del llamante */
public boolean isSubMultiSet (MultiSetIF<E> s);
}
| 43.97561 | 66 | 0.557959 |
840a707ea51cabe2620bb7c642d830239d074645 | 8,831 | package com.stx.xhb.enjoylife.ui.activity;
import android.Manifest;
import android.app.WallpaperManager;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.stx.xhb.enjoylife.R;
import com.stx.xhb.enjoylife.ui.adapter.PhotoViewPagerAdapter;
import com.stx.xhb.enjoylife.utils.ShareUtils;
import com.stx.xhb.enjoylife.utils.ToastUtil;
import com.xhb.core.base.BaseActivity;
import com.xhb.core.util.RxImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
public class PhotoViewActivity extends BaseActivity {
public static final int PERMISS_REQUEST_CODE = 0x001;
@BindView(R.id.photo_viewpager)
ViewPager photoViewpager;
@BindView(R.id.tv_indicator)
TextView mTvIndicator;
@BindView(R.id.toolbar)
Toolbar toolbar;
private ArrayList<String> imageList;
private int mPos;
public static final String TRANSIT_PIC = "transit_img";
private String saveImgUrl = "";
@Override
protected int getLayoutResource() {
return R.layout.activity_photo_view;
}
@Override
protected void onInitialization(Bundle bundle) {
initView();
photoViewpager.setPageMargin((int) (getResources().getDisplayMetrics().density * 15));
photoViewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
saveImgUrl = imageList.get(photoViewpager.getCurrentItem());
mTvIndicator.setText(String.valueOf((photoViewpager.getCurrentItem() + 1) + "/" + imageList.size()));
}
});
ViewCompat.setTransitionName(photoViewpager, PhotoViewActivity.TRANSIT_PIC);
initData();
setAdapter();
}
private void initView() {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
private void initData() {
imageList = getIntent().getStringArrayListExtra("image");
mPos = getIntent().getIntExtra("pos", 0);
mTvIndicator.setText(String.valueOf((mPos + 1) + "/" + imageList.size()));
}
private void setAdapter() {
PhotoViewPagerAdapter adapter = new PhotoViewPagerAdapter(this, imageList);
photoViewpager.setAdapter(adapter);
photoViewpager.setCurrentItem(mPos);
adapter.setOnClickListener(new PhotoViewPagerAdapter.onImageLayoutListener() {
@Override
public void setOnImageOnClik() {
onBackPressed();
}
@Override
public void setLongClick(String url) {
new AlertDialog.Builder(PhotoViewActivity.this)
.setMessage(getString(R.string.ask_saving_picture))
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})) {
saveImage();
} else {
requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISS_REQUEST_CODE);
}
dialog.dismiss();
}
})
.show();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (PERMISS_REQUEST_CODE == requestCode) {
if (checkPermissions(permissions)) {
saveImage();
} else {
showTipsDialog();
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_more, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
if (checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})) {
saveImage();
} else {
requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISS_REQUEST_CODE);
}
return true;
case R.id.menu_setting_picture:
setWallpaper();
return true;
case R.id.menu_share:
Subscription subscribe = RxImage.saveImageAndGetPathObservable(this, saveImgUrl)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Uri>() {
@Override
public void call(Uri uri) {
ShareUtils.shareImage(PhotoViewActivity.this, uri, getString(R.string.share_image_to));
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
ToastUtil.show(throwable.getMessage());
}
});
addSubscription(subscribe);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* 保存图片
*/
private void saveImage() {
Subscription subscribe = RxImage.saveImageAndGetPathObservable(this, saveImgUrl)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Uri>() {
@Override
public void call(Uri uri) {
File appDir = new File(Environment.getExternalStorageDirectory(), "EnjoyLife");
String msg = String.format(getString(R.string.picture_has_save_to),
appDir.getAbsolutePath());
ToastUtil.show(msg);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
ToastUtil.show(getString(R.string.string_img_save_failed));
}
});
addSubscription(subscribe);
}
private void setWallpaper() {
RxImage.setWallPaper(this,saveImgUrl)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
ToastUtil.show("设置壁纸成功");
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
ToastUtil.show("设置壁纸失败");
}
});
}
}
| 39.075221 | 177 | 0.581927 |
6fe154b0367468823b35808870ca47a4046a729b | 2,024 | package com.goebuy.biz.event;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.goebuy.biz.AbstractBiz;
import com.goebuy.entity.event.Tag;
import com.goebuy.service.event.TagService;
@Service
public class TagBiz extends AbstractBiz<Tag, Integer>{
@Autowired
private TagService service;
@Override
public Tag save(Tag addObj) {
return service.save(addObj);
}
@Override
public Tag saveAndFlush(Tag addObj) {
return service.saveAndFlush(addObj);
}
@Override
public List<Tag> save(Iterable<Tag> addObjs) {
return service.save(addObjs);
}
@Override
public List<Tag> findAll() {
return service.findAll();
}
@Override
public List<Tag> findAll(Sort sort) {
return service.findAll(sort);
}
@Override
public List<Tag> findAll(Pageable pageable) {
Page<Tag> page= service.findAll(pageable);
if(page!=null) {
return page.getContent();
}
return null;
}
@Override
public void deleteById(Integer id) {
service.delete(id);
}
@Override
public void deleteByObj(Tag o) {
service.delete(o);
}
@Override
public Tag findById(Integer id) {
return service.findOne(id);
}
@Override
public List<Tag> findByNameMatch(String name) {
return service.findByNameMatch(name);
}
@Override
public Tag findByName(String name) {
return service.findByName(name);
}
@Override
public void deleteAllInBatch() {
service.deleteAllInBatch();
}
@Override
public void deleteInBatch(Iterable<Tag> delObjs) {
service.deleteInBatch(delObjs);
}
@Override
public List<Tag> findByIds(Iterable<Integer> ids) {
return service.findAll(ids);
}
@Override
public void flush() {
service.flush();
}
@Override
public long count() {
return service.count();
}
@Override
public boolean exists(int id) {
return service.exists(id);
}
}
| 18.234234 | 62 | 0.731225 |
9d52b32855793e2d766e6a8fb01cb0972b079a90 | 991 | /**
* @author demo
* 二分查找算法实践
*/
public class BinarySearch {
public static void main(String[] args) {
System.out.println( binarySearch());
int a = 5,b=6,c=2;
int z = (a*b-c)/a;
System.out.println(z);
}
private static String binarySearch() {
int numbers[] = {1,2,3,4,5,6,7,8,9};
int target = 3;
int length = numbers.length;
int start = 0;
int end = length - 1;
int midId = -1;
if (target < numbers[start] || target > numbers[end]){
return "target不在范围内";
}else{
while (start <= end){
midId =(start+end)/2;
if(target == numbers[midId]){
return Integer.toString(target);
}
if (numbers[midId] > target){
end = midId-1;
}else {
start = midId +1;
}
}
}
return "不存在值";
}
}
| 24.775 | 62 | 0.434914 |
b8c3417242a140e8d1c3fb244e73d1de6ba1c734 | 1,711 | package com.icaroabreu.realmmigration.view;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.icaroabreu.realmmigration.R;
import com.icaroabreu.realmmigration.model.Person;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by Icaro Abreu on 05/05/2015.
*/
public class PersonAdapter extends ArrayAdapter<Person> {
private List<Person> persons;
private Activity activity;
public PersonAdapter(Activity activity, List<Person> objects) {
super(activity, 0, objects);
this.persons = objects;
this.activity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
Person person = persons.get(position);
if(convertView != null)
{
viewHolder = (ViewHolder) convertView.getTag();
}
else
{
convertView = ((LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.list_person_item, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
viewHolder.name.setText(person.getFirst_name() + " " + person.getLast_name());
return convertView;
}
static class ViewHolder {
@InjectView(R.id.person_name)
TextView name;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
}
| 24.797101 | 104 | 0.671537 |
c6a4211d4217f1ad254c97faab7e111cdaa8ce70 | 198 | package com.ggj.java.java.firstdemo.testkafakaperformance.testone;
/**
* @author:gaoguangjin
* @date 2016/7/4 17:02
*/
public class TopicOne {
public static String TOPIC="performance12";
}
| 19.8 | 66 | 0.727273 |
cdeea50499c62c7d4f3e06b5eae92f2381e41e51 | 4,314 | package cn.com.allunion.common.handler;
import org.springframework.core.Conventions;
import org.springframework.util.Assert;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 请求封装对象
* @author yang.jie
* @email yang.jie@all-union.com.cn
* @date 2016/5/12.
* @copyright http://www.all-union.com.cn/
*/
public class Request extends LinkedHashMap<String, Object> {
/**
* 请求类型标识
*/
private String mark ;
/**
* Construct a new, empty {@code Request}.
*/
public Request() {
}
/**
* Construct a new {@code Request} containing the supplied attribute
* under the supplied name.
* @see #addAttribute(String, Object)
*/
public Request(String attributeName, Object attributeValue) {
addAttribute(attributeName, attributeValue);
}
/**
* Construct a new {@code Request} containing the supplied attribute.
* Uses attribute name generation to generate the key for the supplied model
* object.
* @see #addAttribute(Object)
*/
public Request(Object attributeValue) {
addAttribute(attributeValue);
}
/**
* Add the supplied attribute under the supplied name.
* @param attributeName the name of the model attribute (never {@code null})
* @param attributeValue the model attribute value (can be {@code null})
*/
public Request addAttribute(String attributeName, Object attributeValue) {
Assert.notNull(attributeName, "Model attribute name must not be null");
put(attributeName, attributeValue);
return this;
}
/**
* Add the supplied attribute to this {@code Map} using a
* {@link Conventions#getVariableName generated name}.
* <p><emphasis>Note: Empty {@link Collection Collections} are not added to
* the model when using this method because we cannot correctly determine
* the true convention name. View code should check for {@code null} rather
* than for empty collections as is already done by JSTL tags.</emphasis>
* @param attributeValue the model attribute value (never {@code null})
*/
public Request addAttribute(Object attributeValue) {
Assert.notNull(attributeValue, "Model object must not be null");
if (attributeValue instanceof Collection && ((Collection<?>) attributeValue).isEmpty()) {
return this;
}
return addAttribute(Conventions.getVariableName(attributeValue), attributeValue);
}
/**
* Copy all attributes in the supplied {@code Collection} into this
* {@code Map}, using attribute name generation for each element.
* @see #addAttribute(Object)
*/
public Request addAllAttributes(Collection<?> attributeValues) {
if (attributeValues != null) {
for (Object attributeValue : attributeValues) {
addAttribute(attributeValue);
}
}
return this;
}
/**
* Copy all attributes in the supplied {@code Map} into this {@code Map}.
* @see #addAttribute(String, Object)
*/
public Request addAllAttributes(Map<String, ?> attributes) {
if (attributes != null) {
putAll(attributes);
}
return this;
}
/**
* Copy all attributes in the supplied {@code Map} into this {@code Map},
* with existing objects of the same name taking precedence (i.e. not getting
* replaced).
*/
public Request mergeAttributes(Map<String, ?> attributes) {
if (attributes != null) {
for (Map.Entry<String, ?> entry : attributes.entrySet()) {
String key = entry.getKey();
if (!containsKey(key)) {
put(key, entry.getValue());
}
}
}
return this;
}
/**
* Does this model contain an attribute of the given name?
* @param attributeName the name of the model attribute (never {@code null})
* @return whether this model contains a corresponding attribute
*/
public boolean containsAttribute(String attributeName) {
return containsKey(attributeName);
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
}
| 31.26087 | 97 | 0.631664 |
088a2ce2d492990f7559ef1c109b703461ce3d74 | 1,636 | package io.github.morichan.fescue.feature.value.expression;
import io.github.morichan.fescue.feature.value.expression.symbol.Symbol;
/**
* <p> 2項式クラス </p>
*
* <p>
* 使い方を次に示します。
* </p>
*
* <pre>
* {@code
* Binomial binomial = new Binomial("*",
* new OneIdentifier(1),
* new ExpressionWithParen(new Binomial("+", new OneIdentifier(2), new OneIdentifier(3))));
*
* System.out.println(binomial); // "1 * (2 + 3)"
* }
* </pre>
*/
public class Binomial implements Expression {
private Expression first;
private Expression second;
private Symbol symbol;
private boolean isHadSpaceBothSides;
/**
* <p> 2項式コンストラクタ </p>
*
* <p>
* 式における2項の{@link Expression}インスタンスと、その演算子を文字列で設定します。
* </p>
*
* @param symbolText 2項式の演算子
* @param first 2項式の最初の式
* @param second 2項式の次の式
*/
public Binomial(String symbolText, Expression first, Expression second) {
if (symbolText == null || first == null || second == null) throw new IllegalArgumentException();
this.first = first;
this.second = second;
this.symbol = Symbol.choose(symbolText);
symbol.is(symbolText);
isHadSpaceBothSides = this.symbol.isHadSpaceBothSides();
}
/**
* <p> 2項式の文字列を取得します。 </p>
*
* @return 2項式の文字列<br>{@code null}および{@code ""}なし
*/
@Override
public String toString() {
if (isHadSpaceBothSides) return first + " " + symbol + " " + second;
return first + symbol.toString() + second;
}
}
| 27.728814 | 105 | 0.573961 |
6dc2c711a072c2ffa34c43e140ba5c4d1fbff4a3 | 1,753 | /*******************************************************************************
* Copyright 2016-2017 Dell Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* @microservice: device-mqtt
* @author: Jim White, Dell
* @version: 1.0.0
*******************************************************************************/
package org.edgexfoundry.domain;
import org.edgexfoundry.support.logging.client.EdgeXLogger;
import org.edgexfoundry.support.logging.client.EdgeXLoggerFactory;
import com.google.gson.Gson;
public class MqttAttribute {
private static final EdgeXLogger logger = EdgeXLoggerFactory.getEdgeXLogger(MqttAttribute.class);
// Replace these attributes with the MQTT
// specific metadata needed by the MQTT Driver
private String name;
public MqttAttribute(Object attributes) {
try {
Gson gson = new Gson();
String jsonString = gson.toJson(attributes);
MqttAttribute thisObject = gson.fromJson(jsonString, this.getClass());
this.setName(thisObject.getName());
} catch (Exception e) {
logger.error("Cannot Construct MqttAttribute: " + e.getMessage());
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 29.216667 | 100 | 0.658871 |
4258ef642963fc5670d96538c4b6eac697d12d8a | 1,639 | package gq.netin.auth.version.rewrite;
import java.nio.charset.Charset;
import java.util.UUID;
import com.mojang.authlib.GameProfile;
import gq.netin.auth.util.Messages;
import gq.netin.auth.util.Reflection;
import gq.netin.auth.util.Util;
import net.minecraft.server.v1_8_R1.EntityPlayer;
import net.minecraft.server.v1_8_R1.LoginListener;
import net.minecraft.server.v1_8_R1.MinecraftServer;
import net.minecraft.server.v1_8_R1.NetworkManager;
import net.minecraft.server.v1_8_R1.PacketLoginOutSuccess;
/**
*
* @author netindev
*
*/
public class v1_8_R1 extends LoginListener {
private static final MinecraftServer SERVER = MinecraftServer.getServer();
public v1_8_R1(NetworkManager networkManager, String player) {
super(v1_8_R1.SERVER, networkManager);
if (this.networkManager == null) {
Util.info(Messages.REFUSED_PLAYER_CONNECTION.replace("<player>", player));
return;
}
Reflection.setField("k", this, this.networkManager, 0);
Reflection.setField("i",
new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + player).getBytes(Charset.forName("UTF-8"))),
player),
this, 1);
}
@Override
public void b() {
this.c();
}
@Override
public void c() {
GameProfile validProfile = (GameProfile) Reflection.getField("i", this, 1);
EntityPlayer attemptLogin = v1_8_R1.SERVER.getPlayerList().attemptLogin(this, validProfile, this.hostname);
if (attemptLogin != null) {
this.networkManager.handle(new PacketLoginOutSuccess(validProfile));
v1_8_R1.SERVER.getPlayerList().a(this.networkManager,
v1_8_R1.SERVER.getPlayerList().processLogin(validProfile, attemptLogin));
}
}
}
| 29.267857 | 109 | 0.758389 |
93be2bb3579af64583ab7aeffa9d6049ba90c47d | 6,104 | package uk.ac.liv.mzidlib.util;
/**
* This class contains some utility methods related to the Controlled Vocabulary
* (CV) at
*
* http://psidev.cvs.sourceforge.net/viewvc/\*checkout*\/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo
*
* @author Pieter
*
*/
//CORRECT URL : see http://psidev.cvs.sourceforge.net/viewvc/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo
public class CVUtils {
/**
* Tries to infer the correct CV term id and name based on the extension of
* the given databaseFileName. It falls back to ["MS:1001348","FASTA
* format"] if it cannot infer the format based on the extension.
*
* @param databaseFileName : the file reported as the protein database where
* the ms/ms search was done.
*
* @return : returns an array with 2 strings, the first one being the CV
* term id and the second one the name.
*/
public static String[] getDatabaseFileFormat(String databaseFileName) {
//The default:
//The sequence database was stored in the FASTA format
String databaseFileFormatID = "MS:1001348";
String databaseFileFormatName = "FASTA format";
if (databaseFileName.toLowerCase().contains(".asn1")) {
//The sequence database was stored in the Abstract Syntax Notation 1 format.
databaseFileFormatID = "MS:1001349";
databaseFileFormatName = "ASN.1";
} else if (databaseFileName.toLowerCase().contains("formatdb")) {//TODO: not sure what the extension would be here...
//The sequence database was stored in the NCBI formatdb (*.p*) format
databaseFileFormatID = "MS:1001350";
databaseFileFormatName = "NCBI *.p*";
} else if (databaseFileName.toLowerCase().contains(".aln")) {
//ClustalW ALN (multiple alignment) format
databaseFileFormatID = "MS:1001351";
databaseFileFormatName = "clustal aln";
} else if (databaseFileName.toLowerCase().contains(".embl")) {
//ClustalW ALN (multiple alignment) format
databaseFileFormatID = "MS:1001352";
databaseFileFormatName = "embl em";
} else if (databaseFileName.toLowerCase().contains(".pir")) {
//The NBRF PIR was used as format.
databaseFileFormatID = "MS:1001353";
databaseFileFormatName = "NBRF PIR";
}
String[] result = {databaseFileFormatID, databaseFileFormatName};
return result;
}
/**
* Tries to infer the correct CV term id and name based on the extension of
* the given spectrumFileName. It falls back to the generic
* ["MS:1000560","mass spectrometer file format"] if it cannot infer the
* format based on the extension.
*
* @param spectrumFileName : the file reported as the ms spectra file that
* contained the ms/ms spectra.
*
* @return : returns an array with 2 strings, the first one being the CV
* term id and the second one the name.
*/
public static String[] getMassSpecFileFormatID(String spectrumFileName) {
//the default:
//TODO check if: MS:1000560 --> would this be Ok as standard? Are there rules about what can be in the tags? Or should
//we leave them empty when we don't have the information?
String massSpecFileFormatID = "MS:1000560";
String massSpecFileFormatName = "mass spectrometer file format";
if (spectrumFileName.toLowerCase().contains(".mzml")) {
//"Proteomics Standards Inititative mzML file format."
massSpecFileFormatID = "MS:1000584";
massSpecFileFormatName = "mzML file";
} else if (spectrumFileName.toLowerCase().contains(".dta")) {//TODO not sure about the extension
//Sequest DTA file format
massSpecFileFormatID = "MS:1000613";
massSpecFileFormatName = "DTA file";
} else if (spectrumFileName.toLowerCase().contains(".mzxml")) {
//Institute of Systems Biology mzXML file format.
massSpecFileFormatID = "MS:1000566";
massSpecFileFormatName = "ISB mzXML file";
} else if (spectrumFileName.toLowerCase().contains(".mzdata")) {
//Proteomics Standards Inititative mzData file format
massSpecFileFormatID = "MS:1000564";
massSpecFileFormatName = "PSI mzData file";
} else if (spectrumFileName.toLowerCase().contains(".mgf")) {
//Mascot MGF file
massSpecFileFormatID = "MS:1001062";
massSpecFileFormatName = "Mascot MGF format";
} else if (spectrumFileName.toLowerCase().contains(".mz5")) {
//mz5 file format, modeled after mzML
massSpecFileFormatID = "MS:1001881";
massSpecFileFormatName = "mz5 file";
}
//TODO - other important formats (but we have to figure out what are their extensions first:
/*
id: MS:1001463
name: Phenyx XML format
is_a: MS:1000560 ! mass spectrometer file format
is_a: MS:1001040 ! intermediate analysis format
id: MS:1001509
name: Agilent MassHunter file
def: "A data file found in an Agilent MassHunter directory which contains raw data acquired by an Agilent mass spectrometer." [PSI:PI]
is_a: MS:1000560 ! mass spectrometer file format
id: MS:1001527
name: Proteinscape spectra
def: "Spectra from Bruker/Protagen Proteinscape database." [PSI:MS]
is_a: MS:1000560 ! mass spectrometer file format
[Term]
id: MS:1000563
name: Thermo RAW file
def: "Thermo Scientific RAW file format." [PSI:MS]
is_a: MS:1000560 ! mass spectrometer file format
[Term]
id: MS:1000565
name: Micromass PKL file
def: "Micromass PKL file format." [PSI:MS]
is_a: MS:1000560 ! mass spectrometer file format
*/
String[] result = {massSpecFileFormatID, massSpecFileFormatName};
return result;
}
}
| 44.882353 | 143 | 0.639089 |
e36e62ee6b031a25673ed1b7b1926ec93389cfa4 | 6,300 | package com.capitalone.dashboard.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.capitalone.dashboard.collector.MetricsProcessorConfig;
import com.capitalone.dashboard.exec.model.MTTR;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
@RunWith(MockitoJUnitRunner.class)
public class ProductionIncidentsDAOTest {
@InjectMocks
private ProductionIncidentsDAO productionIncidentsDAO;
@Mock
private MetricsProcessorConfig metricsProcessorConfig;
@Mock
private MongoTemplate mongoTemplate;
@Mock
private MongoClient mongoClient;
@Mock
private DBCollection mongoCollection;
@Mock
private MongoOperations mongoOperations;
@Test
public void testGetMongoClient() throws Exception {
Mockito.when(metricsProcessorConfig.mongo()).thenReturn(mongoClient);
productionIncidentsDAO.getMongoClient();
}
@Test
public void testGetMongoClient_1() throws Exception {
Mockito.when(metricsProcessorConfig.mongo()).thenThrow(new Exception());
productionIncidentsDAO.getMongoClient();
}
@Test
public void testGetProductionIncidentsDataByAppId() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenReturn(mongoTemplate);
productionIncidentsDAO.getProductionIncidentsDataByAppId("B6LV", mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetProductionIncidentsDataByAppId_1() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenThrow(new Exception());
productionIncidentsDAO.getProductionIncidentsDataByAppId("B6LV", mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetAppIdList() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenReturn(mongoTemplate);
Mockito.when(mongoTemplate.getCollection(Mockito.anyString())).thenReturn(mongoCollection);
productionIncidentsDAO.getAppIdList(mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetAppIdList_1() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenThrow(new Exception());
productionIncidentsDAO.getAppIdList(mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetEntireAppList() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenReturn(mongoTemplate);
Mockito.when(mongoTemplate.getCollection(Mockito.anyString())).thenReturn(mongoCollection);
productionIncidentsDAO.getEntireAppList(mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetEntireAppList_1() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenThrow(new Exception());
productionIncidentsDAO.getEntireAppList(mongoClient);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void getProductionIncidentsDataByAppIdByRegex_1() {
try {
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenThrow(new Exception());
productionIncidentsDAO.getProductionIncidentsDataByAppIdByRegex("D40V", mongoClient, "2018-05-05");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void getProductionIncidentsDataByAppIdByRegex_2() throws Exception {
Query basicQuery = new Query();
basicQuery.addCriteria(Criteria.where("appId").is("D40V"));
basicQuery.addCriteria(Criteria.where("eventStartDT").gte("2018-05-05"));
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(Mockito.any(MongoClient.class)))
.thenReturn(mongoTemplate);
productionIncidentsDAO.getProductionIncidentsDataByAppIdByRegex("D40V", mongoClient, "2018-05-05");
}
@Test
public void getProductionIncidentsDataByAppId() throws Exception {
Mockito.when(metricsProcessorConfig.mongo()).thenReturn(mongoClient);
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(mongoClient)).thenReturn(mongoTemplate);
Query basicQuery = new Query();
basicQuery.addCriteria(Criteria.where("appId").is("D40V"));
basicQuery.addCriteria(Criteria.where("eventStartDT").gte("2018-05-19"));
productionIncidentsDAO.getMTBFDataforApp("D40V");
}
@Test
public void getMTTRDetails() throws Exception {
List<String> productionEvents = new ArrayList<>();
productionEvents.add("CRISIS123");
Query basicQuery = new Query();
basicQuery.addCriteria(Criteria.where("crisisId").in(productionEvents));
Mockito.when(mongoTemplate.find(basicQuery, MTTR.class)).thenReturn(getMTTRLists());
Mockito.when(metricsProcessorConfig.mongo()).thenReturn(mongoClient);
Mockito.when(metricsProcessorConfig.metricsProcessorTemplate(mongoClient)).thenReturn(mongoTemplate);
productionIncidentsDAO.getMTTRDetails(productionEvents);
}
private List<MTTR> getMTTRLists() {
MTTR mttr = new MTTR();
mttr.setAppId("B6LV");
mttr.setCrisisId("12341234");
mttr.setCrisisLevel("SEV2");
mttr.setEventStartDT("asdfasdfasdfaasdf");
mttr.setItduration(44);
mttr.setOwningEntity("some entity");
mttr.setServiceLevel("some level");
return Arrays.asList(mttr);
}
@Test
public void testGetMTTRDetails_1() throws Exception {
List<String> productionEvents = new ArrayList<>();
productionEvents.add("CRISIS123");
Mockito.when(metricsProcessorConfig.mongo()).thenThrow(new Exception());
productionIncidentsDAO.getMTTRDetails(productionEvents);
}
@Test
public void testGetProductionIncidentsDataByAppId_3() throws Exception {
Mockito.when(metricsProcessorConfig.mongo()).thenThrow(new Exception());
productionIncidentsDAO.getMTBFDataforApp("D40V");
}
}
| 31.979695 | 103 | 0.781905 |
2dd6745d50ebe23ac1b16c57d05d1646c938748c | 2,254 | package com.example.android.bakingapp.View;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.bakingapp.Model.StepsItem;
import com.example.android.bakingapp.R;
import java.util.List;
public class RecipeStepAdapter extends RecyclerView.Adapter<RecipeStepAdapter.RecipeViewHolder> {
private static final String TAG = RecipeStepAdapter.class.getName();
private final int mNumberItems;
private final List<StepsItem> steps;
private final Context context;
private OnStepClickListener mClickListener;
public RecipeStepAdapter(List<StepsItem> steps, Context context) {
this.steps = steps;
this.context = context;
this.mNumberItems = steps.size();
this.mClickListener = (OnStepClickListener) context;
}
interface OnStepClickListener {
void onClick(StepsItem item, int currStep);
}
@NonNull
@Override
public RecipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater
.from(context)
.inflate(R.layout.recipe_detail_item, parent, false);
return new RecipeViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecipeStepAdapter.RecipeViewHolder holder, int position) {
holder.stepTextView.setText(steps.get(position).getShortDescription());
}
@Override
public int getItemCount() {
return mNumberItems;
}
class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
final TextView stepTextView;
RecipeViewHolder(View itemView) {
super(itemView);
stepTextView = itemView.findViewById(R.id.detail_step_tv);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition();
mClickListener.onClick(steps.get(position), position);
}
}
} | 25.908046 | 100 | 0.700976 |
8fcc2a99b941e30e267afed620b31a98bb1e8045 | 1,076 | package cn.asany.his.demo.graphql;
import cn.asany.his.demo.bean.User;
import cn.asany.his.demo.graphql.inputs.UserFilter;
import cn.asany.his.demo.graphql.types.UserConnection;
import cn.asany.his.demo.service.UserService;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.jfantasy.framework.dao.OrderBy;
import org.jfantasy.framework.dao.Pager;
import org.jfantasy.framework.util.common.ObjectUtil;
import org.jfantasy.graphql.util.Kit;
import org.springframework.stereotype.Component;
/** @author limaofeng */
@Component
public class UserGraphQLQueryResolver implements GraphQLQueryResolver {
private final UserService userService;
public UserGraphQLQueryResolver(UserService userService) {
this.userService = userService;
}
public UserConnection users(UserFilter filter, int page, int pageSize, OrderBy orderBy) {
Pager<User> pager = new Pager<>(page, pageSize, orderBy);
filter = ObjectUtil.defaultValue(filter, new UserFilter());
return Kit.connection(userService.findPager(pager, filter.build()), UserConnection.class);
}
}
| 35.866667 | 94 | 0.795539 |
40a7fe10eca74c01a1765fefdde4f326e630c7b0 | 454 | package com.kodilla.hibernate.task.dao;
import com.kodilla.hibernate.task.TaskFinancialDetails;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
@Repository
public interface TaskFinancialDetailsDao extends CrudRepository<TaskFinancialDetails, Integer> {
List<TaskFinancialDetails> findByPaid(boolean paid);
}
| 30.266667 | 96 | 0.848018 |
c15223441545173823a00c8e174a044bbb7ccc49 | 7,985 | package org.rcsb.cif.api.generated;
import org.rcsb.cif.model.*;
import javax.annotation.Generated;
import java.util.Map;
/**
* Data items in the PDBX_VALIDATE_SYMM_CONTACT category list the
* atoms within the entry that are in close contact with regard
* the distances expected from either covalent bonding or closest
* approach by van der Waals contacts. Contacts with
* for symmetry related contacts are considered.
* For those contacts not involving hydrogen a limit of
* 2.2 Angstroms is used. For contacts involving a hydrogen atom
* a cutoff of 1.6Angstrom is used.
*/
@Generated("org.rcsb.cif.generator.SchemaGenerator")
public class PdbxValidateSymmContact extends BaseCategory {
public PdbxValidateSymmContact(String name, Map<String, Column> columns) {
super(name, columns);
}
public PdbxValidateSymmContact(String name, int rowCount, Object[] encodedColumns) {
super(name, rowCount, encodedColumns);
}
public PdbxValidateSymmContact(String name) {
super(name);
}
/**
* The value of _pdbx_validate_symm_contact.id must uniquely identify
* each item in the PDBX_VALIDATE_SYMM_CONTACT list.
* This is an integer serial number.
* @return IntColumn
*/
public IntColumn getId() {
return (IntColumn) (isText ? textFields.computeIfAbsent("id", IntColumn::new) :
getBinaryColumn("id"));
}
/**
* The model number for the given angle
* @return IntColumn
*/
public IntColumn getPDBModelNum() {
return (IntColumn) (isText ? textFields.computeIfAbsent("PDB_model_num", IntColumn::new) :
getBinaryColumn("PDB_model_num"));
}
/**
* Part of the identifier of the first of the two atom sites that
* define the close contact.
*
* This data item is a pointer to _atom_site.auth_asym_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthAsymId1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_asym_id_1", StrColumn::new) :
getBinaryColumn("auth_asym_id_1"));
}
/**
* Part of the identifier of the first of the two atom sites that
* define the close contact.
*
* This data item is a pointer to _atom_site.auth_atom_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthAtomId1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_atom_id_1", StrColumn::new) :
getBinaryColumn("auth_atom_id_1"));
}
/**
* Part of the identifier of the first of the two atom sites that
* define the close contact.
*
* This data item is a pointer to _atom_site.auth_comp_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthCompId1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_comp_id_1", StrColumn::new) :
getBinaryColumn("auth_comp_id_1"));
}
/**
* Part of the identifier of the first of the two atom sites that
* define the close contact.
*
* This data item is a pointer to _atom_site.auth_seq_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthSeqId1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_seq_id_1", StrColumn::new) :
getBinaryColumn("auth_seq_id_1"));
}
/**
* Part of the identifier of the second of the two atom sites
* that define the close contact.
*
* This data item is a pointer to _atom_site.auth_atom_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthAtomId2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_atom_id_2", StrColumn::new) :
getBinaryColumn("auth_atom_id_2"));
}
/**
* Part of the identifier of the second of the two atom sites
* that define the close contact.
*
* This data item is a pointer to _atom_site.auth_asym_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthAsymId2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_asym_id_2", StrColumn::new) :
getBinaryColumn("auth_asym_id_2"));
}
/**
* Part of the identifier of the second of the two atom sites
* that define the close contact.
*
* This data item is a pointer to _atom_site.auth_comp_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthCompId2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_comp_id_2", StrColumn::new) :
getBinaryColumn("auth_comp_id_2"));
}
/**
* Part of the identifier of the second of the two atom sites
* that define the close contact.
*
* This data item is a pointer to _atom_site.auth_seq_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getAuthSeqId2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("auth_seq_id_2", StrColumn::new) :
getBinaryColumn("auth_seq_id_2"));
}
/**
* Optional identifier of the first of the two atom sites that
* define the close contact.
* @return StrColumn
*/
public StrColumn getPDBInsCode1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("PDB_ins_code_1", StrColumn::new) :
getBinaryColumn("PDB_ins_code_1"));
}
/**
* Optional identifier of the second of the two atom sites that
* define the close contact.
* @return StrColumn
*/
public StrColumn getPDBInsCode2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("PDB_ins_code_2", StrColumn::new) :
getBinaryColumn("PDB_ins_code_2"));
}
/**
* An optional identifier of the first of the two atoms that
* define the close contact.
*
* This data item is a pointer to _atom_site.label_alt.id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getLabelAltId1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("label_alt_id_1", StrColumn::new) :
getBinaryColumn("label_alt_id_1"));
}
/**
* An optional identifier of the second of the two atoms that
* define the close contact.
*
* This data item is a pointer to _atom_site.label_alt_id in the
* ATOM_SITE category.
* @return StrColumn
*/
public StrColumn getLabelAltId2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("label_alt_id_2", StrColumn::new) :
getBinaryColumn("label_alt_id_2"));
}
/**
* The symmetry of the first of the two atoms define the close contact.
* Symmetry defined in ORTEP style of 555 equal to unit cell with translations
* +-1 from 555 as 000
* @return StrColumn
*/
public StrColumn getSiteSymmetry1() {
return (StrColumn) (isText ? textFields.computeIfAbsent("site_symmetry_1", StrColumn::new) :
getBinaryColumn("site_symmetry_1"));
}
/**
* The symmetry of the second of the two atoms define the close contact.
* Symmetry defined in ORTEP style of 555 equal to unit cell with translations
* +-1 from 555 as 000
* @return StrColumn
*/
public StrColumn getSiteSymmetry2() {
return (StrColumn) (isText ? textFields.computeIfAbsent("site_symmetry_2", StrColumn::new) :
getBinaryColumn("site_symmetry_2"));
}
/**
* The value of the close contact for the two atoms defined.
* @return FloatColumn
*/
public FloatColumn getDist() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("dist", FloatColumn::new) :
getBinaryColumn("dist"));
}
}
| 34.270386 | 100 | 0.649343 |
4c0affe1d51a9355e03bcb28661eb98b6c28e06f | 2,281 | package fr.redstonneur1256.redutilities.graphics.swing.component.abstractComp;
import fr.redstonneur1256.redutilities.Validate;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class AbstractBar extends JComponent {
private int value;
private int maximum;
private String string;
private boolean stringPainted;
private Color stringColor;
private boolean vertical;
public AbstractBar() {
value = 0;
maximum = 100;
string = "";
stringPainted = false;
stringColor = Color.BLACK;
vertical = false;
}
protected int getFill() {
double value = (double) this.value / this.maximum;
return (int) Math.round(value * (isVertical() ? getHeight() : getWidth()));
}
public int getValue() {
return value;
}
public void setValue(int value) {
if(value == this.value)
return;
Validate.isTrue(value >= 0 && value <= maximum, "Value must be >= 0 and <= maximum");
this.value = value;
this.repaint();
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
Validate.isTrue(maximum >= 1, "The maximum must be >= 1");
this.maximum = maximum;
this.repaint();
}
public String getString() {
return string;
}
public void setString(String string) {
Objects.requireNonNull(string, "string == null");
this.string = string;
this.repaint();
}
public boolean isStringPainted() {
return stringPainted;
}
public void setStringPainted(boolean stringPainted) {
this.stringPainted = stringPainted;
}
public Color getStringColor() {
return stringColor;
}
public void setStringColor(Color stringColor) {
this.stringColor = stringColor;
}
public boolean isVertical() {
return vertical;
}
public void setVertical(boolean vertical) {
this.vertical = vertical;
}
public interface Listener {
void valueChanged(int value);
}
public static class ListenerAdapter implements Listener {
@Override
public void valueChanged(int value) {
}
}
}
| 21.72381 | 93 | 0.611135 |
062eb75c58d07b85e408cda00cfd98b2bc47714c | 1,263 | package com.avseredyuk.configuration;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
@EnableCaching
public class AppConfiguration {
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.password}")
private String dbPassword;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Bean
public DataSource dataSource() throws SQLException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName(driverClassName);
return new HikariDataSource(config);
}
}
}
| 31.575 | 60 | 0.70863 |
0d825a5562a555d445895fc8811d2e80b1c1b389 | 779 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exemplosarray;
/**
*
* @author ederson.fernandes
*/
public class ExemploArray01 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
char vogais[] = new char[5];
vogais[0]='a';
vogais[1]='e';
vogais[2]='i';
vogais[3]='o';
vogais[4]='u';
// Uma outra opcao seria:
// char vogais[] = {'a', 'e', 'i', 'o', 'u'};
// Impressao das vogais.
for(int i=0; i<vogais.length; i++){
System.out.println(vogais[i]);
}
}
}
| 22.911765 | 79 | 0.539153 |
8676a3533a0f7ed85f5c74bcd6f325e9dd2d8f66 | 1,335 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.sdk.extensions.trace.testbed.concurrentcommonrequesthandler;
import io.opentelemetry.sdk.extensions.trace.testbed.TestUtils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
final class Client {
private final ExecutorService executor = Executors.newCachedThreadPool();
private final RequestHandler requestHandler;
public Client(RequestHandler requestHandler) {
this.requestHandler = requestHandler;
}
public Future<String> send(final Object message) {
final RequestHandlerContext requestHandlerContext = new RequestHandlerContext();
return executor.submit(
() -> {
TestUtils.sleep();
executor
.submit(
() -> {
TestUtils.sleep();
requestHandler.beforeRequest(message, requestHandlerContext);
})
.get();
executor
.submit(
() -> {
TestUtils.sleep();
requestHandler.afterResponse(message, requestHandlerContext);
})
.get();
return message + ":response";
});
}
}
| 28.404255 | 85 | 0.617228 |
3669a1788a1cc84ae9167abea723e8f0053fbf51 | 5,765 | package com.interview.codingblocks.week9DynamicProgrammming;
import java.util.Arrays;
public class ZeroOrOneKnapsack {
//Given a bag of 10 kg and items are:
//weight: 7 4 4
//price : 15 8 8
//If we use greedy, it picks price 15, and bag fills with weight:7
//Now, if we use dp, it picks optimal weights : 8 8 and profit : 16.
//So, we have to generate Subsets and check, which subset generate maximum profit.
//Step1: Recurrence relation for adding the element into bag:
//profit(n,10) = price [ n - 1 or last item ] + //include the current element
// profit( n - 1 , W - weight of last item ) //profit of remaining items: 10 - 6 = 4kg
//Step2 : Recurrence for not adding element into bag:
//profit(n,10) = 0 +
// profit( n - 1 , W = 10 ) //if we are not picking the weight
//Final profit: Math.max(step1, step2)
static int memo[][] = new int[100][100];
//Video ref : https://www.youtube.com/watch?time_continue=11629&v=X7SrnbgqHHs
public static void main( String[] args ) {
//output: 40
/*int[] weights = {2, 7, 3, 4};
int[] prices = {5, 20, 20, 10};
int N = 4; //number of items
int W = 11; //Bag capacity
*/
//output: 16
int[] weights = {7, 4, 4};
int[] prices = {15, 8, 8};
int N = 3;
int W = 10;
long startTime = System.nanoTime();
System.out.println(solveRecursive(weights, prices, N, W));
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("Time Recursive: " + totalTime);
//-----------------------------------------------------------------
long startTimeMemoization = System.nanoTime();
for (int[] row : memo)
Arrays.fill(row, -1);
System.out.println(solveTopDownDP(weights, prices, N, W));
long endTimeMemoization = System.nanoTime();
long totalTimeMemoization = endTimeMemoization - startTimeMemoization;
System.out.println("Time Top Down DP : " + totalTimeMemoization);
System.out.println(solveBottomUpDP(weights, prices, N, W));
}
//The include-exclude is same as : subsequences.java inside recursion
private static int solveRecursive( int[] weights, int[] prices, int N, int W ) {
//N==0 : if we have choose every items
//W==0 : if knapsack has no weight to fill
if (N == 0 || W == 0)
return 0;
int includeWeight = 0, excludeWeight = 0;
//Step1:
//if current element is fit into knapsack, then only pick element to include into Knapsack(bag)
if (weights[N - 1] <= W)
//N-1 : to pick next element
//W - weights[N-1] : current weight can fit into knapsack, so reduce it from Total weight : W
includeWeight = prices[N - 1] + solveRecursive(weights, prices, N - 1, W - weights[N - 1]);
//Step2: exclude the current from knapsack: just to create subset and check if some other fits into bag.
excludeWeight = 0 + solveRecursive(weights, prices, N - 1, W);
return Math.max(includeWeight, excludeWeight);
}
//We have to work on two params, N & W , so we need 2D array to solve this.
private static int solveTopDownDP( int weights[], int prices[], int N, int W ) {
//N==0 : if we have choose every items
//W==0 : if knapsack has no weight to fill
if (N == 0 || W == 0)
return 0;
if (memo[N - 1][N - 1] != -1)
return memo[N - 1][N - 1];
int includeWeight = 0, excludeWeight;
//Step1:
//if current element is fit into knapsack, then only pick element to include into Knapsack(bag)
if (weights[N - 1] <= W)
//N-1 : to pick next element
//W - weights[N-1] : current weight can fit into knapsack, so reduce it from Total weight : W
includeWeight = prices[N - 1] + solveRecursive(weights, prices, N - 1, W - weights[N - 1]);
//Step2: exclude the current from knapsack: just to create subset and check if some other fits into bag.
excludeWeight = 0 + solveTopDownDP(weights, prices, N - 1, W);
memo[N - 1][N - 1] = Math.max(includeWeight, excludeWeight);
return memo[N - 1][N - 1];
}
//Video : https://www.youtube.com/watch?v=sVAB0p58tlg
private static int solveBottomUpDP( int weights[], int prices[], int N, int W ) {
//initialize dp array with W = total weights size
int dp[][] = new int[prices.length + 1][W + 1];
for (int i = 0; i <= prices.length; i++) {
//Loop through Total weights given
for (int j = 0; j <= W; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
continue;
}
int value;
//if current weight is less than Sum of Weight
if (weights[i - 1] <= j) {
int excludingTheCurrentWeight = dp[i - 1][j]; //copy the value from above cell
int includingTheCurrentWeight = prices[i-1]; //include the current price value
int remainingWeight = j - weights[i-1]; //for remaining weight: [sum of weight - current weight ]
int remainingPrice = dp[i - 1][remainingWeight];
includingTheCurrentWeight += remainingPrice;
value = Math.max(excludingTheCurrentWeight, includingTheCurrentWeight);
} else {
value = dp[i - 1][j];
}
dp[i][j] = value;
}
}
return dp[prices.length][W];
}
}
| 35.368098 | 117 | 0.557329 |
57a1b31dfbeb0c38fed37becb6d351f931fb52e4 | 1,261 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.query.spi;
import java.io.Serializable;
import java.util.Map;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Extends an HQLQueryPlan to maintain a reference to the collection-role name
* being filtered.
*
* @author Steve Ebersole
*/
public class FilterQueryPlan extends HQLQueryPlan implements Serializable {
private final String collectionRole;
/**
* Constructs a query plan for an HQL filter
*
* @param hql The HQL fragment
* @param collectionRole The collection role being filtered
* @param shallow Is the query shallow?
* @param enabledFilters All enabled filters from the Session
* @param factory The factory
*/
public FilterQueryPlan(
String hql,
String collectionRole,
boolean shallow,
Map enabledFilters,
SessionFactoryImplementor factory) {
super( hql, collectionRole, shallow, enabledFilters, factory, null );
this.collectionRole = collectionRole;
}
public String getCollectionRole() {
return collectionRole;
}
}
| 26.829787 | 94 | 0.749405 |
369e3dfc6e6472f3b28ab6eef941a17d5b5a68d2 | 3,238 | /*
* Copyright (C) 2018 Janice Wildrick
*
* 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.youthexploringscience.youthexploringscience.db.entity;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
import com.youthexploringscience.youthexploringscience.db.Event;
@Entity(tableName = "events")
public class EventEntity implements Event {
@PrimaryKey
@NonNull
private String eventId;
private String eventSummary;
private String eventHtmlLink;
private String eventDescription;
private String eventLocation;
private int dateTimeStart;
private int dateTimeEnd;
public EventEntity(@NonNull String eventId, String eventSummary, String eventHtmlLink, String eventDescription, String eventLocation, int dateTimeStart, int dateTimeEnd) {
this.eventId = eventId;
this.eventSummary = eventSummary;
this.eventHtmlLink = eventHtmlLink;
this.eventDescription = eventDescription;
this.eventLocation = eventLocation;
this.dateTimeStart = dateTimeStart;
this.dateTimeEnd = dateTimeEnd;
}
@Override
public String getEventId() {
return eventId;
}
public void setEventId(String id) {
eventId = id;
}
@Override
public String getEventSummary() {
return eventSummary;
}
public void setEventSummary(String summary) {
eventSummary = summary;
}
@Override
public String getEventHtmlLink() {
return eventHtmlLink;
}
public void setEventHtmlLink(String link) {
eventHtmlLink = link;
}
@Override
public String getEventDescription() {
return eventDescription;
}
public void setEventDescription(String description) {
eventDescription = description;
}
@Override
public String getEventLocation() {
return eventLocation;
}
public void setEventLocation(String location) {
eventLocation = location;
}
@Override
public int getDateTimeStart() {
return dateTimeStart;
}
public void setDateTimeStart(int start) {
dateTimeStart = start;
}
@Override
public int getDateTimeEnd() {
return dateTimeEnd;
}
public void setDateTimeEnd(int end) {
dateTimeEnd = end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventEntity that = (EventEntity) o;
return eventId.equals(that.eventId);
}
@Override
public int hashCode() {
return eventId.hashCode();
}
}
| 25.698413 | 175 | 0.679432 |
034d6bd4c2cd86209153cc7ddae07fd814e7eb90 | 137 | /** Provides classes for mutating existing {@code Node} instances to create (evolve) new instances. */
package org.oakgp.evolve.mutate;
| 34.25 | 102 | 0.759124 |
cb664fe7b6a09403b9ba89bbfa796c5c2c2543dd | 1,607 | package org.jfw.util.execut;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.jfw.util.ConstData;
public class ServiceBean implements Service {
private Object bean;
private String startupMethodName;
private String shutdownMethodName;
private Method startupMethod;
private Method shutdownMethod;
private List<String> dependBeanNames;
public List<String> getDependBeanNames() {
return dependBeanNames;
}
public void setDepends(List<String> dependBeanNames) {
this.dependBeanNames = dependBeanNames;
}
public void setBean(Object bean) {
this.bean = bean;
}
public void setStartupMethodName(String startupMethodName) {
this.startupMethodName = startupMethodName;
}
public void setShutdownMethodName(String shutdownMethodName) {
this.shutdownMethodName = shutdownMethodName;
}
private void init() throws NoSuchMethodException, SecurityException{
Class<?> clazz = this.bean.getClass();
this.startupMethod = clazz.getMethod(this.startupMethodName,ConstData.EMPTY_CLASS_ARRAY);
this.shutdownMethod= clazz.getMethod(this.shutdownMethodName, ConstData.EMPTY_CLASS_ARRAY);
}
@Override
public void startup() throws Exception{
this.init();
this.startupMethod.invoke(this.bean, ConstData.EMPTY_OBJECT_ARRAY);
}
@Override
public void shutdown() {
try {
this.shutdownMethod.invoke(this.bean, ConstData.EMPTY_OBJECT_ARRAY);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
}
}
}
| 27.706897 | 94 | 0.755445 |
e3223d6c1483ecca8d47b86b499b06cb6412e61c | 64,079 | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/03/11 Martin D. Flynn
// -Initial release
// 2007/03/25 Martin D. Flynn
// -Added support for rule selectors
// -Updated to use 'DeviceList'
// 2007/06/03 Martin D. Flynn
// -Added PrivateLabel to constructor
// 2007/06/13 Martin D. Flynn
// -Renamed 'DeviceList' to 'ReportDeviceList'
// 2007/06/30 Martin D. Flynn
// -Added 'getTotalsDataIterator'
// 2007/11/28 Martin D. Flynn
// -Integrated use of 'ReportColumn'
// 2008/02/21 Martin D. Flynn
// -Modified '_getEventData' to set the Device on retrieved EventData records
// 2009/01/01 Martin D. Flynn
// -Added 'setOrderAscending' to allow descending order EventData reports.
// 2009/11/01 Martin D. Flynn
// -Added ReportOption support
// 2015/08/16 Martin D. Flynn
// -Added support to "_getEventData_Device(..)" to allow null Device and
// retrieve EventData records based on the "where" specification only.
// ----------------------------------------------------------------------------
package org.opengts.war.report;
import java.util.*;
import java.io.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
import org.opengts.db.tables.*;
import org.opengts.war.tools.PrivateLabel;
import org.opengts.war.tools.RequestProperties;
import org.opengts.war.tools.MapDimension;
import org.opengts.war.tools.OutputProvider;
import org.opengts.war.report.ReportFactory;
import org.opengts.war.report.ReportColumn;
public abstract class ReportData
{
// ------------------------------------------------------------------------
//public static final long RECORD_LIMIT = 800L;
// ------------------------------------------------------------------------
private static final boolean REPORT_DATA_FIELDS_ENABLED = false;
private static final String PROP_reportDataFieldEnabled = "reportDataFieldEnabled";
private static final String PROP_gpsAgeColorRange = "gpsAgeColorRange";
private static final String PROP_gpsAgeColorRange_array = "gpsAgeColorRange.array";
private static final String PROP_creationAgeColorRange = "creationAgeColorRange";
private static final String PROP_creationAgeColorRange_array = "creationAgeColorRange.array";
private static final String PROP_checkinAgeColorRange = "checkinAgeColorRange";
private static final String PROP_checkinAgeColorRange_array = "checkinAgeColorRange.array";
private static final String PROP_loginAgeColorRange = "loginAgeColorRange";
private static final String PROP_loginAgeColorRange_array = "loginAgeColorRange.array";
// ------------------------------------------------------------------------
public static final String FORMAT_MAP = "map";
public static final String FORMAT_KML = "kml";
public static final String FORMAT_PDF = "pdf";
public static final String FORMAT_GRAPH = "graph";
// ------------------------------------------------------------------------
private static final String DFT_REPORT_NAME = "generic.report";
private static final String DFT_REPORT_TITLE = "Generic Report";
private static final String DFT_REPORT_SUBTITLE = "${deviceDesc} [${deviceId}]\n${dateRange}";
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private static final ReportColumn EMPTY_COLUMNS[] = new ReportColumn[0];
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*
public static ReportOptionsProvider getReportOptionsProvider()
{
return new ReportOptionsProvider() {
public OrderedMap<String,ReportOption> getReportOptionMap(ReportFactory rptFact, RequestProperties reqState) {
//PrivateLabel privLabel = reqState.getPrivateLabel();
//I18N i18n = privLabel.getI18N(ReportData.class);
//OrderedMap<String,ReportOption> map = new OrderedMap<String,ReportOption>();
//map.put("test1", new ReportOption("test1", i18n.getString("ReportData.option.1","This is Option 1"), null));
//map.put("test2", new ReportOption("test2", i18n.getString("ReportData.option.2","This is Option 2"), null));
//return map;
return null;
}
};
}
*/
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private String reportName = DFT_REPORT_NAME;
private String reportTitle = DFT_REPORT_TITLE;
private String reportSubtitle = DFT_REPORT_SUBTITLE;
private ReportEntry rptEntry = null;
private ReportFactory rptFactory = null;
private Object/*ReportJob*/ rptJob = null;
private PrivateLabel privLabel = null;
private RequestProperties reqState = null;
private Account account = null;
private User user = null;
private String preferredFormat = "";
private ReportDeviceList deviceList = null;
private int eventDataCount = 0; // per device
private int eventMatchCount = 0; // per device
private int maxEventDataCount = 0; // max device counted events
private int rptRecordCount = 0;
private boolean rptIsPartial = false;
private ReportConstraints rptConstraints = null;
private ReportOption reportOption = null;
private RTProperties reportProperties = null;
private ReportHeaderGroup rptHdrGrps[] = null;
private ReportColumn rptColumns[] = EMPTY_COLUMNS; // never null
private URIArg refreshURL = null;
private URIArg autoReportURL = null;
private URIArg graphImageURL = null; // OBSOLETE
private URIArg mapURL = null;
private URIArg kmlURL = null;
private String iconSelector = null;
private ReportCallback rptCallback = null;
// ------------------------------------------------------------------------
/* OBSOLETE: create an instance of a report */
public ReportData(ReportFactory rptFact, RequestProperties reqState, Account acct, User user, ReportDeviceList devList)
throws ReportException
{
this.rptFactory = rptFact; // never null
this.reqState = reqState; // never null
this.privLabel = this.reqState.getPrivateLabel();
this.account = acct;
this.user = user;
this.deviceList = devList;
}
/**
*** Constructor
**/
public ReportData(ReportEntry rptEntry, RequestProperties reqState, ReportDeviceList devList)
throws ReportException
{
this.rptEntry = rptEntry; // never null
this.rptFactory = this.rptEntry.getReportFactory(); // never null
this.reqState = reqState; // never null
this.privLabel = this.reqState.getPrivateLabel(); // never null
this.account = this.reqState.getCurrentAccount(); // should not be null
this.user = this.reqState.getCurrentUser(); // may be null;
this.deviceList = devList;
}
// ------------------------------------------------------------------------
/**
*** Returns true if this instance defines a ReportJob
**/
public boolean hasReportJob()
{
return (this.rptJob != null)? true : false;
}
/**
*** Gets the ReportJob for this report (if any)
**/
public Object/*ReportJob*/ getReportJob()
{
return this.rptJob;
}
/**
*** Sets the ReportJob for this report (if any)
**/
public void setReportJob(Object/*ReportJob*/ rj)
{
this.rptJob = rj;
}
// ------------------------------------------------------------------------
/**
*** Returns the report entry which created this report
**/
public ReportEntry getReportEntry()
{
return this.rptEntry; // may be null
}
/**
*** Returns the report factory which ctreated this report
**/
public ReportFactory getReportFactory()
{
return this.rptFactory; // never null
}
/**
*** Returns the ReportFactory properties
**/
public RTProperties getProperties()
{
if (this.reportProperties == null) {
this.reportProperties = this.getReportFactory().getProperties(); // never null
if (this.hasReportOption()) {
this.reportProperties = new RTProperties(this.reportProperties);
//this.reportProperties.printProperties("ReportData Properties:");
//this.getReportOption().getProperties().printProperties("ReportOption Properties:");
this.reportProperties.setProperties(this.getReportOption().getProperties());
//this.reportProperties.printProperties("Combined Properties:");
}
}
return this.reportProperties; // never null
}
// ------------------------------------------------------------------------
/**
*** Sets the name of this report
**/
public void setReportName(String name)
{
this.reportName = name;
}
/**
*** Gets the name of this report
**/
public String getReportName()
{
if ((this.reportName != null) && !this.reportName.equals("")) {
return this.reportName;
} else {
return DFT_REPORT_NAME;
}
}
// ------------------------------------------------------------------------
/**
*** Gets the report type
**/
public String getReportType()
{
return this.getReportFactory().getReportType();
}
// ------------------------------------------------------------------------
/**
*** Sets the report title
**/
public void setReportTitle(String title)
{
this.reportTitle = title;
}
/**
*** Gets the report title
**/
public String getReportTitle()
{
if ((this.reportTitle != null) && !this.reportTitle.equals("")) {
return this.expandHeaderText(this.reportTitle);
} else {
return this.expandHeaderText(DFT_REPORT_NAME);
}
}
// ------------------------------------------------------------------------
/**
*** Sets the report sub-title
**/
public void setReportSubtitle(String title)
{
this.reportSubtitle = title;
}
/**
*** Gets the report sub-title
**/
public String getReportSubtitle()
{
//if (!StringTools.isBlank(this.reportSubtitle)) {
return this.expandHeaderText(this.reportSubtitle);
//} else {
// return this.expandHeaderText(DFT_REPORT_SUBTITLE);
//}
}
// ------------------------------------------------------------------------
/**
*** Replaces ${key} fields with the representative text
**/
public String expandHeaderText(String text)
{
return ReportLayout.expandHeaderText(text, this);
}
// ------------------------------------------------------------------------
// RequestProperties
/**
*** Gets the current RequestProperties instance
**/
public RequestProperties getRequestProperties()
{
return this.reqState; // never null
}
/**
*** Returns true if this is a "SOAP" request
**/
public boolean isSoapRequest()
{
return this.getRequestProperties().isSoapRequest();
}
/**
*** Gets the selected TimeZone
**/
public TimeZone getTimeZone()
{
return this.getRequestProperties().getTimeZone();
}
/**
*** Gets the selected TimeZone as a String
**/
public String getTimeZoneString()
{
return this.getRequestProperties().getTimeZoneString(null);
}
// ------------------------------------------------------------------------
// PrivateLabel
/**
*** Gets the current PrivateLabel instance
**/
public PrivateLabel getPrivateLabel()
{
return this.privLabel;
}
/**
*** Gets the current PrivateLabel Locale
**/
public Locale getLocale()
{
return this.getRequestProperties().getLocale();
}
// ------------------------------------------------------------------------
/**
*** Sets the map icon selector
**/
public void setMapIconSelector(String iconSel)
{
this.iconSelector = iconSel;
}
/**
*** Gets the map icon selector
**/
public String getMapIconSelector()
{
return this.iconSelector;
}
// ------------------------------------------------------------------------
// Account
/**
*** Gets the current Account
**/
public Account getAccount()
{
return this.account;
}
/**
*** Gets the current Account-ID
**/
public String getAccountID()
{
Account a = this.getAccount();
return (a != null)? a.getAccountID() : "";
}
/**
*** Gets the current Account description
**/
public String getAccountDescription()
{
Account a = this.getAccount();
return (a != null)? a.getDescription() : "";
}
// ------------------------------------------------------------------------
// User
/**
*** Gets the current User (may be null)
**/
public User getUser()
{
return this.user;
}
/**
*** Gets the current User-ID (may be blank)
**/
public String getUserID()
{
User u = this.getUser();
return (u != null)? u.getUserID() : "";
}
// ------------------------------------------------------------------------
// preferred format
/**
*** Gets the preferred report format
**/
public String getPreferredFormat()
{
return StringTools.trim(this.preferredFormat);
}
/**
*** Sets the preferred report format
**/
public void setPreferredFormat(String format)
{
this.preferredFormat = StringTools.trim(format);
}
// ------------------------------------------------------------------------
// single device report
/**
*** Returns true if this report handles only a single device at a time
*** @return True If this report handles only a single device at a time
**/
public boolean isSingleDeviceOnly()
{
return false;
}
// ------------------------------------------------------------------------
// Devices
/**
*** Sets the device list
**/
protected void setReportDeviceList(ReportDeviceList devList)
throws ReportException
{
this.deviceList = devList;
}
/**
*** Gets the device list
**/
public ReportDeviceList getReportDeviceList()
{
if (this.deviceList == null) {
this.deviceList = new ReportDeviceList(this.getAccount(),this.getUser());
// -- sort by device description!
}
return this.deviceList;
}
/**
*** Returns true if this was a group selection report
**/
public boolean isDeviceGroupReport()
{
ReportDeviceList rdl = this.getReportDeviceList();
return rdl.isDeviceGroup();
}
/**
*** Gets the device list size
**/
public int getDeviceCount()
{
if (this.deviceList == null) {
return 0;
} else {
return this.deviceList.size();
}
}
/**
*** Gets the first device id in the list
**/
public String getFirstDeviceID()
{
return this.getReportDeviceList().getFirstDeviceID();
}
/**
*** Gets the Device instance for the specified ID
**/
public Device getDevice(String deviceID)
throws DBException
{
ReportDeviceList devList = this.getReportDeviceList();
return devList.getDevice(deviceID);
}
// ------------------------------------------------------------------------
// report header groups
/**
*** Sets the report header groups
**/
public void setReportHeaderGroups(ReportHeaderGroup rhg[])
{
this.rptHdrGrps = rhg;
}
/**
*** Gets the report header groups
**/
public ReportHeaderGroup[] getReportHeaderGroups()
{
return this.rptHdrGrps;
}
/**
*** Sets the report header group at the specified column
**/
public ReportHeaderGroup getReportHeaderGroup(int col)
{
/* no report header groups? */
if (ListTools.isEmpty(this.rptHdrGrps)) {
return null;
}
/* search for column */
for (ReportHeaderGroup rhg : this.rptHdrGrps) {
int C = rhg.getColIndex();
if (col == C) {
return rhg;
}
// TODO: optimize
}
/* not found */
return null;
}
// ------------------------------------------------------------------------
// report columns
/**
*** Sets the report columns [initialized by ReportFactory.createReport(...)]
**/
public void setReportColumns(ReportColumn columns[])
{
this.rptColumns = (columns != null)? columns : EMPTY_COLUMNS;
}
/**
*** Gets the report columns (does not return null)
**/
public ReportColumn[] getReportColumns()
{
return this.rptColumns;
}
/**
*** Gets the report column count
**/
public int getColumnCount()
{
return this.rptColumns.length;
}
/**
*** Returns true if this report has the named column
**/
public boolean hasReportColumn(String name)
{
if (!StringTools.isBlank(name)) {
for (ReportColumn rc : this.rptColumns) {
if (rc.getName().equalsIgnoreCase(name)) {
return true;
}
}
}
return false;
}
// --------------------------------
/**
*** Sets the column names to include in the report (null/empty for all columns)
*** (currently only called from "Service.java"
**/
public boolean setIncludeColumnNames(Set<String> colNames)
{
if (!ListTools.isEmpty(colNames)) {
int colLen = 0;
ReportColumn newCols[] = new ReportColumn[this.rptColumns.length];
for (ReportColumn RC : this.rptColumns) {
if (colNames.contains(RC.getName())) {
newCols[colLen++] = RC;
}
}
// -- trim new column array
if (colLen <= 0) {
// -- no columns were chosen, leave as-is
return false;
} else
if (colLen < newCols.length) {
// -- new array is smaller (likely)
this.rptColumns = ListTools.toArray(newCols,0,colLen);
return true;
} else {
// -- all columns selected, leave as-is
return true;
}
} else {
// -- no columns to include
return false;
}
}
// --------------------------------
/**
*** Sets the column names to omit from the report
**/
public boolean setOmitColumnNames(Set<String> colNames)
{
if (!ListTools.isEmpty(colNames)) {
int colLen = 0; // count of columns to retain
ReportColumn newCols[] = new ReportColumn[this.rptColumns.length];
for (ReportColumn RC : this.rptColumns) {
if (!colNames.contains(RC.getName())) {
newCols[colLen++] = RC;
}
}
// -- trim new column array
if (colLen <= 0) {
// -- all columns were omitted. Not allowed, leave as-is
return false;
} else
if (colLen < newCols.length) {
// -- new array is smaller (likely)
this.rptColumns = ListTools.toArray(newCols,0,colLen);
return true;
} else {
// -- no columns omitted, leave as-is
return true;
}
} else {
// -- no columns to omit
return false;
}
}
// --------------------------------
/**
*** Dynamic checking for whether a specific column should be displayed.
*** (callback from "HeaderRowTemplate.java" and "BodyRowTemplate.java")
**/
public boolean showColumn(ReportColumn rtpCol)
{
return true;
}
// ------------------------------------------------------------------------
// ReportOption
/**
*** Returns true if this report has report options
**/
public boolean hasReportOption()
{
return (this.reportOption != null);
}
/**
*** Gets the report options
**/
public ReportOption getReportOption()
{
return this.reportOption;
}
/**
*** Sets the report options
**/
public void setReportOption(ReportOption rptOpt)
{
this.reportOption = rptOpt;
this.reportProperties = null;
}
// ------------------------------------------------------------------------
// set constraints used for retrieving EventData records
/**
*** Sets the ReportConstraints for this report
*** @param rc The ReportConstraints
**/
public void setReportConstraints(ReportConstraints rc)
{
// This is a clone of the ReportConstraints found in the report factory
// This ReportConstraints object is owned only by this specific report and may
// be modified if necessary.
this.rptConstraints = rc;
}
/**
*** Gets the ReportConstraints for this report
*** @return The ReportConstraints
**/
public ReportConstraints getReportConstraints()
{
if (this.rptConstraints == null) {
// this should never occur, but return a default report constraints anyway
this.rptConstraints = new ReportConstraints(); // should never occur!
}
return this.rptConstraints;
}
// ------------------------------------------------------------------------
// Enable report fields
/**
*** Return true if report data fields should be enabled.<br>
*** Report data fields are those that are calculated as the report is
*** generated. (not used by all report types).
*** @return True if the report data fields should be enabled
**/
public boolean getReportDataFieldsEnabled()
{
return this.getProperties().getBoolean(PROP_reportDataFieldEnabled,REPORT_DATA_FIELDS_ENABLED);
}
// ------------------------------------------------------------------------
// GPS AgeColorRange
// ReportLayout.ParseAgeColorRange("1200:#550000,3600:#BB0000",null)
public static final ReportLayout.AgeColorRange GpsAgeColorRangeDefault[] = new ReportLayout.AgeColorRange[] {
new ReportLayout.AgeColorRange(3600, "#BB0000", "italic"), // 60 minutes
new ReportLayout.AgeColorRange(1200, "#550000", null ), // 20 minutes
};
/**
*** Gets the GPS age color range array
**/
public ReportLayout.AgeColorRange[] getGpsAgeColorRangeArray()
{
RTProperties rtp = this.getProperties();
Object gacra = rtp.getProperty(PROP_gpsAgeColorRange_array,null);
if (!(gacra instanceof ReportLayout.AgeColorRange[])) {
String gacrl = rtp.getString(PROP_gpsAgeColorRange,null);
gacra = ReportLayout.ParseAgeColorRange(gacrl,GpsAgeColorRangeDefault);
if (gacra == null) {
gacra = new ReportLayout.AgeColorRange[0];
}
rtp.setProperty(PROP_gpsAgeColorRange_array,gacra); // cache
}
return (ReportLayout.AgeColorRange[])gacra;
}
/**
*** Gets the GPS age color for the specified age
**/
public ReportLayout.AgeColorRange getGpsAgeColorRange(long age)
{
ReportLayout.AgeColorRange acra[] = this.getGpsAgeColorRangeArray();
return ReportLayout.GetAgeColorRange(age, acra);
}
// ------------------------------------------------------------------------
// Creation AgeColorRange
// ReportLayout.ParseAgeColorRange("1200:#550000,3600:#BB0000",null)
public static final ReportLayout.AgeColorRange CreationAgeColorRangeDefault[] = new ReportLayout.AgeColorRange[] {
// empty
};
/**
*** Gets the creation age color range array
**/
public ReportLayout.AgeColorRange[] getCreationAgeColorRangeArray()
{
RTProperties rtp = this.getProperties();
Object cacra = rtp.getProperty(PROP_creationAgeColorRange_array,null);
if (!(cacra instanceof ReportLayout.AgeColorRange[])) {
String cacrl = rtp.getString(PROP_creationAgeColorRange,null);
cacra = ReportLayout.ParseAgeColorRange(cacrl,CreationAgeColorRangeDefault);
if (cacra == null) {
cacra = new ReportLayout.AgeColorRange[0];
}
rtp.setProperty(PROP_creationAgeColorRange_array,cacra); // cache
}
return (ReportLayout.AgeColorRange[])cacra;
}
/**
*** Gets the creation age color for the specified age
**/
public ReportLayout.AgeColorRange getCreationAgeColorRange(long age)
{
ReportLayout.AgeColorRange acra[] = this.getCreationAgeColorRangeArray();
return ReportLayout.GetAgeColorRange(age, acra);
}
// ------------------------------------------------------------------------
// CheckIn AgeColorRange
// ReportLayout.ParseAgeColorRange("86400:#BB0000",null)
public static final ReportLayout.AgeColorRange CheckinAgeColorRangeDefault[] = new ReportLayout.AgeColorRange[] {
new ReportLayout.AgeColorRange(DateTime.HourSeconds(24), "#BB0000", null), // 24 hours
};
/**
*** Gets the check-in age color range array
**/
public ReportLayout.AgeColorRange[] getCheckinAgeColorRangeArray()
{
RTProperties rtp = this.getProperties();
Object cacra = rtp.getProperty(PROP_checkinAgeColorRange_array,null);
if (!(cacra instanceof ReportLayout.AgeColorRange[])) {
String cacrl = rtp.getString(PROP_checkinAgeColorRange,null);
cacra = ReportLayout.ParseAgeColorRange(cacrl,CheckinAgeColorRangeDefault);
if (cacra == null) {
cacra = new ReportLayout.AgeColorRange[0];
}
rtp.setProperty(PROP_checkinAgeColorRange_array,cacra); // cache
}
return (ReportLayout.AgeColorRange[])cacra;
}
/**
*** Gets the check-in age color for the specified age
**/
public ReportLayout.AgeColorRange getCheckinAgeColorRange(long age)
{
ReportLayout.AgeColorRange acra[] = this.getCheckinAgeColorRangeArray();
return ReportLayout.GetAgeColorRange(age, acra);
}
// ------------------------------------------------------------------------
// Login AgeColorRange
// ReportLayout.ParseAgeColorRange("604800:#AA9700,2592000:#DD0000",null)
public static final ReportLayout.AgeColorRange LoginAgeColorRangeDefault[] = new ReportLayout.AgeColorRange[] {
new ReportLayout.AgeColorRange(DateTime.DaySeconds( 7), "#AA9700", null), // 1 week (yellow)
new ReportLayout.AgeColorRange(DateTime.DaySeconds(30), "#DD0000", null), // 1 month (red)
};
/**
*** Gets the log-in age color range array
**/
public ReportLayout.AgeColorRange[] getLoginAgeColorRangeArray()
{
RTProperties rtp = this.getProperties();
Object cacra = rtp.getProperty(PROP_loginAgeColorRange_array,null);
if (!(cacra instanceof ReportLayout.AgeColorRange[])) {
String cacrl = rtp.getString(PROP_loginAgeColorRange,null);
cacra = ReportLayout.ParseAgeColorRange(cacrl,LoginAgeColorRangeDefault);
if (cacra == null) {
cacra = new ReportLayout.AgeColorRange[0];
}
rtp.setProperty(PROP_loginAgeColorRange_array,cacra); // cache
}
return (ReportLayout.AgeColorRange[])cacra;
}
/**
*** Gets the log-in age color for the specified age
**/
public ReportLayout.AgeColorRange getLoginAgeColorRange(long age)
{
ReportLayout.AgeColorRange acra[] = this.getLoginAgeColorRangeArray();
return ReportLayout.GetAgeColorRange(age, acra);
}
// ------------------------------------------------------------------------
// -- The following allows the specific report to override any of the defined constraints
/**
*** Returns the 'rule' selector constraint
*** @return The 'rule' selector constraint
**/
public String getRuleSelector()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getRuleSelector();
}
/**
*** Returns the 'WHERE' selector constraint
*** @return The 'WHERE' selector constraint
**/
public String getWhereSelector()
{
ReportConstraints rc = this.getReportConstraints();
String wh = rc.getWhere();
if (this.hasReportOption()) {
ReportOption ro = this.getReportOption();
wh = StringTools.replaceKeys(wh, ro.getProperties());
}
return wh;
}
// --------------------------------
/**
*** Returns the selection limit type constraint
*** @return The selection limit type constraint
**/
public EventData.LimitType getSelectionLimitType()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getSelectionLimitType();
}
/**
*** Returns the selection limit constraint.
*** @return The selection limit constraint
**/
public long getSelectionLimit()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getSelectionLimit();
}
/**
*** Returns the report limit constraint.
*** @return The report limit constraint
**/
public long getReportLimit()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getReportLimit();
}
// --------------------------------
/**
*** Returns true if the report time-start is required
*** @return True if the report time-start is required
**/
public boolean getRequiresTimeStart()
{
return true;
}
/**
*** Returns true if the report time-end is required
*** @return True if the report time-end is required
**/
public boolean getRequiresTimeEnd()
{
return true;
}
// --------------------------------
/**
*** Returns the time start constraint
*** @return The time start constraint
**/
public long getTimeStart()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getTimeStart();
}
/**
*** Returns the time end constraint
*** @return The time end constraint
**/
public long getTimeEnd()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getTimeEnd();
}
// --------------------------------
/**
*** Returns the "valid GPS required" constraint
*** @return The "valid GPS required" constraint
**/
public boolean getValidGPSRequired()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getValidGPSRequired();
}
/**
*** Returns the status codes constraint
*** @return The status codes constraint
**/
public int[] getStatusCodes()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getStatusCodes();
}
/**
*** Returns true if the data records are to be in ascending order
*** @return True if the data records are to be in ascending order
**/
public boolean getOrderAscending()
{
ReportConstraints rc = this.getReportConstraints();
return rc.getOrderAscending();
}
// ------------------------------------------------------------------------
// ReportCallback
/**
*** Gets the ReportCallback instance (if specified)
*** @return The ReportCallback instance, or null if not set
**/
public ReportCallback getReportCallback()
{
return this.rptCallback;
}
/**
*** Sets the ReportCallback instance
*** @param rptCB The ReportCallback instance
**/
public void setReportCallback(ReportCallback rptCB)
throws ReportException
{
this.rptCallback = rptCB;
if (this.rptCallback != null) {
this.rptCallback.setReport(this);
}
}
// ------------------------------------------------------------------------
// EventData record retrieval
/**
*** Creates and returns an iterator over the EventData records based on the
*** defined selection criteria
*** @return The EventData row data iterator
**/
/*
public DBDataIterator getEventDataIterator()
{
EventData ed[] = this.getEventData_DeviceList(null);
return new ArrayDataIterator(ed); // 'EventDataLayout' expects EventData[]
}
*/
/**
*** Returns an array EventData records based on the predefined ReportDeviceList and constraints
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned EventData
*** array may be null.
*** @return An array of EventData records for the device (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] getEventData_DeviceList(DBRecordHandler<EventData> rcdHandler)
{
long rptLimit = this.getReportLimit(); // report record limit
/* EventData record accumulator */
java.util.List<EventData> edList = new Vector<EventData>();
/* iterate through devices */
this.maxEventDataCount = 0;
ReportDeviceList devList = this.getReportDeviceList();
for (Iterator<String> i = devList.iterator(); i.hasNext();) {
String devID = i.next();
this.eventDataCount = 0; // per device
this.eventMatchCount = 0; // per device
/* have we reached our limit? */
if ((rptLimit >= 0L) && (edList.size() >= rptLimit)) {
break;
}
// -- there is room for at least one more record
/* get device records */
try {
Device device = devList.getDevice(devID);
EventData ed[] = this._getEventData_Device(device, null, rcdHandler); // may be empty
if (rptLimit < 0L) {
// -- no limit: add all of new EventData records to list
ListTools.toList(ed, edList);
} else {
int maxRcds = (int)rptLimit - edList.size(); // > 0
if (ed.length <= maxRcds) {
// -- under limit: add all of new EventData records to list
ListTools.toList(ed, edList);
} else {
// -- clip to limit
ListTools.toList(ed, 0, maxRcds, edList);
}
}
} catch (DBException dbe) {
Print.logError("Error retrieving EventData for Device: " + devID);
}
/* maximum selected EventData records */
if (this.eventDataCount > this.maxEventDataCount) {
this.maxEventDataCount = this.eventDataCount;
}
}
return edList.toArray(new EventData[edList.size()]);
}
/**
*** Returns an array EventData records for the specified Device
*** @param deviceDB The Device for which EventData records will be selected
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned EventData
*** array may be null.
*** @return An array of EventData records for the device (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] getEventData_Device(Device deviceDB, DBRecordHandler<EventData> rcdHandler)
{
this.eventDataCount = 0; // per device
this.eventMatchCount = 0; // per device
EventData ed[] = this._getEventData_Device(deviceDB, null, rcdHandler);
this.maxEventDataCount = this.eventDataCount;
return ed;
}
/**
*** Returns an array EventData records for the specified Device
*** @param deviceDB The Device for which EventData records will be selected
*** @param timeStart The Start time
*** @param timeEnd The End time
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned EventData
*** array may be null.
*** @return An array of EventData records for the device (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] getEventData_Device(Device deviceDB,
long timeStart, long timeEnd,
DBRecordHandler<EventData> rcdHandler)
{
this.eventDataCount = 0; // per device
this.eventMatchCount = 0; // per device
long ts = (timeStart > 0L)? timeStart : this.getTimeStart();
long te = (timeEnd > 0L)? timeEnd : this.getTimeEnd();
EventData ed[] = this._getEventData_Device(deviceDB, ts, te, null, rcdHandler);
this.maxEventDataCount = this.eventDataCount;
return ed;
}
/**
*** Returns an array EventData records for the specified Driver
*** @param driverID The DriverID for which EventData records will be selected
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned EventData
*** array may be null.
*** @return An array of EventData records for the driver (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] getEventData_Driver(String driverID, DBRecordHandler<EventData> rcdHandler)
{
String accountID = this.getAccountID();
this.eventDataCount = 0; // per device
this.eventMatchCount = 0; // per device
if (!StringTools.isBlank(driverID)) {
Print.logInfo("Getting EventData records by Driver: " + accountID + "/" + driverID);
DBWhere dwh = new DBWhere(EventData.getFactory());
dwh.append(dwh.EQ(EventData.FLD_driverID, driverID));
EventData ed[] = this._getEventData_Device(null/*Device*/, dwh.toString(), rcdHandler);
this.maxEventDataCount = this.eventDataCount;
return ed;
} else {
Print.logWarn("DriverID is null/blank: " + accountID);
return new EventData[0];
}
}
/**
*** Callback for each EventData record selected. This method can be overridden by
*** the subclass to allow for additional criteria selection.
*** @param ev The current EventData record to test
*** @return True to accept record, false to skip record
**/
protected boolean isEventDataMatch(EventData ev)
{
return true;
}
// ------------------------------------------------------------------------
// read EventData records (based on Device)
private static class LastEventData
{
private EventData event = null;
public void setEvent(EventData ev) { this.event = ev; }
public EventData getEvent() { return this.event; }
}
/**
*** Returns an array EventData records for the specified Device
*** @param deviceDB The Device for which EventData records will be selected
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned EventData
*** array may be null.
*** @return An array of EventData records for the device (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] _getEventData_Device(final Device deviceDB,
String addtlWhereSelect_1,
final DBRecordHandler<EventData> rcdHandler)
{
long timeStart = this.getTimeStart();
long timeEnd = this.getTimeEnd();
return this._getEventData_Device(deviceDB,
timeStart, timeEnd,
addtlWhereSelect_1,
rcdHandler);
}
/**
*** Returns an array EventData records for the specified Device
*** @param deviceDB The Device for which EventData records will be selected
*** @param timeStart Selection Start time
*** @param timeEnd Selection End time
*** @param addtlWhereSelect_1 Additional "Where" selection criteria
*** @param rcdHandler The callback DBRecordHandler. If specified, the returned
*** EventData array may be null.
*** @return An array of EventData records for the device (may be null if a callback
*** DBRecordHandler has been specified).
**/
protected EventData[] _getEventData_Device(final Device deviceDB,
long timeStart, long timeEnd,
String addtlWhereSelect_1,
final DBRecordHandler<EventData> rcdHandler)
{
String addtlWhereSelect_2 = this.getWhereSelector();
//Print.logInfo("Additional Where #2: " + addtlWhereSelect_2);
/* Device */
// -- a null device may be allowed to for getting driver associated events
if ((deviceDB == null) &&
StringTools.isBlank(addtlWhereSelect_1) &&
StringTools.isBlank(addtlWhereSelect_2)) {
// -- no device, with a blank additional-select, would select too many records
Print.logWarn("Device not specified and no additional 'WHERE' selection specified.");
return EventData.EMPTY_ARRAY;
}
/* Account */
String accountID = this.getAccountID();
//Print.logInfo("Getting EventData for " + accountID + "/" + deviceID);
/* EventData rule selector (RuleFactory support required) */
final String ruleSelector = this.getRuleSelector();
final RuleFactory ruleFact;
if (!StringTools.isBlank(ruleSelector)) {
//Print.logInfo("Constraint Rule Selector: " + ruleSelector);
ruleFact = Device.getRuleFactory();
if (ruleFact == null) {
Print.logWarn("RuleSelector not supported");
}
} else {
//Print.logInfo("No Constraint Rule Selector");
ruleFact = null;
}
/* create record handler */
final LastEventData lastEDR = new LastEventData();
DBRecordHandler<EventData> evRcdHandler = new DBRecordHandler<EventData>() {
public int handleDBRecord(EventData rcd) throws DBException {
//Print.logInfo("Read EventData: " + rcd);
ReportData.this.eventDataCount++;
EventData ev = rcd;
// -- chain events together
EventData lastEv = lastEDR.getEvent(); // may be null
ev.setPreviousEventData(lastEv); // may set null
lastEDR.setEvent(ev);
// -- set the Device instance for this EventData
if (deviceDB != null) {
// -- (assume Account/Device match) cache Device
ev.setDevice(deviceDB);
// -- TODO: mark device as having had an event
} else
if (lastEv != null) {
// -- try getting Device from last event
String A = lastEv.getAccountID();
String D = lastEv.getDeviceID();
if (ev.getAccountID().equals(A) && ev.getDeviceID().equals(D)) {
// -- Account/Device match, try getting Device from last event
Device dev = lastEv.getDevice(); // may force DB query
if (dev != null) {
ev.setDevice(dev);
} else {
// -- last Device instance is null
}
} else {
// -- last event does not match this event
}
}
// -- calculate report distance
if (ReportData.this.getReportDataFieldsEnabled() && (lastEv != null)) {
ev.calculateReportDistance(lastEv);
}
// -- check match
if (!ReportData.this.isEventDataMatch(ev)) {
// -- no match: skip this event
// - TODO: remove this event from the EventData previous-event chain?
return DBRH_SKIP;
} else
if ((ruleFact != null) && !ruleFact.isSelectorMatch(ruleSelector,ev)) {
// -- no match: skip this event
// - TODO: remove this event from the EventData previous-event chain?
return DBRH_SKIP;
}
// -- mark device as having had a match?
ReportData.this.eventMatchCount++;
// - TODO:
// -- check RecordHandler
if (rcdHandler == null) {
// -- match, no default record handler
return DBRH_SAVE;
} else {
// -- match, send to default record handler
try {
return rcdHandler.handleDBRecord(rcd);
} catch (DBException dbe) {
throw dbe; // re-throw DBException
} catch (Throwable th) {
Print.logException("RecordHandler callback exception", th);
return DBRH_STOP;
}
}
}
};
/* get events */
EventData ed[] = null;
try {
String devID = (deviceDB != null)? deviceDB.getDeviceID() : null;
//Print.logInfo("Reading EventData: dev="+deviceDB +", ts="+timeStart +", te="+timeEnd);
ed = EventData.getRangeEvents(
accountID, devID,
timeStart, timeEnd,
this.getStatusCodes(),
this.getValidGPSRequired(),
this.getSelectionLimitType(), this.getSelectionLimit(), this.getOrderAscending(),
addtlWhereSelect_1, addtlWhereSelect_2,
evRcdHandler);
} catch (DBException dbe) {
Print.logException("Unable to obtain EventData records", dbe);
}
/* no events? */
if (ed == null) {
return EventData.EMPTY_ARRAY;
}
/* update device */
if (deviceDB != null) {
// -- set device in each retrieved event
for (int i = 0; i < ed.length; i++) {
ed[i].setDevice(deviceDB);
}
}
/* return events */
return ed;
}
// ------------------------------------------------------------------------
/**
*** Returns the actual counted EventData records from the last query (including all devices)
**/
public long getEventDataCount()
{
return (long)this.eventDataCount;
}
/**
*** Returns the number of EventData records matched by "isEventDataMatch()", or the rule selector.
**/
public long getEventMatchCount()
{
return (long)this.eventMatchCount;
}
/**
*** Return the largest counted EventData records from the last query for a single device
**/
public long getMaximumEventDataCount()
{
return (long)this.maxEventDataCount;
}
/**
*** Returns the count of EventData records based on the EventData constraints
**/
protected long countEventData(Device deviceDB)
{
long timeStart = this.getTimeStart();
long timeEnd = this.getTimeEnd();
return this._countEventData(deviceDB, timeStart, timeEnd);
}
/**
*** Returns the count of EventData records based on the EventData constraints
**/
protected long countEventData(Device deviceDB, long timeStart, long timeEnd)
{
return this._countEventData(deviceDB, timeStart, timeEnd);
}
/* return the count of EventData records based on the EventData constraints */
//protected long _countEventData(Device deviceDB)
//{
// long timeStart = this.getTimeStart();
// long timeEnd = this.getTimeEnd();
// return this._countEventData(deviceDB, timeStart, timeEnd);
//}
/**
*** Returns the count of EventData records based on the EventData constraints
**/
protected long _countEventData(Device deviceDB, long timeStart, long timeEnd)
{
/* Device */
if (deviceDB == null) {
return 0L;
}
/* Account */
String accountID = this.getAccountID();
//Print.logInfo("Getting EventData for " + accountID + "/" + deviceID);
/* EventData rule selector */
// (not supported)
final String ruleSelector = this.getRuleSelector();
if ((ruleSelector != null) && !ruleSelector.equals("")) {
Print.logWarn("RuleSelector not supported when obtaining EventData record counts!");
}
/* get events */
long recordCount = 0L;
try {
recordCount = EventData.countRangeEvents(
accountID, deviceDB.getDeviceID(),
timeStart, timeEnd,
this.getStatusCodes(),
this.getValidGPSRequired(),
this.getSelectionLimitType(), this.getSelectionLimit(),
this.getWhereSelector());
} catch (DBException dbe) {
Print.logException("Unable to obtain EventData record count", dbe);
}
/* return events */
return recordCount;
}
// ------------------------------------------------------------------------
// Report Reord Count
/**
*** Sets the report record count
**/
public void setReportRecordCount(int count, boolean isPartial)
{
this.rptRecordCount = count;
this.rptIsPartial = isPartial;
}
/**
*** Gets the report record count
**/
public int getReportRecordCount()
{
return this.rptRecordCount;
}
/**
*** Returns true if the actual number of report records would have exceeded
*** the maximum nuber of allowed report records, indicating that this report
*** contains only partial data.
**/
public boolean getReportIsPartial()
{
return this.rptIsPartial;
}
// ------------------------------------------------------------------------
// Auto Report URL
/**
*** Set the auto report URL
**/
public void setAutoReportURL(URIArg autoReportURL)
{
this.autoReportURL = autoReportURL;
}
/**
*** Get the auto report URL
**/
public URIArg getAutoReportURL()
{
return this.autoReportURL;
}
// ------------------------------------------------------------------------
// Graph
/**
*** Returns true if this report supports displaying a graph
*** @return True if this report supports displaying a graph, false otherwise
**/
public boolean getSupportsGraphDisplay()
{
// -- override in subclass
return false;
}
/**
*** Writes any required report JavaScript
**/
public void writeJavaScript(PrintWriter pw, RequestProperties reqState)
throws IOException
{
// -- override in subclass
}
/**
*** Writes the report html body content
**/
public void writeHtmlBody(PrintWriter pw, RequestProperties reqState)
throws IOException
{
// -- override in subclass
}
/**
*** Gets the Graph link description (if any)
**/
public String getGraphLinkDescription()
{
return null;
}
/**
*** Gets the Graph window size
**/
public MapDimension getGraphWindowSize()
{
return new MapDimension(730,440);
}
// ------------------------------------------------------------------------
// Graph URL
/**
*** Sets the Graph image URL (OBSOLETE)
**/
public void setGraphImageURL(URIArg graphURL)
{
if (this.getSupportsGraphDisplay()) {
this.graphImageURL = graphURL;
}
}
/**
*** Sets the Graph image URL (OBSOLETE)
**/
public URIArg getGraphImageURL() // OBSOLETE
{
return this.getSupportsGraphDisplay()? this.graphImageURL : null;
}
// ------------------------------------------------------------------------
// Map URL
/**
*** Returns true if this report supports displaying a map
*** @return True if this report supports displaying a map, false otherwise
**/
public boolean getSupportsMapDisplay()
{
// -- override in subclass
return false;
}
/**
*** Returns true if the map route-line is to be displayed, false otherwise
*** @param isFleet True if this maps represents a Group/Fleet of devices
**/
public boolean showMapRouteLine(boolean isFleet)
{
// -- default to show route-line if not a Fleet/Group map
return isFleet? false : true;
}
/**
*** Sets the Map URL
**/
public void setMapURL(URIArg mapURL)
{
if (this.getSupportsMapDisplay()) {
this.mapURL = mapURL;
//Print.logInfo("Map URL: " + this.mapURL);
}
}
/**
*** Gets the Map URL
**/
public URIArg getMapURL()
{
return this.getSupportsMapDisplay()? this.mapURL : null;
}
/**
*** Returns true if the Map URL has been defined
**/
public boolean hasMapURL()
{
return !StringTools.isBlank(this.getMapURL())? true : false;
}
/**
*** Gets the Map link description
**/
public String getMapLinkDescription()
{
return null;
}
/**
*** Gets the Map window size
**/
public MapDimension getMapWindowSize()
{
return new MapDimension(700,500);
}
// ------------------------------------------------------------------------
// KML URL
/**
*** Returns true if this report supports displaying KML
*** @return True if this report supports displaying KML, false otherwise
**/
public boolean getSupportsKmlDisplay()
{
// -- override in subclass
return false;
}
/**
*** Sets the Google KML URL
**/
public void setKmlURL(URIArg kmlURL)
{
if (this.getSupportsKmlDisplay()) {
this.kmlURL = kmlURL;
//Print.logInfo("KML URL: " + this.kmlURL);
}
}
/**
*** Gets the Google KML URL
**/
public URIArg getKmlURL()
{
return this.getSupportsKmlDisplay()? this.kmlURL : null;
}
/**
*** Gets the Google KML link description
**/
public String getKmlLinkDescription()
{
return null;
}
// ------------------------------------------------------------------------
// Refresh URL
/**
*** Returns true id the refresh-url has been defined
**/
public boolean hasRefreshURL()
{
return !StringTools.isBlank(this.refreshURL)? true : false;
}
/**
*** Sets the report refresh URL
**/
public void setRefreshURL(URIArg refreshURL)
{
this.refreshURL = refreshURL;
//Print.logInfo("Refresh URL: " + this.refreshURL);
}
/**
*** Gets the report refresh URL
**/
public URIArg getRefreshURL()
{
return this.refreshURL;
}
// ------------------------------------------------------------------------
// Start report
/**
*** This method is called after all other ReportConstraints have been set.
*** The report has this opportunity to make any changes to the ReportConstraints
*** before the report is actually generated
**/
public void postInitialize()
{
// last oportunity for the report to configure itself before actually writing out data
// To prevent requireing that the subclass call "super.postInitialize()" it is
// strongly recommended that this placeholder method always be empty.
}
// ------------------------------------------------------------------------
// ReportLayout
/**
*** Gets the report layout
**/
public abstract ReportLayout getReportLayout();
// ------------------------------------------------------------------------
// DataRow
/**
*** Gets the DataRowTemplate instance
**/
public DataRowTemplate getDataRowTemplate()
{
return this.getReportLayout().getDataRowTemplate();
}
// ------------------------------------------------------------------------
/**
*** Writes report style attributes
**/
public void writeReportStyle(String format, OutputProvider out)
throws ReportException
{
String fmt = StringTools.blankDefault(format, this.getPreferredFormat());
this.getReportLayout().writeReportStyle(fmt, this, out, 0);
}
/**
*** Writes the report
**/
public int writeReport(String format, OutputProvider out)
throws ReportException
{
String fmt = StringTools.blankDefault(format, this.getPreferredFormat());
return this.getReportLayout().writeReport(fmt, this, out, 0);
}
/**
*** Writes the report
**/
public int writeReport(String format, OutputProvider out, int indentLevel)
throws ReportException
{
String fmt = StringTools.blankDefault(format, this.getPreferredFormat());
return this.getReportLayout().writeReport(fmt, this, out, indentLevel);
}
// ------------------------------------------------------------------------
// DBDataIterator
/**
*** Gets the details data interator for this report.<br>
*** The subclass of this object must implement this method.<br>
*** For simple EventData record data, this method could simply return:<br>
*** new ArrayDataIterator(this.getEventData_DeviceList());
**/
public abstract DBDataIterator getBodyDataIterator();
/**
*** Gets the totals data interator for this report.<br>
*** The subclass of this object must implement this method.<br>
*** For simple EventData record data, this method may simply return null.
**/
public abstract DBDataIterator getTotalsDataIterator();
/**
*** This is an implementation of DBDataIterator that iterates through an array of row objects
**/
public class ArrayDataIterator
implements DBDataIterator
{
private int recordIndex = -1;
private Object data[] = null;
private Object dataObj = null;
private DBDataRow dataRow = null;
public ArrayDataIterator(Object data[]) {
this.data = data;
this.recordIndex = -1;
this.dataRow = new DBDataRowAdapter(ReportData.this) {
public Object getRowObject() {
return ArrayDataIterator.this.dataObj;
}
public Object getDBValue(String name, int rowNdx, ReportColumn rptCol) {
Object obj = ArrayDataIterator.this.dataObj;
if (obj != null) {
DataRowTemplate drt = ReportData.this.getDataRowTemplate();
return drt.getFieldValue(name, rowNdx, ReportData.this, rptCol, obj); // DataRowTemplate.getFieldValue
} else {
return "";
}
}
};
}
public Object[] getArray() {
return this.data;
}
public boolean hasNext() {
return (this.data != null) && ((this.recordIndex + 1) < this.data.length);
}
public DBDataRow next() {
if (this.hasNext()) {
this.recordIndex++;
this.dataObj = this.data[this.recordIndex];
return this.dataRow;
} else {
this.dataObj = null;
return null;
}
}
}
/**
*** This is an implementation of DBDataIterator that iterates through an array of row objects
**/
protected class ListDataIterator
implements DBDataIterator
{
private Iterator<?> dataIter = null;
private Object dataObj = null;
private DBDataRow dataRow = null;
public ListDataIterator(java.util.List<?> data) {
this.dataIter = (data != null)? data.iterator() : null;
this.dataRow = new DBDataRowAdapter(ReportData.this) {
public Object getRowObject() {
return ListDataIterator.this.dataObj;
}
public Object getDBValue(String name, int rowNdx, ReportColumn rptCol) {
Object obj = ListDataIterator.this.dataObj;
if (obj != null) {
DataRowTemplate rdp = ReportData.this.getDataRowTemplate();
return rdp.getFieldValue(name, rowNdx, ReportData.this, rptCol, obj); // DataRowTemplate.getFieldValue
} else {
return "";
}
}
};
}
public boolean hasNext() {
return (this.dataIter != null) && this.dataIter.hasNext();
}
public DBDataRow next() {
if (this.hasNext()) {
this.dataObj = this.dataIter.next();
return this.dataRow;
} else {
this.dataObj = null;
return null;
}
}
}
// ------------------------------------------------------------------------
}
| 32.710056 | 126 | 0.541207 |
378a085779f3bb15fdd1d774a6a68a1af9221a34 | 2,019 | package leetcode.medium;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class P_220 {
public boolean containsNearbyAlmostDuplicateTS(int[] nums, int k, int t) {
if (t < 0) { return false; }
final TreeSet<Integer> ts = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
if (!ts.add(nums[i])) {
return true;
}
final Integer higher = ts.higher(nums[i]);
final Integer lower = ts.lower(nums[i]);
if (higher != null && higher <= t + nums[i]) {
return true;
}
if (lower != null && nums[i] <= t + lower) {
return true;
}
if (ts.size() > k) {
ts.remove(nums[i - k]);
}
}
return false;
}
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (t <= 0) { return t == 0 ? containsNearbyDuplicate(nums, k) : false; }
final Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
final int m = Math.floorDiv(nums[i], t);
if (map.containsKey(m)
|| (map.containsKey(m - 1) && Math.abs(nums[i] - map.get(m - 1)) <= t)
|| (map.containsKey(m + 1) && Math.abs(nums[i] - map.get(m + 1)) <= t)) {
return true;
}
map.put(m, nums[i]);
if (i >= k) {
map.remove(Math.floorDiv(nums[i - k], t));
}
}
return false;
}
public boolean containsNearbyDuplicate(int[] nums, int k) {
final Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!set.add(nums[i])) {
return true;
}
if (set.size() > k) {
set.remove(nums[i - k]);
}
}
return false;
}
}
| 31.546875 | 89 | 0.463101 |
bc71517f216b8dc358c2d0ae3ad6a719e9a3ea40 | 3,969 | package uk.gov.hmcts.reform.iacaseapi.component.testutils.wiremock;
import static uk.gov.hmcts.reform.iacaseapi.component.testutils.fixtures.AsylumCaseForTest.anAsylumCase;
import static uk.gov.hmcts.reform.iacaseapi.component.testutils.fixtures.PreSubmitCallbackResponseForTest.PreSubmitCallbackResponseForTestBuilder.someCallbackResponseWith;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import uk.gov.hmcts.reform.iacaseapi.component.testutils.fixtures.AsylumCaseForTest;
import uk.gov.hmcts.reform.iacaseapi.component.testutils.fixtures.PreSubmitCallbackResponseForTest;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCase;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.Callback;
public class DocumentsApiCallbackTransformer extends ResponseDefinitionTransformer {
private ObjectMapper objectMapper = new ObjectMapper();
private Map<String, Object> additionalAsylumCaseData = new HashMap<>();
public DocumentsApiCallbackTransformer() {
objectMapper.registerModule(new Jdk8Module());
objectMapper.registerModule(new JavaTimeModule());
}
@Override
public ResponseDefinition transform(
Request request,
ResponseDefinition responseDefinition,
FileSource files,
Parameters parameters
) {
Callback<AsylumCase> asylumCaseCallback = readValue(
request,
new TypeReference<Callback<AsylumCase>>() {});
AsylumCase incomingAsylumCase = asylumCaseCallback
.getCaseDetails()
.getCaseData();
AsylumCaseForTest asylumCaseToBeReturned = anAsylumCase()
.withCaseDetails(incomingAsylumCase)
.writeOrOverwrite(additionalAsylumCaseData);
PreSubmitCallbackResponseForTest preSubmitCallbackResponseForTest =
someCallbackResponseWith()
.data(asylumCaseToBeReturned)
.build();
ResponseDefinitionBuilder responseDefinitionBuilder = new ResponseDefinitionBuilder()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(
writeValue(
preSubmitCallbackResponseForTest));
return responseDefinitionBuilder.build();
}
@Override
public String getName() {
return "ia-case-documents-api-transformer";
}
@Override
public boolean applyGlobally() {
return false;
}
public void addAdditionalAsylumCaseData(
String fieldname,
Object value
) {
additionalAsylumCaseData.put(fieldname, value);
}
private String writeValue(PreSubmitCallbackResponseForTest preSubmitCallbackResponseForTest) {
try {
return objectMapper.writeValueAsString(preSubmitCallbackResponseForTest);
} catch (JsonProcessingException e) {
throw new RuntimeException("Json parsing exception", e);
}
}
private Callback<AsylumCase> readValue(Request request, TypeReference<Callback<AsylumCase>> typeRef) {
try {
return objectMapper.readValue(request.getBodyAsString(), typeRef);
} catch (IOException e) {
throw new RuntimeException("Json parsing exception", e);
}
}
}
| 38.911765 | 171 | 0.736458 |
763bdd736e8dd3a9c93042b1cc51f6dcceb364b5 | 2,188 | /**
* Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.core.cli.operations;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.locationtech.geowave.core.cli.VersionUtils;
import org.locationtech.geowave.core.cli.annotations.GeowaveOperation;
import org.locationtech.geowave.core.cli.api.DefaultOperation;
import org.locationtech.geowave.core.cli.api.OperationParams;
import org.locationtech.geowave.core.cli.operations.config.options.ConfigOptions;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
@GeowaveOperation(name = "geowave")
@Parameters(commandDescription = "This is the top level section.")
public class GeowaveTopLevelSection extends DefaultOperation {
@Parameter(names = "--debug", description = "Verbose output")
private Boolean verboseFlag;
@Parameter(names = "--version", description = "Output Geowave build version information")
private Boolean versionFlag;
// This contains methods and parameters for determining where the GeoWave
// cached configuration file is.
@ParametersDelegate
private ConfigOptions options = new ConfigOptions();
@Override
public boolean prepare(final OperationParams inputParams) {
// This will load the properties file parameter into the
// operation params.
options.prepare(inputParams);
super.prepare(inputParams);
// Up the log level
if (Boolean.TRUE.equals(verboseFlag)) {
LogManager.getRootLogger().setLevel(Level.DEBUG);
}
// Print out the version info if requested.
if (Boolean.TRUE.equals(versionFlag)) {
VersionUtils.printVersionInfo();
// Do not continue
return false;
}
// Successfully prepared
return true;
}
}
| 36.466667 | 100 | 0.765082 |
04e96e7b37ce1a7e2bda67ebe02d7bb99784950e | 1,573 | package com.noah.solutions.system.repository;
import com.noah.solutions.system.entity.OrderRecord;
import com.noah.solutions.system.view.UserOrderNewRecordView;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Set;
@Repository
public interface OrderRecordRepository extends JpaRepository<OrderRecord,String> {
Set<OrderRecord> findAllByOrderIdOrderByIdDesc(String orderId);
List<OrderRecord> findAllByOrderId(String orderId, Pageable pageable);
@Query("select new OrderRecord(u.nickName,od) from OrderRecord od inner join com.noah.solutions.system.entity.User u on od.operatorId=u.userId where od.orderId=?1 order by od.createTime desc,od.id desc ")
List<OrderRecord> selectAllByOrderId(String orderId);
OrderRecord findFirstByOrderIdOrderByCreateTimeDesc(String orderId);
//// @Query("select new com.noah.solutions.system.view.UserOrderNewRecordView(o.orderNo,or.title,or.tbExplain,or.createTime,or.courier) from OrderRecord or inner join com.noah.solutions.system.entity.Order o on or.orderId = o.orderId where o.orderState <> ?1")
// @Query(value = "select new OrderRecord(u.nickName,od) from OrderRecord od inner join (select o.order_id,o.order_no from tb_order o where o.orderState <> ?1 limit ?2,?3",nativeQuery = true)
// List<UserOrderNewRecordView> findAllNewRecord(Integer orderState,Integer page,Integer limit);
}
| 56.178571 | 265 | 0.800381 |
e323ea039ee726634d05691f43f67199324fc93a | 17,320 | package com.kiven.kutils.logHelper;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.kiven.kutils.R;
import com.kiven.kutils.activityHelper.KActivityHelper;
import com.kiven.kutils.activityHelper.KHelperActivity;
import com.kiven.kutils.tools.KFile;
import com.kiven.kutils.tools.KAlertDialogHelper;
import com.kiven.kutils.tools.KGranting;
import com.kiven.kutils.tools.KString;
import com.kiven.kutils.tools.KUtil;
import com.kiven.kutils.tools.KView;
import com.kiven.kutils.widget.UIGridView;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class AHFileManager extends KActivityHelper {
private GridViewAdapter gridViewAdapter = new GridViewAdapter();
private final ArrayList<LFile> modules = new ArrayList<>();
// 选择的文件路径
private final ArrayList<LFile> selDir = new ArrayList<>();
private final MyAdapter childAdapter = new MyAdapter();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (!KGranting.useFragmentRequest)
KGranting.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onCreate(@NonNull KHelperActivity activity, Bundle savedInstanceState) {
super.onCreate(activity, savedInstanceState);
activity.setTheme(R.style.KTheme);
setContentView(R.layout.k_ah_file_manager);
initBackToolbar(R.id.toolbar, true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
childAdapter.notifyDataSetChanged();
} else {
KGranting.requestPermissions(mActivity, 345, Manifest.permission.WRITE_EXTERNAL_STORAGE, "存储空间", new KGranting.GrantingCallBack() {
@Override
public void onGrantSuccess(boolean isSuccess) {
if (isSuccess) {
// 刷新列表
childAdapter.notifyDataSetChanged();
}
}
});
}
modules.add(new LFile("应用内部", mActivity.getFilesDir().getParentFile()));
File cf = mActivity.getExternalCacheDir().getParentFile();
if (cf != null) {
modules.add(new LFile("应用外部", cf));
}
modules.add(new LFile("/system", Environment.getRootDirectory()));
modules.add(new LFile("/data", Environment.getDataDirectory()));
modules.add(new LFile("系统根目录", new File("/")));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
modules.add(new LFile("/storage", Environment.getStorageDirectory()));
}
modules.add(new LFile("系统内部存储", Environment.getExternalStorageDirectory()));
modules.add(new LFile("相册", new File(Environment.getExternalStorageDirectory(), "Pictures")));
modules.add(new LFile("sourceDir", new File(mActivity.getApplicationInfo().sourceDir)));
modules.add(new LFile("publicSourceDir", new File(mActivity.getApplicationInfo().publicSourceDir)));
modules.add(new LFile("nativeLibraryDir", new File(mActivity.getApplicationInfo().nativeLibraryDir)));
modules.add(new LFile("dataDir", new File(mActivity.getApplicationInfo().dataDir)));
UIGridView gridView = findViewById(R.id.uiGridView);
gridView.setAdapter(gridViewAdapter);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
{
try {
Class.forName("com.google.android.flexbox.FlexboxLayoutManager");
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(mActivity);
layoutManager.setFlexDirection(FlexDirection.ROW);
layoutManager.setJustifyContent(JustifyContent.CENTER);
recyclerView.setLayoutManager(layoutManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
recyclerView.setLayoutManager(new GridLayoutManager(mActivity, KUtil.getScreenWith() / KUtil.dip2px(50f)));
}
}
recyclerView.setAdapter(childAdapter);
onSelectedDir();
}
private void onSelectedDir() {
if (selDir.size() > 0) {
LFile file = selDir.get(selDir.size() - 1);
File[] childs = file.listFiles();
if (childs != null && childs.length > 1)
Arrays.sort(childs, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
boolean dir1 = o1.isDirectory();
boolean dir2 = o2.isDirectory();
if (dir1 == dir2) {
return o1.compareTo(o2);
} else {
if (dir1) return -1;
}
return 0;
}
});
childAdapter.refreshData(childs);
} else {
childAdapter.refreshData(modules);
}
gridViewAdapter.notifyDataSetChanged();
}
/**
* 点击系统返回按钮时
*/
@Override
public boolean onBackPressed() {
if (selDir.size() > 0) {
selDir.remove(selDir.size() - 1);
onSelectedDir();
return false;
}
return super.onBackPressed();
}
private class GridViewAdapter extends UIGridView.Adapter implements View.OnClickListener {
@Override
public int getGridViewItemCount() {
return selDir.size() + 1;
}
@Override
public View getItemView(Context context, View itemView, ViewGroup parentView, int position) {
TextView tv;
if (itemView == null) {
tv = new TextView(mActivity);
tv.setPadding(10, 10, 10, 10);
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.k_right_arrow, 0);
tv.setCompoundDrawablePadding(10);
tv.setOnClickListener(this);
} else {
tv = (TextView) itemView;
}
if (position < 1) {
tv.setText("多根");
} else {
tv.setText(selDir.get(position - 1).name);
}
tv.setTag(position);
return tv;
}
@Override
public void onClick(View v) {
int position = (int) v.getTag();
List<LFile> rf = new ArrayList<>();
for (int i = position; i < selDir.size(); i++) {
rf.add(selDir.get(i));
}
selDir.removeAll(rf);
onSelectedDir();
}
}
private class MyHolder extends RecyclerView.ViewHolder {
ImageView imageView;
ImageView iv_unread;
TextView tv_num;
void showImage() {
ImageView iv = new ImageView(mActivity);
iv.setAdjustViewBounds(true);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.setImageBitmap(BitmapFactory.decodeFile(cFile.getAbsolutePath()));
new AlertDialog.Builder(mActivity).setView(iv).show();
}
MyHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
iv_unread = itemView.findViewById(R.id.iv_unread);
tv_num = itemView.findViewById(R.id.tv_num);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (cFile.canRead())
KAlertDialogHelper.Show2BDialog(mActivity, "是否删除文件?", new View.OnClickListener() {
@Override
public void onClick(View v) {
KUtil.deleteFile(cFile, true);
onSelectedDir();
}
});
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
KLog.i("点击文件 = " + cFile.getAbsolutePath() + "\n修改时间 = " + KString.formatDate(cFile.lastModified()) +
"\n文件大小 = " + Formatter.formatFileSize(mActivity, cFile.length()));
if (cFile.canRead()) {
if (cFile.isDirectory()) {
selDir.add(cFile);
onSelectedDir();
} else {
if (KFile.checkFileType(cFile) != KFile.FileType.UNKNOWN) {
showImage();
} else
new MaterialAlertDialogBuilder(mActivity)
.setTitle("选择打开方式").setMessage("文件大小" + Formatter.formatFileSize(mActivity, cFile.length()))
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNeutralButton("图片", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showImage();
}
})
.setPositiveButton("文档", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cFile.length() / 1024 > 100) {
KAlertDialogHelper.Show1BDialog(mActivity, "文件太大了,会卡!");
} else {
new AlertDialog.Builder(mActivity)
.setTitle("选择编码")
.setItems(new CharSequence[]{
"UTF-8", "US_ASCII", "ISO-8859-1", "UTF-16", "UTF-16BE", "UTF-16LE"
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Charset charset;
switch (which) {
case 1:
charset = Charset.forName("US_ASCII");
break;
case 2:
charset = Charset.forName("ISO-8859-1");
break;
case 3:
charset = Charset.forName("UTF-16");
break;
case 4:
charset = Charset.forName("UTF-16BE");
break;
case 5:
charset = Charset.forName("UTF-16LE");
break;
default:
charset = Charset.forName("UTF-8");
}
ScrollView scrollView = new ScrollView(mActivity);
TextView tv = new TextView(mActivity);
scrollView.addView(tv);
tv.setText(KFile.readFile(cFile, charset));
new AlertDialog.Builder(mActivity).setView(scrollView).show();
}
}).show();
}
}
})
.show();
}
}
}
});
}
LFile cFile;
public void bindData(LFile file) {
cFile = file;
if (file.isDirectory()) {
imageView.setImageResource(android.R.drawable.ic_dialog_email);
} else {
if (KFile.checkFileType(cFile) != KFile.FileType.UNKNOWN) {
// x.image().bind(imageView, cFile.getAbsolutePath());
imageView.setImageBitmap(BitmapFactory.decodeFile(cFile.getAbsolutePath()));
} else
imageView.setImageResource(android.R.drawable.ic_menu_gallery);
}
KView.setVisibility(iv_unread, !file.canRead());
tv_num.setText(file.name);
}
}
private class MyAdapter extends RecyclerView.Adapter<MyHolder> {
// 选择的文件夹下的所有文件
private final ArrayList<LFile> childFiles = new ArrayList<>();
void refreshData(@NonNull List<LFile> datas) {
childFiles.clear();
childFiles.addAll(datas);
notifyDataSetChanged();
}
void refreshData(File[] datas) {
childFiles.clear();
if (datas != null && datas.length > 0)
for (File cf : datas) {
childFiles.add(new LFile(cf));
}
notifyDataSetChanged();
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(mActivity).inflate(R.layout.k_item_res, parent, false));
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
holder.bindData(childFiles.get(position));
}
@Override
public int getItemCount() {
return childFiles.size();
}
}
private static class LFile extends File {
String name = "";
LFile(@NonNull String name, @NonNull File file) {
this(file.getPath());
this.name = name;
}
LFile(@NonNull File file) {
this(file.getPath());
name = file.getName();
}
LFile(@NonNull String pathname) {
super(pathname);
}
LFile(String parent, @NonNull String child) {
super(parent, child);
}
LFile(File parent, @NonNull String child) {
super(parent, child);
}
LFile(@NonNull URI uri) {
super(uri);
}
}
}
| 41.336516 | 143 | 0.480658 |
8ad3070266122c85185f313630298bca789ec4ce | 1,706 | package aungpyaephyo.net.phandeeyarlivecoding.views;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import aungpyaephyo.net.phandeeyarlivecoding.R;
import aungpyaephyo.net.phandeeyarlivecoding.data.vos.EventVO;
/**
* Created by aung on 2/28/16.
*/
public class ViewItemEvent extends CardView {
private TextView tvEventTitle;
private ImageView ivStockPhoto;
private TextView tvEventDesc;
private TextView tvEventTime;
public ViewItemEvent(Context context) {
super(context);
}
public ViewItemEvent(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewItemEvent(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
tvEventTitle = (TextView) findViewById(R.id.tv_event_title);
ivStockPhoto = (ImageView) findViewById(R.id.iv_stock_photo);
tvEventDesc = (TextView) findViewById(R.id.tv_event_desc);
tvEventTime = (TextView) findViewById(R.id.tv_event_time);
}
public void setData(EventVO event) {
tvEventTitle.setText(event.getEventTitle());
tvEventDesc.setText(event.getEventDesc());
tvEventTime.setText(event.getEventDateTime());
Glide.with(getContext())
.load(event.getStockPhoto()) //url.
.centerCrop()
.placeholder(R.drawable.stock_photo_placeholder)
.into(ivStockPhoto);
}
}
| 28.915254 | 81 | 0.69871 |
598daec6583b83ef6a4ece8ec9c99ade435264d8 | 1,883 | /*
* Copyright 2019 (c) Tim Langhammer
*
* 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 earth.eu.jtzipi.jpp.map;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author jTzipi
*/
public class PenAndPaperSite implements IPenAndPaperSite {
private String name;
private List<IPenAndPaperMap> levelMapL;
PenAndPaperSite( final String nameStr, final List<IPenAndPaperMap> penAndPaperMapList ) {
this.name = nameStr;
this.levelMapL = penAndPaperMapList;
}
PenAndPaperSite ( final String nameStr ) {
this(nameStr, new ArrayList<>() );
}
@Override
public String getName() {
return name;
}
@Override
public List<IPenAndPaperMap> getLevelMaps() {
return levelMapL;
}
public static PenAndPaperSite of( String nameStr ) {
return new PenAndPaperSite( nameStr );
}
@Override
public void removeMap( IPenAndPaperMap map ) {
if( null == map ) {
}
this.levelMapL.remove( map );
}
/**
* Add a new map to this site.
* @param map map
* @throws NullPointerException if {@code map}
*/
@Override
public void addMap(final IPenAndPaperMap map) {
Objects.requireNonNull( map );
this.levelMapL.add( map );
}
}
| 23.835443 | 93 | 0.651089 |
886853a7140b2792ebdffa355fdc495f57e3a034 | 163 | package com.example.c;
import com.example.a.A;
import com.example.b.B;
public class C extends B {
A a;
public static void badUseOfA() {
A.onlyInB();
}
}
| 10.866667 | 33 | 0.668712 |
3333cfde95fe329d4c712c4080f16be4dd932f3c | 301 | package p;
public class Annotation1_in {
public void foo() {
Cell1 c = Cell1.createCell1();
}
}
@interface Preliminary {
}
class Cell1 {
public static Cell1 createCell1() {
return new Cell1();
}
@Preliminary
private Cell1() /*[*/
/*]*/
{
}
}
| 12.04 | 39 | 0.541528 |
e1df0ecd7b8c63a94e9fae0e2fe3f6e7c393dbd0 | 6,223 | package edu.umd.lib.ole.profile;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.kuali.ole.batch.bo.OLEBatchProcessProfileBo;
import org.kuali.ole.batch.bo.xstream.OLEBatchProcessProfileRecordProcessor;
import org.kuali.ole.sys.context.SpringContext;
import org.kuali.rice.krad.service.LookupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.Version;
/**
* Servlet for exporting a OLE Batch Process Profile to XML.
*/
public class ProfileExportServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(ProfileExportServlet.class);
private static Configuration freeMarkerCfg;
/**
* Sets up FreeMarker configuration.
*/
@Override
public void init() throws ServletException {
super.init();
// Set up FreeMarker configuration
freeMarkerCfg = new Configuration();
freeMarkerCfg.setClassForTemplateLoading(this.getClass(), "");
freeMarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
freeMarkerCfg.setDefaultEncoding("UTF-8");
freeMarkerCfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
freeMarkerCfg.setIncompatibleImprovements(new Version(2, 3, 20)); // FreeMarker 2.3.20
}
/**
* Responds to GET requests. If a request parameter of "profileName" is
* provided, will attempt to return a profile with that name, otherwise
* an HTML form will be displayed.
*
* @param request the HttpServletRequest containing the request parameters
* @param response the HttpServletResponse for the server response.
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O exception occurs.
*/
public void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String profileName = request.getParameter("profileName");
if( profileName == null )
{
sendExportRequestForm(request, response);
} else {
sendProfile( profileName, response );
}
}
/**
* Responds with an HTML form to specify the profile to export.
*
* @param request the HttpServletRequest containing the request parameters
* @param response the HttpServletResponse for the server response.
*/
private void sendExportRequestForm( HttpServletRequest request,
HttpServletResponse response) {
try {
Writer out = response.getWriter();
Template temp = freeMarkerCfg.getTemplate("exportRequestForm.ftl");
temp.process(null, out);
} catch (TemplateException e) {
LOG.error("Error processing template", e);
} catch( IOException ioe ) {
LOG.error("Error writing response", ioe);
}
}
/**
* If a profile with the given name is found, responds with the profile,
* otherwise an HTML page describing the error is returned.
*
* @param profileName
* @param response
* @throws IOException
*/
void sendProfile( String profileName,
HttpServletResponse response)
throws IOException
{
LOG.debug("sendProfile: profileName=" + profileName);
List<String> errors = new ArrayList<String>();
SpringContext.getBean(LookupService.class);
LookupService lookup = SpringContext.getBean(LookupService.class);
Collection<OLEBatchProcessProfileBo> c = lookup.findCollectionBySearchHelper(
OLEBatchProcessProfileBo.class, new HashMap<String, String>(), true);
boolean profileFound = false;
for( Iterator<OLEBatchProcessProfileBo> it = c.iterator(); it.hasNext(); ) {
OLEBatchProcessProfileBo profile = it.next();
if ( profile.getBatchProcessProfileName().equals(profileName) )
{
response.setContentType("text/xml");
response.setHeader("Content-Disposition",
"attachment; filename=" + profileName +".xml");
PrintWriter out = response.getWriter();
OLEBatchProcessProfileRecordProcessor rp =
new OLEBatchProcessProfileRecordProcessor();
out.println(rp.toXml(profile));
profileFound = true;
out.flush();
LOG.info("sendProfile: " + profileName + " successfully exported.");
return;
}
}
// Error handling
if (!profileFound) {
errors.add("Could not find a profile named '" + profileName + "'");
}
if ( LOG.isWarnEnabled() ) {
LOG.warn("sendProfile: Could not export profile named \"" + profileName + "\".");
LOG.warn("sendProfile: The following errors occurred:");
for( String error: errors )
{
LOG.warn("\t"+error);
}
}
Map<String, List<String>> templateParams = new HashMap<String,List<String>>();
templateParams.put("errors", errors);
Template temp = freeMarkerCfg.getTemplate("error.ftl");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
temp.process(templateParams, out);
} catch (TemplateException e) {
LOG.error("Error processing template", e);
}
}
/**
* Delegates all POST requests to doGet method.
*
* @param request the HttpServletRequest containing the request parameters
* @param response the HttpServletResponse for the server response.
* @throws ServletException if the request cannot be handled
* @throws IOException if an I/O exception occurs.
*/
public void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet( request, response );
}
}
| 33.637838 | 93 | 0.708661 |
093258f4e7dab5ff9fc78cb05edd7eaa599ee7ba | 937 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.client4j.permissions.groups;
import com.client4j.permissions.PermissionPattern;
import com.client4j.permissions.PermissionsGroup;
/**
*
* @author shannah
*/
public class PreferencesPermissionsGroup extends PermissionsGroup {
public PreferencesPermissionsGroup() {
setName("Access to Preferences");
setDescription("This app has requested access to the Java Preferences API. This API is shared accross all apps within the same installation of Java so it may potentially allow this app to access the preference settings for other apps that you have installed. Only grant this if you trust the application");
getPatterns(true).add(new PermissionPattern("java.lang.RuntimePermission", "preferences"));
}
}
| 42.590909 | 316 | 0.766275 |
83c54e100696590eb2c7bc362da4a0d424a3d070 | 3,250 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.10
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.gdal.ogr;
import org.gdal.osr.SpatialReference;
public class GeomFieldDefn {
private long swigCPtr;
protected boolean swigCMemOwn;
protected GeomFieldDefn(long cPtr, boolean cMemoryOwn) {
if (cPtr == 0)
throw new RuntimeException();
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(GeomFieldDefn obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
ogrJNI.delete_GeomFieldDefn(swigCPtr);
}
swigCPtr = 0;
}
}
private Object parentReference;
protected static long getCPtrAndDisown(GeomFieldDefn obj) {
if (obj != null)
{
obj.swigCMemOwn= false;
obj.parentReference = null;
}
return getCPtr(obj);
}
/* Ensure that the GC doesn't collect any parent instance set from Java */
protected void addReference(Object reference) {
parentReference = reference;
}
public boolean equals(Object obj) {
boolean equal = false;
if (obj instanceof GeomFieldDefn)
equal = (((GeomFieldDefn)obj).swigCPtr == this.swigCPtr);
return equal;
}
public int hashCode() {
return (int)swigCPtr;
}
public GeomFieldDefn(String name_null_ok, int field_type) {
this(ogrJNI.new_GeomFieldDefn__SWIG_0(name_null_ok, field_type), true);
}
public GeomFieldDefn(String name_null_ok) {
this(ogrJNI.new_GeomFieldDefn__SWIG_1(name_null_ok), true);
}
public GeomFieldDefn() {
this(ogrJNI.new_GeomFieldDefn__SWIG_2(), true);
}
public String GetName() {
return ogrJNI.GeomFieldDefn_GetName(swigCPtr, this);
}
public String GetNameRef() {
return ogrJNI.GeomFieldDefn_GetNameRef(swigCPtr, this);
}
public void SetName(String name) {
ogrJNI.GeomFieldDefn_SetName(swigCPtr, this, name);
}
public int GetFieldType() {
return ogrJNI.GeomFieldDefn_GetFieldType(swigCPtr, this);
}
public void SetType(int type) {
ogrJNI.GeomFieldDefn_SetType(swigCPtr, this, type);
}
public SpatialReference GetSpatialRef() {
long cPtr = ogrJNI.GeomFieldDefn_GetSpatialRef(swigCPtr, this);
return (cPtr == 0) ? null : new SpatialReference(cPtr, true);
}
public void SetSpatialRef(SpatialReference srs) {
ogrJNI.GeomFieldDefn_SetSpatialRef(swigCPtr, this, SpatialReference.getCPtr(srs), srs);
}
public int IsIgnored() {
return ogrJNI.GeomFieldDefn_IsIgnored(swigCPtr, this);
}
public void SetIgnored(int bIgnored) {
ogrJNI.GeomFieldDefn_SetIgnored(swigCPtr, this, bIgnored);
}
public int IsNullable() {
return ogrJNI.GeomFieldDefn_IsNullable(swigCPtr, this);
}
public void SetNullable(int bNullable) {
ogrJNI.GeomFieldDefn_SetNullable(swigCPtr, this, bNullable);
}
}
| 25.390625 | 91 | 0.662462 |
e309e0b3ebb015bb07c54e00bd265b7004b824d2 | 497 | package com.acnt.bugfree.activity.base;
import android.support.v7.app.AppCompatActivity;
import com.acnt.bugfree.util.EventBusUtil;
/**
* 应用的基础类,封装一些基础的方法,方便子类的调用
* Created by NiuKY on 9/30.
*/
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
EventBusUtil.register(this);
}
@Override
protected void onPause() {
super.onPause();
EventBusUtil.unRegister(this);
}
}
| 19.88 | 62 | 0.682093 |
cc181f319843a4cba0ca55fc0f5da638e0538515 | 8,993 | package azathoth.util.prospecting.registry;
import azathoth.util.prospecting.Prospecting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;
import net.minecraftforge.oredict.OreDictionary;
public class ProspectingSavedData extends WorldSavedData {
private HashMap<List<Integer>, HashMap<String, Float>> chunks; // [cx, cz]: { "ore": amt }
private HashMap<List<Integer>, Long> expiry;
private HashMap<List<Integer>, HashMap<String, Integer>> nuggets;
private World world;
public ProspectingSavedData(World world, String tag) {
super(tag);
this.world = world;
this.chunks = new HashMap<List<Integer>, HashMap<String, Float>>();
this.expiry = new HashMap<List<Integer>, Long>();
this.nuggets = new HashMap<List<Integer>, HashMap<String, Integer>>();
}
public ProspectingSavedData(String tag) {
super(tag);
this.chunks = new HashMap<List<Integer>, HashMap<String, Float>>();
this.expiry = new HashMap<List<Integer>, Long>();
this.nuggets = new HashMap<List<Integer>, HashMap<String, Integer>>();
}
public void setWorld(World world) {
this.world = world;
}
@Override
public void readFromNBT(NBTTagCompound t) {
Prospecting.logger.debug("Reading from NBT...");
this.chunks = new HashMap<List<Integer>, HashMap<String, Float>>();
this.expiry = new HashMap<List<Integer>, Long>();
this.nuggets = new HashMap<List<Integer>, HashMap<String, Integer>>();
for (Object x : t.func_150296_c()) {
for (Object z : t.getCompoundTag((String) x).func_150296_c()) {
List<Integer> chunk = Arrays.asList(Integer.valueOf((String) x), Integer.valueOf((String) z));
HashMap<String, Float> ores = new HashMap<String, Float>();
for (Object ore : t.getCompoundTag((String) x).getCompoundTag((String) z).func_150296_c()) {
if (!((String) ore).equals("expiry") && !((String) ore).equals("nuggets")) {
ores.put((String) ore, t.getCompoundTag((String) x).getCompoundTag((String) z).getFloat((String) ore));
}
}
HashMap<String, Integer> nug_list = new HashMap<String, Integer>();
for (Object ore : t.getCompoundTag((String) x).getCompoundTag((String) z).getCompoundTag("nuggets").func_150296_c()) {
nug_list.put((String) ore, t.getCompoundTag((String) x).getCompoundTag((String) z).getCompoundTag("nuggets").getInteger((String) ore));
}
this.chunks.put(chunk, ores);
this.expiry.put(chunk, t.getCompoundTag((String) x).getCompoundTag((String) z).getLong("expiry"));
this.nuggets.put(chunk, nug_list);
}
}
}
@Override
public void writeToNBT(NBTTagCompound t) {
Prospecting.logger.debug("Writing to NBT...");
for (Map.Entry<List<Integer>, HashMap<String, Float>> chunk : this.chunks.entrySet()) {
int cx = chunk.getKey().get(0);
int cz = chunk.getKey().get(1);
Prospecting.logger.debug("Writing chunk " + chunk.getKey().toString() + "...");
NBTTagCompound x_tag = new NBTTagCompound();
NBTTagCompound z_tag = new NBTTagCompound();
NBTTagCompound nug_tag = new NBTTagCompound();
for (Map.Entry<String, Float> ore : chunk.getValue().entrySet()) {
z_tag.setFloat(ore.getKey(), ore.getValue());
}
for (Map.Entry<String, Integer> ore : nuggets.get(chunk.getKey()).entrySet()) {
nug_tag.setInteger(ore.getKey(), ore.getValue());
}
// Prospecting.logger.debug("Cooldown: " + this.expiry.get(chunk.getKey()));
// Prospecting.logger.debug("Nuggets: " + this.nuggets.get(chunk.getKey()));
z_tag.setLong("expiry", this.expiry.get(chunk.getKey()));
z_tag.setTag("nuggets", nug_tag);
x_tag.setTag(Integer.toString(cz), z_tag);
t.setTag(Integer.toString(cx), x_tag);
}
}
public boolean hasChunk(int cx, int cz) {
try {
return this.chunks.get(Arrays.asList(cx, cz)) != null;
} catch (NullPointerException e) {
return false;
}
}
public boolean isStale(int cx, int cz) {
try {
return !hasChunk(cx, cz) || world.getWorldTime() > this.expiry.get(Arrays.asList(cx, cz));
} catch (NullPointerException e) {
return true;
}
}
public boolean hasNuggets(int cx, int cz) {
try {
for (Map.Entry<String, Integer> ore : this.nuggets.get(Arrays.asList(cx, cz)).entrySet()) {
if (ore.getValue() > 0)
return true;
}
return false;
} catch (NullPointerException e) {
return false;
}
}
public void scanChunk(int cx, int cz) {
Block b;
HashMap<String, Float> ores = new HashMap<String, Float>();
int total = 0;
List<Integer> chunk = Arrays.asList(cx, cz);
int x = cx << 4;
int z = cz << 4;
if (isStale(cx, cz)) {
Prospecting.logger.debug("Scanning chunk [" + cx + ", " + cz + "]...");
for (int i = 1; i <= 256; i++) {
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
b = world.getBlock(x + j, i, z + k);
if (!b.equals(Blocks.air)) {
String name = OreDictCache.getOreName(b, b.getDamageValue(world, x + j , i, z + k));
if (name != null) {
float amt = OreDictCache.getOreValue(b, b.getDamageValue(world, x + j, i, z + k));
if (ores.containsKey(name)) {
amt += ores.remove(name);
}
ores.put(name, amt);
}
total++;
}
}
}
}
Prospecting.logger.debug("Scanned.");
Prospecting.logger.debug("Total blocks scanned: " + total);
Prospecting.logger.debug("Ore types found: " + ores.size());
this.chunks.put(chunk, ores);
this.expiry.put(chunk, world.getWorldTime() + (20 * Prospecting.config.chunk_expiry));
if (!this.nuggets.containsKey(chunk)) {
this.nuggets.put(chunk, new HashMap<String, Integer>());
for (Map.Entry<String, Float> ore : this.chunks.get(chunk).entrySet()) {
if (!this.nuggets.get(chunk).containsKey(ore.getKey())) {
int amount = getNuggetAmount(ore.getValue());
if (amount > 0) {
this.nuggets.get(chunk).put(ore.getKey(), amount);
}
}
}
}
markDirty();
}
}
private int getNuggetAmount(float amt) {
int divisor = Prospecting.config.ore_per_nugget + (ThreadLocalRandom.current().nextInt(0, (Prospecting.config.ore_per_nugget_deviation * 2) + 1)) - Prospecting.config.ore_per_nugget_deviation;
int r = (int) (amt / divisor);
if (r > Prospecting.config.max_nuggets) {
return Prospecting.config.max_nuggets;
} else if (r < 0) {
return 0;
}
return r;
}
public int getFlowerCount(String ore, int cx, int cz) {
List<Integer> chunk = Arrays.asList(cx, cz);
if (this.chunks.containsKey(chunk) && this.chunks.get(chunk).containsKey(ore)) {
int divisor = Prospecting.config.ore_per_flower + (ThreadLocalRandom.current().nextInt(0, (Prospecting.config.ore_per_flower_deviation * 2) + 1)) - Prospecting.config.ore_per_flower_deviation;
return (int) (this.chunks.get(chunk).get(ore) / divisor);
}
return 0;
}
// gets a nugget for chunk <cx, cz> and decrements that chunk's nugget count
public ItemStack getNugget(int cx, int cz) {
scanChunk(cx, cz); // make sure we're dealing with an initialized chunk
if (hasNuggets(cx, cz)) {
List<Integer> chunk = Arrays.asList(cx, cz);
ArrayList<String> ores;
Prospecting.logger.info("Getting nuggets for " + chunk.toString());
try {
ores = new ArrayList<String>(this.nuggets.get(chunk).keySet());
} catch (NullPointerException e) {
return null;
}
String ore = ores.get(ThreadLocalRandom.current().nextInt(0, ores.size()));
ItemStack nugget = OreDictCache.getNuggetFromName(ore);
Prospecting.logger.info("Selected " + ore);
if (nugget != null) {
Prospecting.logger.info("Nugget found.");
int amt = this.nuggets.get(chunk).get(ore) - 1;
Prospecting.logger.info("Chunk has " + amt + " nuggets after spawning.");
if (amt <= 0) {
this.nuggets.get(chunk).remove(ore);
} else {
this.nuggets.get(chunk).put(ore, amt);
}
markDirty();
return new ItemStack(nugget.getItem(), 1, nugget.getItemDamage());
}
Prospecting.logger.info("Nugget was null.");
return null;
} else {
Prospecting.logger.info("Chunk has no nuggets left.");
return null;
}
}
public void logChunk(int cx, int cz) {
List<Integer> chunk = Arrays.asList(cx, cz);
if (hasChunk(cx, cz)) {
Prospecting.logger.info("Chunk info " + chunk.toString() + ":");
for (Map.Entry<String, Float> o : this.chunks.get(chunk).entrySet()) {
Prospecting.logger.info("\"" + o.getKey() + "\": " + o.getValue());
}
} else {
Prospecting.logger.info("No data for chunk " + chunk.toString() + ".");
}
}
public Set<String> getOres(int cx, int cz) {
try {
return chunks.get(Arrays.asList(cx, cz)).keySet();
} catch (NullPointerException e) {
return null;
}
}
}
| 32.701818 | 195 | 0.662404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.