hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9233a95cb92c1df3f51063d170ab38c3a8b8ae46 | 15,095 | java | Java | desktop/libs/hadoop/java/src/main/gen-java/org/apache/hadoop/thriftfs/api/RuntimeInfo.java | digideskio/hortonworks-sandbox | dd8e95c91faee3daa094707baeb94c3953b41efa | [
"Apache-2.0"
] | 19 | 2015-05-01T19:59:03.000Z | 2021-12-09T08:03:16.000Z | desktop/libs/hadoop/java/src/main/gen-java/org/apache/hadoop/thriftfs/api/RuntimeInfo.java | digideskio/hortonworks-sandbox | dd8e95c91faee3daa094707baeb94c3953b41efa | [
"Apache-2.0"
] | 1 | 2018-01-03T15:26:49.000Z | 2018-01-03T15:26:49.000Z | desktop/libs/hadoop/java/src/main/gen-java/org/apache/hadoop/thriftfs/api/RuntimeInfo.java | hortonworks/hortonworks-sandbox | dd8e95c91faee3daa094707baeb94c3953b41efa | [
"Apache-2.0"
] | 30 | 2015-03-25T19:40:07.000Z | 2021-05-28T22:59:26.000Z | 30.743381 | 184 | 0.68526 | 996,653 | /**
* Autogenerated by Thrift Compiler (0.7.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
package org.apache.hadoop.thriftfs.api;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Memory available via java.lang.Runtime
*/
public class RuntimeInfo implements org.apache.thrift.TBase<RuntimeInfo, RuntimeInfo._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RuntimeInfo");
private static final org.apache.thrift.protocol.TField TOTAL_MEMORY_FIELD_DESC = new org.apache.thrift.protocol.TField("totalMemory", org.apache.thrift.protocol.TType.I64, (short)1);
private static final org.apache.thrift.protocol.TField FREE_MEMORY_FIELD_DESC = new org.apache.thrift.protocol.TField("freeMemory", org.apache.thrift.protocol.TType.I64, (short)2);
private static final org.apache.thrift.protocol.TField MAX_MEMORY_FIELD_DESC = new org.apache.thrift.protocol.TField("maxMemory", org.apache.thrift.protocol.TType.I64, (short)3);
public long totalMemory; // required
public long freeMemory; // required
public long maxMemory; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TOTAL_MEMORY((short)1, "totalMemory"),
FREE_MEMORY((short)2, "freeMemory"),
MAX_MEMORY((short)3, "maxMemory");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TOTAL_MEMORY
return TOTAL_MEMORY;
case 2: // FREE_MEMORY
return FREE_MEMORY;
case 3: // MAX_MEMORY
return MAX_MEMORY;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TOTALMEMORY_ISSET_ID = 0;
private static final int __FREEMEMORY_ISSET_ID = 1;
private static final int __MAXMEMORY_ISSET_ID = 2;
private BitSet __isset_bit_vector = new BitSet(3);
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TOTAL_MEMORY, new org.apache.thrift.meta_data.FieldMetaData("totalMemory", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.FREE_MEMORY, new org.apache.thrift.meta_data.FieldMetaData("freeMemory", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.MAX_MEMORY, new org.apache.thrift.meta_data.FieldMetaData("maxMemory", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RuntimeInfo.class, metaDataMap);
}
public RuntimeInfo() {
}
public RuntimeInfo(
long totalMemory,
long freeMemory,
long maxMemory)
{
this();
this.totalMemory = totalMemory;
setTotalMemoryIsSet(true);
this.freeMemory = freeMemory;
setFreeMemoryIsSet(true);
this.maxMemory = maxMemory;
setMaxMemoryIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public RuntimeInfo(RuntimeInfo other) {
__isset_bit_vector.clear();
__isset_bit_vector.or(other.__isset_bit_vector);
this.totalMemory = other.totalMemory;
this.freeMemory = other.freeMemory;
this.maxMemory = other.maxMemory;
}
public RuntimeInfo deepCopy() {
return new RuntimeInfo(this);
}
@Override
public void clear() {
setTotalMemoryIsSet(false);
this.totalMemory = 0;
setFreeMemoryIsSet(false);
this.freeMemory = 0;
setMaxMemoryIsSet(false);
this.maxMemory = 0;
}
public long getTotalMemory() {
return this.totalMemory;
}
public RuntimeInfo setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
setTotalMemoryIsSet(true);
return this;
}
public void unsetTotalMemory() {
__isset_bit_vector.clear(__TOTALMEMORY_ISSET_ID);
}
/** Returns true if field totalMemory is set (has been assigned a value) and false otherwise */
public boolean isSetTotalMemory() {
return __isset_bit_vector.get(__TOTALMEMORY_ISSET_ID);
}
public void setTotalMemoryIsSet(boolean value) {
__isset_bit_vector.set(__TOTALMEMORY_ISSET_ID, value);
}
public long getFreeMemory() {
return this.freeMemory;
}
public RuntimeInfo setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
setFreeMemoryIsSet(true);
return this;
}
public void unsetFreeMemory() {
__isset_bit_vector.clear(__FREEMEMORY_ISSET_ID);
}
/** Returns true if field freeMemory is set (has been assigned a value) and false otherwise */
public boolean isSetFreeMemory() {
return __isset_bit_vector.get(__FREEMEMORY_ISSET_ID);
}
public void setFreeMemoryIsSet(boolean value) {
__isset_bit_vector.set(__FREEMEMORY_ISSET_ID, value);
}
public long getMaxMemory() {
return this.maxMemory;
}
public RuntimeInfo setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
setMaxMemoryIsSet(true);
return this;
}
public void unsetMaxMemory() {
__isset_bit_vector.clear(__MAXMEMORY_ISSET_ID);
}
/** Returns true if field maxMemory is set (has been assigned a value) and false otherwise */
public boolean isSetMaxMemory() {
return __isset_bit_vector.get(__MAXMEMORY_ISSET_ID);
}
public void setMaxMemoryIsSet(boolean value) {
__isset_bit_vector.set(__MAXMEMORY_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TOTAL_MEMORY:
if (value == null) {
unsetTotalMemory();
} else {
setTotalMemory((Long)value);
}
break;
case FREE_MEMORY:
if (value == null) {
unsetFreeMemory();
} else {
setFreeMemory((Long)value);
}
break;
case MAX_MEMORY:
if (value == null) {
unsetMaxMemory();
} else {
setMaxMemory((Long)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TOTAL_MEMORY:
return Long.valueOf(getTotalMemory());
case FREE_MEMORY:
return Long.valueOf(getFreeMemory());
case MAX_MEMORY:
return Long.valueOf(getMaxMemory());
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TOTAL_MEMORY:
return isSetTotalMemory();
case FREE_MEMORY:
return isSetFreeMemory();
case MAX_MEMORY:
return isSetMaxMemory();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof RuntimeInfo)
return this.equals((RuntimeInfo)that);
return false;
}
public boolean equals(RuntimeInfo that) {
if (that == null)
return false;
boolean this_present_totalMemory = true;
boolean that_present_totalMemory = true;
if (this_present_totalMemory || that_present_totalMemory) {
if (!(this_present_totalMemory && that_present_totalMemory))
return false;
if (this.totalMemory != that.totalMemory)
return false;
}
boolean this_present_freeMemory = true;
boolean that_present_freeMemory = true;
if (this_present_freeMemory || that_present_freeMemory) {
if (!(this_present_freeMemory && that_present_freeMemory))
return false;
if (this.freeMemory != that.freeMemory)
return false;
}
boolean this_present_maxMemory = true;
boolean that_present_maxMemory = true;
if (this_present_maxMemory || that_present_maxMemory) {
if (!(this_present_maxMemory && that_present_maxMemory))
return false;
if (this.maxMemory != that.maxMemory)
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
public int compareTo(RuntimeInfo other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
RuntimeInfo typedOther = (RuntimeInfo)other;
lastComparison = Boolean.valueOf(isSetTotalMemory()).compareTo(typedOther.isSetTotalMemory());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTotalMemory()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.totalMemory, typedOther.totalMemory);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetFreeMemory()).compareTo(typedOther.isSetFreeMemory());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetFreeMemory()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.freeMemory, typedOther.freeMemory);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMaxMemory()).compareTo(typedOther.isSetMaxMemory());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMaxMemory()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.maxMemory, typedOther.maxMemory);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField field;
iprot.readStructBegin();
while (true)
{
field = iprot.readFieldBegin();
if (field.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (field.id) {
case 1: // TOTAL_MEMORY
if (field.type == org.apache.thrift.protocol.TType.I64) {
this.totalMemory = iprot.readI64();
setTotalMemoryIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
}
break;
case 2: // FREE_MEMORY
if (field.type == org.apache.thrift.protocol.TType.I64) {
this.freeMemory = iprot.readI64();
setFreeMemoryIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
}
break;
case 3: // MAX_MEMORY
if (field.type == org.apache.thrift.protocol.TType.I64) {
this.maxMemory = iprot.readI64();
setMaxMemoryIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(TOTAL_MEMORY_FIELD_DESC);
oprot.writeI64(this.totalMemory);
oprot.writeFieldEnd();
oprot.writeFieldBegin(FREE_MEMORY_FIELD_DESC);
oprot.writeI64(this.freeMemory);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MAX_MEMORY_FIELD_DESC);
oprot.writeI64(this.maxMemory);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RuntimeInfo(");
boolean first = true;
sb.append("totalMemory:");
sb.append(this.totalMemory);
first = false;
if (!first) sb.append(", ");
sb.append("freeMemory:");
sb.append(this.freeMemory);
first = false;
if (!first) sb.append(", ");
sb.append("maxMemory:");
sb.append(this.maxMemory);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bit_vector = new BitSet(1);
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
}
|
9233a97987d0218e21cda01c529d70667ce4b75c | 303 | java | Java | src/main/java/app/jg/og/zamong/dto/request/FollowUserRequest.java | OGJG-ZAMONG/ZAMONG-Backend-V1 | d286d68be7af8691b14b406f02c3b0af09e782f3 | [
"MIT"
] | 35 | 2021-08-17T11:06:09.000Z | 2022-03-31T10:27:03.000Z | src/main/java/app/jg/og/zamong/dto/request/FollowUserRequest.java | OGJG-ZAMONG/ZAMONG-Backend-V1 | d286d68be7af8691b14b406f02c3b0af09e782f3 | [
"MIT"
] | 165 | 2021-08-13T02:02:06.000Z | 2021-12-26T13:22:06.000Z | src/main/java/app/jg/og/zamong/dto/request/FollowUserRequest.java | OGJG-ZAMONG/ZAMONG-Backend-V1 | d286d68be7af8691b14b406f02c3b0af09e782f3 | [
"MIT"
] | 1 | 2021-12-06T13:04:41.000Z | 2021-12-06T13:04:41.000Z | 18.9375 | 50 | 0.772277 | 996,654 | package app.jg.og.zamong.dto.request;
import lombok.*;
import javax.validation.constraints.NotNull;
@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class FollowUserRequest {
@NotNull(message = "유저 아이디를 반드시 입력해야 합니다")
private String userUuid;
}
|
9233a995cf5f8d78ea6593415ee84ab1fb05055c | 40,683 | java | Java | src/main/java/Diadoc/Api/Proto/Events/ResolutionRequestInfoProtos.java | XomakNet/diadocsdk-java | 021ab0775a0d61709e42816817bc745f9eab206f | [
"MIT"
] | null | null | null | src/main/java/Diadoc/Api/Proto/Events/ResolutionRequestInfoProtos.java | XomakNet/diadocsdk-java | 021ab0775a0d61709e42816817bc745f9eab206f | [
"MIT"
] | null | null | null | src/main/java/Diadoc/Api/Proto/Events/ResolutionRequestInfoProtos.java | XomakNet/diadocsdk-java | 021ab0775a0d61709e42816817bc745f9eab206f | [
"MIT"
] | null | null | null | 37.704356 | 216 | 0.653369 | 996,655 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Events/ResolutionRequestInfo.proto
package Diadoc.Api.Proto.Events;
public final class ResolutionRequestInfoProtos {
private ResolutionRequestInfoProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
/**
* Protobuf enum {@code Diadoc.Api.Proto.Events.ResolutionRequestType}
*/
public enum ResolutionRequestType
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>UnknownResolutionRequestType = -1;</code>
*/
UnknownResolutionRequestType(0, -1),
/**
* <code>ApprovementRequest = 0;</code>
*/
ApprovementRequest(1, 0),
/**
* <code>SignatureRequest = 1;</code>
*/
SignatureRequest(2, 1),
/**
* <code>ApprovementSignatureRequest = 2;</code>
*/
ApprovementSignatureRequest(3, 2),
;
/**
* <code>UnknownResolutionRequestType = -1;</code>
*/
public static final int UnknownResolutionRequestType_VALUE = -1;
/**
* <code>ApprovementRequest = 0;</code>
*/
public static final int ApprovementRequest_VALUE = 0;
/**
* <code>SignatureRequest = 1;</code>
*/
public static final int SignatureRequest_VALUE = 1;
/**
* <code>ApprovementSignatureRequest = 2;</code>
*/
public static final int ApprovementSignatureRequest_VALUE = 2;
public final int getNumber() { return value; }
public static ResolutionRequestType valueOf(int value) {
switch (value) {
case -1: return UnknownResolutionRequestType;
case 0: return ApprovementRequest;
case 1: return SignatureRequest;
case 2: return ApprovementSignatureRequest;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ResolutionRequestType>
internalGetValueMap() {
return internalValueMap;
}
private static com.google.protobuf.Internal.EnumLiteMap<ResolutionRequestType>
internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ResolutionRequestType>() {
public ResolutionRequestType findValueByNumber(int number) {
return ResolutionRequestType.valueOf(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(index);
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.getDescriptor().getEnumTypes().get(0);
}
private static final ResolutionRequestType[] VALUES = values();
public static ResolutionRequestType valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
return VALUES[desc.getIndex()];
}
private final int index;
private final int value;
private ResolutionRequestType(int index, int value) {
this.index = index;
this.value = value;
}
// @@protoc_insertion_point(enum_scope:Diadoc.Api.Proto.Events.ResolutionRequestType)
}
public interface ResolutionRequestInfoOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.Events.ResolutionRequestInfo)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
boolean hasRequestType();
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType getRequestType();
/**
* <code>required string Author = 2;</code>
*/
boolean hasAuthor();
/**
* <code>required string Author = 2;</code>
*/
java.lang.String getAuthor();
/**
* <code>required string Author = 2;</code>
*/
com.google.protobuf.ByteString
getAuthorBytes();
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
boolean hasTarget();
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget getTarget();
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder getTargetOrBuilder();
/**
* <code>optional string ResolvedWith = 4;</code>
*/
boolean hasResolvedWith();
/**
* <code>optional string ResolvedWith = 4;</code>
*/
java.lang.String getResolvedWith();
/**
* <code>optional string ResolvedWith = 4;</code>
*/
com.google.protobuf.ByteString
getResolvedWithBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Events.ResolutionRequestInfo}
*/
public static final class ResolutionRequestInfo extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.Events.ResolutionRequestInfo)
ResolutionRequestInfoOrBuilder {
// Use ResolutionRequestInfo.newBuilder() to construct.
private ResolutionRequestInfo(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private ResolutionRequestInfo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final ResolutionRequestInfo defaultInstance;
public static ResolutionRequestInfo getDefaultInstance() {
return defaultInstance;
}
public ResolutionRequestInfo getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ResolutionRequestInfo(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType value = Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType.valueOf(rawValue);
if (value == null) {
unknownFields.mergeVarintField(1, rawValue);
} else {
bitField0_ |= 0x00000001;
requestType_ = value;
}
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
author_ = bs;
break;
}
case 26: {
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder subBuilder = null;
if (((bitField0_ & 0x00000004) == 0x00000004)) {
subBuilder = target_.toBuilder();
}
target_ = input.readMessage(Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(target_);
target_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000004;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000008;
resolvedWith_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.class, Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.Builder.class);
}
public static com.google.protobuf.Parser<ResolutionRequestInfo> PARSER =
new com.google.protobuf.AbstractParser<ResolutionRequestInfo>() {
public ResolutionRequestInfo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ResolutionRequestInfo(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<ResolutionRequestInfo> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int REQUESTTYPE_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType requestType_;
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public boolean hasRequestType() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType getRequestType() {
return requestType_;
}
public static final int AUTHOR_FIELD_NUMBER = 2;
private java.lang.Object author_;
/**
* <code>required string Author = 2;</code>
*/
public boolean hasAuthor() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Author = 2;</code>
*/
public java.lang.String getAuthor() {
java.lang.Object ref = author_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
author_ = s;
}
return s;
}
}
/**
* <code>required string Author = 2;</code>
*/
public com.google.protobuf.ByteString
getAuthorBytes() {
java.lang.Object ref = author_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
author_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TARGET_FIELD_NUMBER = 3;
private Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget target_;
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public boolean hasTarget() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget getTarget() {
return target_;
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder getTargetOrBuilder() {
return target_;
}
public static final int RESOLVEDWITH_FIELD_NUMBER = 4;
private java.lang.Object resolvedWith_;
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public boolean hasResolvedWith() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public java.lang.String getResolvedWith() {
java.lang.Object ref = resolvedWith_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
resolvedWith_ = s;
}
return s;
}
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public com.google.protobuf.ByteString
getResolvedWithBytes() {
java.lang.Object ref = resolvedWith_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resolvedWith_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
requestType_ = Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType.UnknownResolutionRequestType;
author_ = "";
target_ = Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.getDefaultInstance();
resolvedWith_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasAuthor()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeEnum(1, requestType_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getAuthorBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeMessage(3, target_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getResolvedWithBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, requestType_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getAuthorBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, target_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getResolvedWithBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Events.ResolutionRequestInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.Events.ResolutionRequestInfo)
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.class, Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.Builder.class);
}
// Construct using Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getTargetFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
requestType_ = Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType.UnknownResolutionRequestType;
bitField0_ = (bitField0_ & ~0x00000001);
author_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
if (targetBuilder_ == null) {
target_ = Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.getDefaultInstance();
} else {
targetBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
resolvedWith_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor;
}
public Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo getDefaultInstanceForType() {
return Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.getDefaultInstance();
}
public Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo build() {
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo buildPartial() {
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo result = new Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.requestType_ = requestType_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.author_ = author_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
if (targetBuilder_ == null) {
result.target_ = target_;
} else {
result.target_ = targetBuilder_.build();
}
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.resolvedWith_ = resolvedWith_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo) {
return mergeFrom((Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo other) {
if (other == Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo.getDefaultInstance()) return this;
if (other.hasRequestType()) {
setRequestType(other.getRequestType());
}
if (other.hasAuthor()) {
bitField0_ |= 0x00000002;
author_ = other.author_;
onChanged();
}
if (other.hasTarget()) {
mergeTarget(other.getTarget());
}
if (other.hasResolvedWith()) {
bitField0_ |= 0x00000008;
resolvedWith_ = other.resolvedWith_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasAuthor()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestInfo) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType requestType_ = Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType.UnknownResolutionRequestType;
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public boolean hasRequestType() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType getRequestType() {
return requestType_;
}
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public Builder setRequestType(Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
requestType_ = value;
onChanged();
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Events.ResolutionRequestType RequestType = 1 [default = UnknownResolutionRequestType];</code>
*/
public Builder clearRequestType() {
bitField0_ = (bitField0_ & ~0x00000001);
requestType_ = Diadoc.Api.Proto.Events.ResolutionRequestInfoProtos.ResolutionRequestType.UnknownResolutionRequestType;
onChanged();
return this;
}
private java.lang.Object author_ = "";
/**
* <code>required string Author = 2;</code>
*/
public boolean hasAuthor() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Author = 2;</code>
*/
public java.lang.String getAuthor() {
java.lang.Object ref = author_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
author_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string Author = 2;</code>
*/
public com.google.protobuf.ByteString
getAuthorBytes() {
java.lang.Object ref = author_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
author_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string Author = 2;</code>
*/
public Builder setAuthor(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
author_ = value;
onChanged();
return this;
}
/**
* <code>required string Author = 2;</code>
*/
public Builder clearAuthor() {
bitField0_ = (bitField0_ & ~0x00000002);
author_ = getDefaultInstance().getAuthor();
onChanged();
return this;
}
/**
* <code>required string Author = 2;</code>
*/
public Builder setAuthorBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
author_ = value;
onChanged();
return this;
}
private Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget target_ = Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder> targetBuilder_;
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public boolean hasTarget() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget getTarget() {
if (targetBuilder_ == null) {
return target_;
} else {
return targetBuilder_.getMessage();
}
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Builder setTarget(Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget value) {
if (targetBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
target_ = value;
onChanged();
} else {
targetBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Builder setTarget(
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder builderForValue) {
if (targetBuilder_ == null) {
target_ = builderForValue.build();
onChanged();
} else {
targetBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Builder mergeTarget(Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget value) {
if (targetBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004) &&
target_ != Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.getDefaultInstance()) {
target_ =
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.newBuilder(target_).mergeFrom(value).buildPartial();
} else {
target_ = value;
}
onChanged();
} else {
targetBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Builder clearTarget() {
if (targetBuilder_ == null) {
target_ = Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.getDefaultInstance();
onChanged();
} else {
targetBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder getTargetBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getTargetFieldBuilder().getBuilder();
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
public Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder getTargetOrBuilder() {
if (targetBuilder_ != null) {
return targetBuilder_.getMessageOrBuilder();
} else {
return target_;
}
}
/**
* <code>optional .Diadoc.Api.Proto.ResolutionTarget Target = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder>
getTargetFieldBuilder() {
if (targetBuilder_ == null) {
targetBuilder_ = new com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTarget.Builder, Diadoc.Api.Proto.ResolutionTargetProtos.ResolutionTargetOrBuilder>(
getTarget(),
getParentForChildren(),
isClean());
target_ = null;
}
return targetBuilder_;
}
private java.lang.Object resolvedWith_ = "";
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public boolean hasResolvedWith() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public java.lang.String getResolvedWith() {
java.lang.Object ref = resolvedWith_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
resolvedWith_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public com.google.protobuf.ByteString
getResolvedWithBytes() {
java.lang.Object ref = resolvedWith_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resolvedWith_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public Builder setResolvedWith(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
resolvedWith_ = value;
onChanged();
return this;
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public Builder clearResolvedWith() {
bitField0_ = (bitField0_ & ~0x00000008);
resolvedWith_ = getDefaultInstance().getResolvedWith();
onChanged();
return this;
}
/**
* <code>optional string ResolvedWith = 4;</code>
*/
public Builder setResolvedWithBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
resolvedWith_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.Events.ResolutionRequestInfo)
}
static {
defaultInstance = new ResolutionRequestInfo(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Events.ResolutionRequestInfo)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\"Events/ResolutionRequestInfo.proto\022\027Di" +
"adoc.Api.Proto.Events\032\026ResolutionTarget." +
"proto\"\324\001\n\025ResolutionRequestInfo\022a\n\013Reque" +
"stType\030\001 \001(\0162..Diadoc.Api.Proto.Events.R" +
"esolutionRequestType:\034UnknownResolutionR" +
"equestType\022\016\n\006Author\030\002 \002(\t\0222\n\006Target\030\003 \001" +
"(\0132\".Diadoc.Api.Proto.ResolutionTarget\022\024" +
"\n\014ResolvedWith\030\004 \001(\t*\221\001\n\025ResolutionReque" +
"stType\022)\n\034UnknownResolutionRequestType\020\377" +
"\377\377\377\377\377\377\377\377\001\022\026\n\022ApprovementRequest\020\000\022\024\n\020Sig",
"natureRequest\020\001\022\037\n\033ApprovementSignatureR" +
"equest\020\002B\035B\033ResolutionRequestInfoProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
Diadoc.Api.Proto.ResolutionTargetProtos.getDescriptor(),
}, assigner);
internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_Events_ResolutionRequestInfo_descriptor,
new java.lang.String[] { "RequestType", "Author", "Target", "ResolvedWith", });
Diadoc.Api.Proto.ResolutionTargetProtos.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
9233ac3023579a1086bf719e00e09ab09ea61331 | 716 | java | Java | ejb_practice/src/main/java/com/ecme/facade/PartsBeanFacade.java | edgar-mercado/jee_training | 837d8927e8e82cc529496002d3a8aa43360a9e20 | [
"Apache-2.0"
] | null | null | null | ejb_practice/src/main/java/com/ecme/facade/PartsBeanFacade.java | edgar-mercado/jee_training | 837d8927e8e82cc529496002d3a8aa43360a9e20 | [
"Apache-2.0"
] | null | null | null | ejb_practice/src/main/java/com/ecme/facade/PartsBeanFacade.java | edgar-mercado/jee_training | 837d8927e8e82cc529496002d3a8aa43360a9e20 | [
"Apache-2.0"
] | null | null | null | 23.866667 | 79 | 0.730447 | 996,656 | /*
* 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.ecme.facade;
import com.ecme.entities.PartsEntity;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author edgar
*/
@Stateless
public class PartsBeanFacade extends AbstractFacade<PartsEntity> {
@PersistenceContext(unitName = "ejb_practicePU")
private EntityManager em;
@Override
protected EntityManager getEntityManager(){
return em;
}
public PartsBeanFacade(){
super(PartsEntity.class);
}
}
|
9233ac632bf1fe5b4707dd23e2fc7300fd898264 | 3,644 | java | Java | src/main/java/org/openapitools/client/model/CommonGetAutocompleteV1Response.java | eZmaxinc/eZmax-SDK-android | 4a0134c2e5870fe5b49c74e61770ec66e00f93ab | [
"MIT"
] | 1 | 2021-03-30T00:51:33.000Z | 2021-03-30T00:51:33.000Z | src/main/java/org/openapitools/client/model/CommonGetAutocompleteV1Response.java | eZmaxinc/eZmax-SDK-android | 4a0134c2e5870fe5b49c74e61770ec66e00f93ab | [
"MIT"
] | null | null | null | src/main/java/org/openapitools/client/model/CommonGetAutocompleteV1Response.java | eZmaxinc/eZmax-SDK-android | 4a0134c2e5870fe5b49c74e61770ec66e00f93ab | [
"MIT"
] | 1 | 2021-03-30T00:51:38.000Z | 2021-03-30T00:51:38.000Z | 35.067308 | 178 | 0.733754 | 996,657 | /**
* eZmax API Definition
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.3
* Contact: kenaa@example.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.*;
import org.openapitools.client.model.CommonGetAutocompleteV1ResponseAllOf;
import org.openapitools.client.model.CommonResponse;
import org.openapitools.client.model.CommonResponseObjDebug;
import org.openapitools.client.model.CommonResponseObjDebugPayload;
import org.openapitools.client.model.CustomAutocompleteElementResponse;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
/**
* Response for the /1/object/xxx/getAutocomplete API Request
**/
@ApiModel(description = "Response for the /1/object/xxx/getAutocomplete API Request")
public class CommonGetAutocompleteV1Response {
@SerializedName("mPayload")
private List<CustomAutocompleteElementResponse> mPayload = null;
@SerializedName("objDebugPayload")
private CommonResponseObjDebugPayload objDebugPayload = null;
@SerializedName("objDebug")
private CommonResponseObjDebug objDebug = null;
/**
* Generic Autocomplete Response
**/
@ApiModelProperty(required = true, value = "Generic Autocomplete Response")
public List<CustomAutocompleteElementResponse> getMPayload() {
return mPayload;
}
public void setMPayload(List<CustomAutocompleteElementResponse> mPayload) {
this.mPayload = mPayload;
}
/**
**/
@ApiModelProperty(value = "")
public CommonResponseObjDebugPayload getObjDebugPayload() {
return objDebugPayload;
}
public void setObjDebugPayload(CommonResponseObjDebugPayload objDebugPayload) {
this.objDebugPayload = objDebugPayload;
}
/**
**/
@ApiModelProperty(value = "")
public CommonResponseObjDebug getObjDebug() {
return objDebug;
}
public void setObjDebug(CommonResponseObjDebug objDebug) {
this.objDebug = objDebug;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CommonGetAutocompleteV1Response commonGetAutocompleteV1Response = (CommonGetAutocompleteV1Response) o;
return (this.mPayload == null ? commonGetAutocompleteV1Response.mPayload == null : this.mPayload.equals(commonGetAutocompleteV1Response.mPayload)) &&
(this.objDebugPayload == null ? commonGetAutocompleteV1Response.objDebugPayload == null : this.objDebugPayload.equals(commonGetAutocompleteV1Response.objDebugPayload)) &&
(this.objDebug == null ? commonGetAutocompleteV1Response.objDebug == null : this.objDebug.equals(commonGetAutocompleteV1Response.objDebug));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.mPayload == null ? 0: this.mPayload.hashCode());
result = 31 * result + (this.objDebugPayload == null ? 0: this.objDebugPayload.hashCode());
result = 31 * result + (this.objDebug == null ? 0: this.objDebug.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CommonGetAutocompleteV1Response {\n");
sb.append(" mPayload: ").append(mPayload).append("\n");
sb.append(" objDebugPayload: ").append(objDebugPayload).append("\n");
sb.append(" objDebug: ").append(objDebug).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
9233acae0c8040418416befc3cf9c90794a71d76 | 10,726 | java | Java | src/main/java/co/signal/kafkameter/KafkaProducerSampler.java | sharmaSelenium/kafkameter | 52908a6871d9aa33a88e2f02c664429e4944afda | [
"Apache-2.0"
] | 124 | 2015-05-12T22:33:00.000Z | 2021-12-15T17:44:27.000Z | src/main/java/co/signal/kafkameter/KafkaProducerSampler.java | sharmaSelenium/kafkameter | 52908a6871d9aa33a88e2f02c664429e4944afda | [
"Apache-2.0"
] | 82 | 2019-10-07T11:31:44.000Z | 2021-12-09T21:49:06.000Z | src/main/java/co/signal/kafkameter/KafkaProducerSampler.java | sharmaSelenium/kafkameter | 52908a6871d9aa33a88e2f02c664429e4944afda | [
"Apache-2.0"
] | 67 | 2015-02-13T11:16:05.000Z | 2022-01-03T16:56:04.000Z | 38.035461 | 128 | 0.746131 | 996,658 | /*
* Copyright 2014 Signal.
*
* 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 co.signal.kafkameter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import com.google.common.base.Strings;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.log.Logger;
/**
* A {@link org.apache.jmeter.samplers.Sampler Sampler} which produces Kafka messages.
*
* @author codyaray
* @since 6/27/14
*
* @see "http://ilkinbalkanay.blogspot.com/2010/03/load-test-whatever-you-want-with-apache.html"
* @see "http://newspaint.wordpress.com/2012/11/28/creating-a-java-sampler-for-jmeter/"
* @see "http://jmeter.512774.n5.nabble.com/Custom-Sampler-Tutorial-td4490189.html"
*/
public class KafkaProducerSampler extends AbstractJavaSamplerClient {
private static final Logger log = LoggingManager.getLoggerForClass();
/**
* Parameter for setting the Kafka brokers; for example, "kafka01:9092,kafka02:9092".
*/
private static final String PARAMETER_KAFKA_BROKERS = "kafka_brokers";
/**
* Parameter for setting the Kafka topic name.
*/
private static final String PARAMETER_KAFKA_TOPIC = "kafka_topic";
/**
* Parameter for setting the Kafka key.
*/
private static final String PARAMETER_KAFKA_KEY = "kafka_key";
/**
* Parameter for setting the Kafka message.
*/
private static final String PARAMETER_KAFKA_MESSAGE = "kafka_message";
/**
* Parameter for setting Kafka's {@code serializer.class} property.
*/
private static final String PARAMETER_KAFKA_MESSAGE_SERIALIZER = "kafka_message_serializer";
/**
* Parameter for setting Kafka's {@code key.serializer.class} property.
*/
private static final String PARAMETER_KAFKA_KEY_SERIALIZER = "kafka_key_serializer";
/**
* Parameter for setting the Kafka ssl keystore (include path information); for example, "server.keystore.jks".
*/
private static final String PARAMETER_KAFKA_SSL_KEYSTORE = "kafka_ssl_keystore";
/**
* Parameter for setting the Kafka ssl keystore password.
*/
private static final String PARAMETER_KAFKA_SSL_KEYSTORE_PASSWORD = "kafka_ssl_keystore_password";
/**
* Parameter for setting the Kafka ssl truststore (include path information); for example, "client.truststore.jks".
*/
private static final String PARAMETER_KAFKA_SSL_TRUSTSTORE = "kafka_ssl_truststore";
/**
* Parameter for setting the Kafka ssl truststore password.
*/
private static final String PARAMETER_KAFKA_SSL_TRUSTSTORE_PASSWORD = "kafka_ssl_truststore_password";
/**
* Parameter for setting the Kafka security protocol; "true" or "false".
*/
private static final String PARAMETER_KAFKA_USE_SSL = "kafka_use_ssl";
/**
* Parameter for setting encryption. It is optional.
*/
private static final String PARAMETER_KAFKA_COMPRESSION_TYPE = "kafka_compression_type";
/**
* Parameter for setting the partition. It is optional.
*/
private static final String PARAMETER_KAFKA_PARTITION = "kafka_partition";
//private Producer<Long, byte[]> producer;
private KafkaProducer<String, String> producer;
@Override
public void setupTest(JavaSamplerContext context) {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, context.getParameter(PARAMETER_KAFKA_BROKERS));
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, context.getParameter(PARAMETER_KAFKA_KEY_SERIALIZER));
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, context.getParameter(PARAMETER_KAFKA_MESSAGE_SERIALIZER));
props.put(ProducerConfig.ACKS_CONFIG, "1");
// check if kafka security protocol is SSL or PLAINTEXT (default)
if(context.getParameter(PARAMETER_KAFKA_USE_SSL).equals("true")){
log.info("Setting up SSL properties...");
props.put("security.protocol", "SSL");
props.put("ssl.keystore.location", context.getParameter(PARAMETER_KAFKA_SSL_KEYSTORE));
props.put("ssl.keystore.password", context.getParameter(PARAMETER_KAFKA_SSL_KEYSTORE_PASSWORD));
props.put("ssl.truststore.location", context.getParameter(PARAMETER_KAFKA_SSL_TRUSTSTORE));
props.put("ssl.truststore.password", context.getParameter(PARAMETER_KAFKA_SSL_TRUSTSTORE_PASSWORD));
}
String compressionType = context.getParameter(PARAMETER_KAFKA_COMPRESSION_TYPE);
if (!Strings.isNullOrEmpty(compressionType)) {
props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, compressionType);
}
producer = new KafkaProducer<String, String>(props);
}
@Override
public void teardownTest(JavaSamplerContext context) {
producer.close();
}
@Override
public Arguments getDefaultParameters() {
Arguments defaultParameters = new Arguments();
defaultParameters.addArgument(PARAMETER_KAFKA_BROKERS, "${PARAMETER_KAFKA_BROKERS}");
defaultParameters.addArgument(PARAMETER_KAFKA_TOPIC, "${PARAMETER_KAFKA_TOPIC}");
defaultParameters.addArgument(PARAMETER_KAFKA_KEY, "${PARAMETER_KAFKA_KEY}");
defaultParameters.addArgument(PARAMETER_KAFKA_MESSAGE, "${PARAMETER_KAFKA_MESSAGE}");
defaultParameters.addArgument(PARAMETER_KAFKA_MESSAGE_SERIALIZER, "org.apache.kafka.common.serialization.StringSerializer");
defaultParameters.addArgument(PARAMETER_KAFKA_KEY_SERIALIZER, "org.apache.kafka.common.serialization.StringSerializer");
defaultParameters.addArgument(PARAMETER_KAFKA_SSL_KEYSTORE, "${PARAMETER_KAFKA_SSL_KEYSTORE}");
defaultParameters.addArgument(PARAMETER_KAFKA_SSL_KEYSTORE_PASSWORD, "${PARAMETER_KAFKA_SSL_KEYSTORE_PASSWORD}");
defaultParameters.addArgument(PARAMETER_KAFKA_SSL_TRUSTSTORE, "${PARAMETER_KAFKA_SSL_TRUSTSTORE}");
defaultParameters.addArgument(PARAMETER_KAFKA_SSL_TRUSTSTORE_PASSWORD, "${PARAMETER_KAFKA_SSL_TRUSTSTORE_PASSWORD}");
defaultParameters.addArgument(PARAMETER_KAFKA_USE_SSL, "${PARAMETER_KAFKA_USE_SSL}");
defaultParameters.addArgument(PARAMETER_KAFKA_COMPRESSION_TYPE, null);
defaultParameters.addArgument(PARAMETER_KAFKA_PARTITION, null);
return defaultParameters;
}
@Override
public SampleResult runTest(JavaSamplerContext context) {
SampleResult result = newSampleResult();
String topic = context.getParameter(PARAMETER_KAFKA_TOPIC);
String key = context.getParameter(PARAMETER_KAFKA_KEY);
String message = context.getParameter(PARAMETER_KAFKA_MESSAGE);
sampleResultStart(result, message);
final ProducerRecord<String, String> producerRecord;
String partitionString = context.getParameter(PARAMETER_KAFKA_PARTITION);
if (Strings.isNullOrEmpty(partitionString)) {
producerRecord = new ProducerRecord<String, String>(topic, key, message);
} else {
final int partitionNumber = Integer.parseInt(partitionString);
producerRecord = new ProducerRecord<String, String>(topic, partitionNumber, key, message);
}
try {
producer.send(producerRecord);
sampleResultSuccess(result, null);
} catch (Exception e) {
sampleResultFailed(result, "500", e);
}
return result;
}
/**
* Use UTF-8 for encoding of strings
*/
private static final String ENCODING = "UTF-8";
/**
* Factory for creating new {@link SampleResult}s.
*/
private SampleResult newSampleResult() {
SampleResult result = new SampleResult();
result.setDataEncoding(ENCODING);
result.setDataType(SampleResult.TEXT);
return result;
}
/**
* Start the sample request and set the {@code samplerData} to {@code data}.
*
* @param result
* the sample result to update
* @param data
* the request to set as {@code samplerData}
*/
private void sampleResultStart(SampleResult result, String data) {
result.setSamplerData(data);
result.sampleStart();
}
/**
* Mark the sample result as {@code end}ed and {@code successful} with an "OK" {@code responseCode},
* and if the response is not {@code null} then set the {@code responseData} to {@code response},
* otherwise it is marked as not requiring a response.
*
* @param result sample result to change
* @param response the successful result message, may be null.
*/
private void sampleResultSuccess(SampleResult result, /* @Nullable */ String response) {
result.sampleEnd();
result.setSuccessful(true);
result.setResponseCodeOK();
if (response != null) {
result.setResponseData(response, ENCODING);
}
else {
result.setResponseData("No response required", ENCODING);
}
}
/**
* Mark the sample result as @{code end}ed and not {@code successful}, and set the
* {@code responseCode} to {@code reason}.
*
* @param result the sample result to change
* @param reason the failure reason
*/
private void sampleResultFailed(SampleResult result, String reason) {
result.sampleEnd();
result.setSuccessful(false);
result.setResponseCode(reason);
}
/**
* Mark the sample result as @{code end}ed and not {@code successful}, set the
* {@code responseCode} to {@code reason}, and set {@code responseData} to the stack trace.
*
* @param result the sample result to change
* @param exception the failure exception
*/
private void sampleResultFailed(SampleResult result, String reason, Exception exception) {
sampleResultFailed(result, reason);
result.setResponseMessage("Exception: " + exception);
result.setResponseData(getStackTrace(exception), ENCODING);
}
/**
* Return the stack trace as a string.
*
* @param exception the exception containing the stack trace
* @return the stack trace
*/
private String getStackTrace(Exception exception) {
StringWriter stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
}
|
9233acd33ee07dccf85dd24e827b4db55af22b3d | 150 | java | Java | LoudQuack.java | Nazymmm/Assignment1_SDP | c30fcc1f85d8caf72495e88dd73c9fa583cea7e2 | [
"MIT"
] | null | null | null | LoudQuack.java | Nazymmm/Assignment1_SDP | c30fcc1f85d8caf72495e88dd73c9fa583cea7e2 | [
"MIT"
] | null | null | null | LoudQuack.java | Nazymmm/Assignment1_SDP | c30fcc1f85d8caf72495e88dd73c9fa583cea7e2 | [
"MIT"
] | null | null | null | 16.666667 | 50 | 0.633333 | 996,659 | package Ass1;
public class LoudQuack implements IQuackBehavior{
public void quack() {
System.out.println("Loud quack");
}
}
|
9233ad32b19fcaa7430c1a431566faff0a65b42a | 1,731 | java | Java | src/com/nic/controller/Controllo.java | NicolaRorato/e-commerce-template | ee4fbf2b24e43987a0d4b96f5672f0dc69334d04 | [
"MIT"
] | null | null | null | src/com/nic/controller/Controllo.java | NicolaRorato/e-commerce-template | ee4fbf2b24e43987a0d4b96f5672f0dc69334d04 | [
"MIT"
] | null | null | null | src/com/nic/controller/Controllo.java | NicolaRorato/e-commerce-template | ee4fbf2b24e43987a0d4b96f5672f0dc69334d04 | [
"MIT"
] | null | null | null | 32.660377 | 119 | 0.727903 | 996,660 | package com.nic.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.nic.architecture.dao.DAOException;
import com.nic.businesscomponent.beans.LoginUtilities;
import com.nic.businesscomponent.security.GeneraMD5;
@WebServlet("/controllo")
public class Controllo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = GeneraMD5.convertiMD5(request.getParameter("password"));
HttpSession session = request.getSession();
String userpass, adminpass;
if(username != null && password != null){
try {
LoginUtilities u = new LoginUtilities();
userpass = u.getUserPass(username);
adminpass = u.getAdminPass(username);
if(userpass != null) {
if(userpass.equals(password)) {
session.setAttribute("username", username);
response.sendRedirect("corsi.jsp");
} else {
response.sendRedirect("accessonegato.jsp");
}
} else if(adminpass != null) {
if(adminpass.equals(password)) {
session.setAttribute("admin", username);
response.sendRedirect("admin/");
}else {
response.sendRedirect("accessonegato.jsp");
}
} else {
response.sendRedirect("accessonegato.jsp");
}
} catch(ClassNotFoundException | DAOException exc) {
exc.printStackTrace();
}
}
}
}
|
9233ad6d6da9d19565a4cf5beff1f9e154289caf | 2,105 | java | Java | SampleChargebee/src/test/java/com/invicara/chargebee/test/PlanTest.java | aloktech/AllProjects | 9a7f3318517083b2d0fa5313580bbf725b677989 | [
"Apache-2.0"
] | 1 | 2020-03-12T12:55:27.000Z | 2020-03-12T12:55:27.000Z | SampleChargebee/src/test/java/com/invicara/chargebee/test/PlanTest.java | aloktech/AllProjects | 9a7f3318517083b2d0fa5313580bbf725b677989 | [
"Apache-2.0"
] | 9 | 2021-09-20T20:36:53.000Z | 2022-03-08T21:11:25.000Z | SampleChargebee/src/test/java/com/invicara/chargebee/test/PlanTest.java | aloktech/AllProjects | 9a7f3318517083b2d0fa5313580bbf725b677989 | [
"Apache-2.0"
] | null | null | null | 27.697368 | 89 | 0.618052 | 996,661 | /*
* 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.invicara.chargebee.test;
import com.chargebee.models.Plan;
import com.invicara.chargebee.model.BIMPlan;
import com.invicara.chargebee.repository.PlanRepository;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;
import static com.invicara.chargebee.test.AbstractTest.injector;
/**
*
* @author alok
*/
public class PlanTest extends AbstractTest<PlanRepository> {
private final PlanRepository repository = injector.getInstance(PlanRepository.class);
@Test
public void test() {
// create();
getById();
// update();
// delete();
}
@Override
public void create() {
BIMPlan plan = new BIMPlan.BIMPlanBuilder()
.id("free-trial")
.name("Free Trial")
.invoiceName("Free Trial Plan")
.price(5000)
.build();
repository.setPlan(plan);
Optional<Plan> optional = repository.create();
optional.ifPresent(p -> {
Assert.assertEquals("Success", "free-trial", p.id());
});
}
@Override
public void getById() {
Optional<Plan> optional = repository.getById("free-trial");
optional.ifPresent(p -> {
Assert.assertEquals("Success", "free-trial", p.id());
});
}
@Override
public void update() {
boolean status = repository.updateById("free-trial", "Free Trial Plan A");
Assert.assertTrue(status);
Optional<Plan> optional = repository.getById("free-trial");
optional.ifPresent(p -> {
Assert.assertEquals("Success", "Free Trial Plan A", p.invoiceName());
});
}
@Override
public void delete() {
boolean status = repository.deleteById("free-trial");
Assert.assertTrue(status);
status = repository.deleteById("free-trial");
Assert.assertFalse(status);
}
}
|
9233adc8596398eb25b4c974671ba7999af32786 | 541 | java | Java | struts-example/src/main/java/com/mcnz/struts/HelloAction.java | learn-struts-fast/struts-tutorials | e5d0f80f8f5f2c7d0c54408e206c7fd9a0f33129 | [
"MIT"
] | null | null | null | struts-example/src/main/java/com/mcnz/struts/HelloAction.java | learn-struts-fast/struts-tutorials | e5d0f80f8f5f2c7d0c54408e206c7fd9a0f33129 | [
"MIT"
] | null | null | null | struts-example/src/main/java/com/mcnz/struts/HelloAction.java | learn-struts-fast/struts-tutorials | e5d0f80f8f5f2c7d0c54408e206c7fd9a0f33129 | [
"MIT"
] | 1 | 2020-09-13T20:05:29.000Z | 2020-09-13T20:05:29.000Z | 21.64 | 61 | 0.700555 | 996,662 | package com.mcnz.struts;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
@Action("/hello")
@Result(name = "success", location = "/results.jsp")
public class HelloAction {
public String execute() {
System.out.println("Value of firstname is: " + firstName);
return "success";
}
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
|
9233ae677edde5e889e4abf604cd6c5cec59b1ce | 936 | java | Java | aek-assets-web-api/src/main/java/com/aek/ebey/assets/web/feign/FileServerClientService.java | honghuixixi/aek-assets-service | 1281e320f934159989f28a33d362f8f633f139a3 | [
"Apache-2.0"
] | null | null | null | aek-assets-web-api/src/main/java/com/aek/ebey/assets/web/feign/FileServerClientService.java | honghuixixi/aek-assets-service | 1281e320f934159989f28a33d362f8f633f139a3 | [
"Apache-2.0"
] | null | null | null | aek-assets-web-api/src/main/java/com/aek/ebey/assets/web/feign/FileServerClientService.java | honghuixixi/aek-assets-service | 1281e320f934159989f28a33d362f8f633f139a3 | [
"Apache-2.0"
] | null | null | null | 34.666667 | 143 | 0.813034 | 996,663 | package com.aek.ebey.assets.web.feign;
import java.util.List;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import com.aek.common.core.Result;
import com.aek.ebey.assets.core.config.FeignMultipartSupportConfig;
/**
* 用户远程调用接口
*/
@FeignClient(value="${feign-fileserver.serviceId}", fallback = FileServerClientHystrix.class,configuration = FeignMultipartSupportConfig.class)
public interface FileServerClientService {
/**
* 文件上传接口
*/
@RequestMapping(method = RequestMethod.POST, value = "/upload2", consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public Result<List<Object>> upload(@RequestPart("files") MultipartFile files);
} |
9233af2c52d8623c79b2a33bef00c59367064d09 | 107 | java | Java | corpus/class/eclipse.jdt.ui/486.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.jdt.ui/486.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.jdt.ui/486.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 8.230769 | 24 | 0.570093 | 996,664 | //renaming I.m to k
package p;
interface I extends I2 {
void m();
}
interface I2 {
void m();
}
|
9233af32e39fc58a3b00705b723ba2a6a14b662d | 2,465 | java | Java | app/src/main/java/com/example/qrscore/fragment/QRGeneratorDialog.java | CMPUT301W22T20/QR-Score | 3a8ae4689f0a87874fec21ecc06315d679e41737 | [
"MIT"
] | 1 | 2022-02-10T21:54:49.000Z | 2022-02-10T21:54:49.000Z | app/src/main/java/com/example/qrscore/fragment/QRGeneratorDialog.java | CMPUT301W22T20/QR-Score | 3a8ae4689f0a87874fec21ecc06315d679e41737 | [
"MIT"
] | 32 | 2022-02-11T00:19:27.000Z | 2022-03-23T20:05:36.000Z | app/src/main/java/com/example/qrscore/fragment/QRGeneratorDialog.java | CMPUT301W22T20/QR-Score | 3a8ae4689f0a87874fec21ecc06315d679e41737 | [
"MIT"
] | null | null | null | 30.8125 | 132 | 0.680325 | 996,665 | package com.example.qrscore.fragment;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.example.qrscore.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
/**
* Purpose: Dialog to display the QR Code generated.
*
* Outstanding Issues:
*/
public class QRGeneratorDialog extends DialogFragment {
ImageView qrCode;
String email;
String userUID;
Boolean login;
String account;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Bundle mArgs = getArguments();
email = mArgs.getString("email");
userUID = mArgs.getString("userUID");
login = mArgs.getBoolean("login");
View view = inflater.inflate(R.layout.qr_generator_diaglog, container, false);
qrCode = view.findViewById(R.id.qr_generator_image_view);
if (getDialog() != null && getDialog().getWindow() != null) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
generateQR();
return view;
}
/**
* Purpose: Generate the QR Code and add it to the Dialog View.
*/
// https://www.youtube.com/watch?v=n8HdrLYL9DA
private void generateQR() {
MultiFormatWriter writer = new MultiFormatWriter();
if (login) {
account = email + "," + userUID;
}
else {
account = userUID + ",";
}
try {
BitMatrix bitMatrix = writer.encode(account, BarcodeFormat.QR_CODE, 600, 600);
BarcodeEncoder encoder = new BarcodeEncoder();
Bitmap bitmap = encoder.createBitmap(bitMatrix);
qrCode.setImageBitmap(bitmap);
}
catch (WriterException e) {
e.printStackTrace();
}
}
}
|
9233afe586cc7d33ed7a18cff67cbd9989a336bc | 21,808 | java | Java | heron/packing/tests/java/org/apache/heron/packing/CommonPackingTests.java | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 3,348 | 2016-05-25T16:04:31.000Z | 2018-03-28T17:46:14.000Z | heron/packing/tests/java/org/apache/heron/packing/CommonPackingTests.java | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 1,542 | 2016-05-25T16:46:44.000Z | 2018-03-29T17:30:23.000Z | heron/packing/tests/java/org/apache/heron/packing/CommonPackingTests.java | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 702 | 2016-05-25T16:07:43.000Z | 2018-03-27T06:31:07.000Z | 53.190244 | 100 | 0.668929 | 996,666 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.heron.packing;
import java.util.Map;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.apache.heron.api.generated.TopologyAPI;
import org.apache.heron.common.basics.ByteAmount;
import org.apache.heron.common.basics.Pair;
import org.apache.heron.common.utils.topology.TopologyTests;
import org.apache.heron.packing.exceptions.ConstraintViolationException;
import org.apache.heron.packing.utils.PackingUtils;
import org.apache.heron.spi.common.Config;
import org.apache.heron.spi.common.Context;
import org.apache.heron.spi.packing.IPacking;
import org.apache.heron.spi.packing.IRepacking;
import org.apache.heron.spi.packing.InstanceId;
import org.apache.heron.spi.packing.PackingPlan;
import org.apache.heron.spi.packing.Resource;
import org.apache.heron.spi.utils.PackingTestUtils;
import static org.apache.heron.packing.AssertPacking.DELTA;
/**
* There is some common functionality in multiple packing plans. This class contains common tests.
*/
public abstract class CommonPackingTests {
protected static final String BOLT_NAME = "bolt";
protected static final String SPOUT_NAME = "spout";
protected static final int DEFAULT_CONTAINER_PADDING_PERCENT = 10;
protected int spoutParallelism;
protected int boltParallelism;
protected Integer totalInstances;
protected org.apache.heron.api.Config topologyConfig;
protected TopologyAPI.Topology topology;
protected Resource instanceDefaultResources;
protected int numContainers;
protected abstract IPacking getPackingImpl();
protected abstract IRepacking getRepackingImpl();
@Before
public void setUp() {
this.spoutParallelism = 4;
this.boltParallelism = 3;
this.totalInstances = this.spoutParallelism + this.boltParallelism;
// Set up the topology and its config. Tests can safely modify the config by reference after the
// topology is created, but those changes will not be reflected in the underlying protobuf
// object Config and Topology objects. This is typically fine for packing tests since they don't
// access the protobuf values.
this.topologyConfig = new org.apache.heron.api.Config();
this.topologyConfig.setTopologyContainerMaxNumInstances(4);
this.topology = getTopology(spoutParallelism, boltParallelism, topologyConfig);
Config config = PackingTestUtils.newTestConfig(this.topology);
this.instanceDefaultResources = new Resource(
Context.instanceCpu(config), Context.instanceRam(config), Context.instanceDisk(config));
}
protected static TopologyAPI.Topology getTopology(int spoutParallelism, int boltParallelism,
org.apache.heron.api.Config topologyConfig) {
return TopologyTests.createTopology("testTopology", topologyConfig, SPOUT_NAME, BOLT_NAME,
spoutParallelism, boltParallelism);
}
protected PackingPlan pack(TopologyAPI.Topology testTopology) {
IPacking packing = getPackingImpl();
packing.initialize(PackingTestUtils.newTestConfig(testTopology), testTopology);
return packing.pack();
}
private PackingPlan repack(TopologyAPI.Topology testTopology,
PackingPlan initialPackingPlan,
Map<String, Integer> componentChanges) {
IRepacking repacking = getRepackingImpl();
repacking.initialize(PackingTestUtils.newTestConfig(testTopology), testTopology);
return repacking.repack(initialPackingPlan, componentChanges);
}
protected Resource getDefaultMaxContainerResource() {
return getDefaultMaxContainerResource(
PackingUtils.DEFAULT_MAX_NUM_INSTANCES_PER_CONTAINER);
}
protected Resource getDefaultMaxContainerResource(int maxNumInstancesPerContainer) {
return new Resource(this.instanceDefaultResources.getCpu() * maxNumInstancesPerContainer,
this.instanceDefaultResources.getRam().multiply(maxNumInstancesPerContainer),
this.instanceDefaultResources.getDisk().multiply(maxNumInstancesPerContainer));
}
protected Resource getDefaultUnspecifiedContainerResource(int testNumInstances,
int testNumContainers,
Resource padding) {
int largestContainerSize = (int) Math.ceil((double) testNumInstances / testNumContainers);
return new Resource(largestContainerSize + padding.getCpu(),
ByteAmount.fromGigabytes(largestContainerSize).plus(padding.getRam()),
ByteAmount.fromGigabytes(largestContainerSize).plus(padding.getDisk()));
}
protected PackingPlan doDefaultScalingTest(Map<String, Integer> componentChanges,
int numContainersBeforeRepack,
int numContainersAfterRepack,
Resource maxContainerResource) {
return doPackingAndScalingTest(topology, componentChanges,
instanceDefaultResources, boltParallelism,
instanceDefaultResources, spoutParallelism,
numContainersBeforeRepack, numContainersAfterRepack, maxContainerResource);
}
/**
* Performs a scaling test for a specific topology. It first
* computes an initial packing plan as a basis for scaling.
* Given specific component parallelism changes, a new packing plan is produced.
*
* @param testTopology Input topology
* @param componentChanges parallelism changes for scale up/down
* @param boltRes RAM allocated to bolts
* @param testBoltParallelism bolt parallelism
* @param spoutRes RAM allocated to spouts
* @param testSpoutParallelism spout parallelism
* @param numContainersBeforeRepack number of containers that the initial packing plan should use
* @param numContainersAfterRepack number of instances expected before scaling
* @return the new packing plan
*/
protected PackingPlan doPackingAndScalingTest(TopologyAPI.Topology testTopology,
Map<String, Integer> componentChanges,
Resource boltRes, int testBoltParallelism,
Resource spoutRes, int testSpoutParallelism,
int numContainersBeforeRepack,
int numContainersAfterRepack,
Resource maxContainerResource) {
PackingPlan packingPlan = doPackingTest(testTopology, boltRes, testBoltParallelism,
spoutRes, testSpoutParallelism, numContainersBeforeRepack, maxContainerResource);
PackingPlan newPackingPlan = doScalingTest(testTopology, packingPlan, componentChanges,
boltRes, testBoltParallelism, spoutRes, testSpoutParallelism,
numContainersAfterRepack, maxContainerResource);
return newPackingPlan;
}
protected PackingPlan doPackingTest(TopologyAPI.Topology testTopology,
Resource boltRes, int testBoltParallelism,
Resource spoutRes, int testSpoutParallelism,
int testNumContainers,
Resource maxContainerResource) {
PackingPlan packingPlan = pack(testTopology);
Assert.assertEquals(testNumContainers, packingPlan.getContainers().size());
Assert.assertEquals(testBoltParallelism + testSpoutParallelism,
(int) packingPlan.getInstanceCount());
AssertPacking.assertNumInstances(packingPlan.getContainers(), BOLT_NAME, testBoltParallelism);
AssertPacking.assertNumInstances(packingPlan.getContainers(), SPOUT_NAME, testSpoutParallelism);
AssertPacking.assertInstanceRam(packingPlan.getContainers(), BOLT_NAME, SPOUT_NAME,
boltRes.getRam(), spoutRes.getRam());
AssertPacking.assertInstanceCpu(packingPlan.getContainers(), BOLT_NAME, SPOUT_NAME,
boltRes.getCpu(), spoutRes.getCpu());
AssertPacking.assertInstanceIndices(packingPlan.getContainers(), BOLT_NAME, SPOUT_NAME);
AssertPacking.assertContainerRam(packingPlan.getContainers(), maxContainerResource.getRam());
AssertPacking.assertContainerCpu(packingPlan.getContainers(), maxContainerResource.getCpu());
return packingPlan;
}
protected PackingPlan doPackingTestWithPartialResource(TopologyAPI.Topology testTopology,
Optional<ByteAmount> boltRam,
Optional<Double> boltCpu,
int testBoltParallelism,
Optional<ByteAmount> spoutRam,
Optional<Double> spoutCpu,
int testSpoutParallelism,
int testNumContainers,
Resource padding,
Resource maxContainerResource) {
PackingPlan packingPlan = pack(testTopology);
Assert.assertEquals(testNumContainers, packingPlan.getContainers().size());
Assert.assertEquals(testBoltParallelism + testSpoutParallelism,
(int) packingPlan.getInstanceCount());
AssertPacking.assertNumInstances(packingPlan.getContainers(), BOLT_NAME, testBoltParallelism);
AssertPacking.assertNumInstances(packingPlan.getContainers(), SPOUT_NAME, testSpoutParallelism);
for (PackingPlan.ContainerPlan containerPlan : packingPlan.getContainers()) {
int instancesCount = containerPlan.getInstances().size();
if (!boltRam.isPresent() && !spoutRam.isPresent()) {
ByteAmount instanceRam = maxContainerResource.getRam()
.minus(padding.getRam()).divide(instancesCount);
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
Assert.assertEquals(instanceRam, instancePlan.getResource().getRam());
}
} else if (!boltRam.isPresent() || !spoutRam.isPresent()) {
String explicitComponent = boltRam.isPresent() ? BOLT_NAME : SPOUT_NAME;
String implicitComponent = boltRam.isPresent() ? SPOUT_NAME : BOLT_NAME;
ByteAmount explicitRam = boltRam.orElseGet(spoutRam::get);
int explicitCount = 0;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(explicitComponent)) {
Assert.assertEquals(explicitRam, instancePlan.getResource().getRam());
explicitCount++;
}
}
int implicitCount = instancesCount - explicitCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(implicitComponent)) {
Assert.assertEquals(
maxContainerResource.getRam()
.minus(explicitRam.multiply(explicitCount))
.minus(padding.getRam())
.divide(implicitCount),
instancePlan.getResource().getRam());
}
}
}
if (!boltCpu.isPresent() && !spoutCpu.isPresent()) {
double instanceCpu = (maxContainerResource.getCpu() - padding.getCpu()) / instancesCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
Assert.assertEquals(instanceCpu, instancePlan.getResource().getCpu(), DELTA);
}
} else if (!boltCpu.isPresent() || !spoutCpu.isPresent()) {
String explicitComponent = boltCpu.isPresent() ? BOLT_NAME : SPOUT_NAME;
String implicitComponent = boltCpu.isPresent() ? SPOUT_NAME : BOLT_NAME;
double explicitCpu = boltCpu.orElseGet(spoutCpu::get);
int explicitCount = 0;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(explicitComponent)) {
Assert.assertEquals(explicitCpu, instancePlan.getResource().getCpu(), DELTA);
explicitCount++;
}
}
int implicitCount = instancesCount - explicitCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(implicitComponent)) {
Assert.assertEquals(
(maxContainerResource.getCpu()
- explicitCpu * explicitCount
- padding.getCpu()) / implicitCount,
instancePlan.getResource().getCpu(), DELTA);
}
}
}
}
AssertPacking.assertInstanceIndices(packingPlan.getContainers(), BOLT_NAME, SPOUT_NAME);
AssertPacking.assertContainerRam(packingPlan.getContainers(), maxContainerResource.getRam());
AssertPacking.assertContainerCpu(packingPlan.getContainers(), maxContainerResource.getCpu());
return packingPlan;
}
protected PackingPlan doScalingTest(TopologyAPI.Topology testTopology,
PackingPlan packingPlan,
Map<String, Integer> componentChanges,
Resource boltRes, int testBoltParallelism,
Resource spoutRes, int testSpoutParallelism,
int testNumContainers,
Resource maxContainerResource) {
PackingPlan newPackingPlan = repack(testTopology, packingPlan, componentChanges);
Assert.assertEquals(testNumContainers, newPackingPlan.getContainers().size());
AssertPacking.assertInstanceRam(newPackingPlan.getContainers(), BOLT_NAME, SPOUT_NAME,
boltRes.getRam(), spoutRes.getRam());
AssertPacking.assertInstanceCpu(newPackingPlan.getContainers(), BOLT_NAME, SPOUT_NAME,
boltRes.getCpu(), spoutRes.getCpu());
// AssertPacking.assertInstanceIndices(newPackingPlan.getContainers(), BOLT_NAME, SPOUT_NAME);
AssertPacking.assertNumInstances(newPackingPlan.getContainers(), BOLT_NAME,
testBoltParallelism + componentChanges.getOrDefault(BOLT_NAME, 0));
AssertPacking.assertNumInstances(newPackingPlan.getContainers(), SPOUT_NAME,
testSpoutParallelism + componentChanges.getOrDefault(SPOUT_NAME, 0));
AssertPacking.assertContainerRam(newPackingPlan.getContainers(), maxContainerResource.getRam());
AssertPacking.assertContainerCpu(newPackingPlan.getContainers(), maxContainerResource.getCpu());
return newPackingPlan;
}
protected PackingPlan doScalingTestWithPartialResource(TopologyAPI.Topology testTopology,
PackingPlan packingPlan,
Map<String, Integer> componentChanges,
Optional<ByteAmount> boltRam,
Optional<Double> boltCpu,
int testBoltParallelism,
Optional<ByteAmount> spoutRam,
Optional<Double> spoutCpu,
int testSpoutParallelism,
int testNumContainers,
Resource padding,
Resource maxContainerResource) {
System.out.println(packingPlan);
PackingPlan newPackingPlan = repack(testTopology, packingPlan, componentChanges);
System.out.println(newPackingPlan);
Assert.assertEquals(testNumContainers, newPackingPlan.getContainers().size());
Assert.assertEquals(testBoltParallelism + testSpoutParallelism
+ componentChanges.getOrDefault(BOLT_NAME, 0)
+ componentChanges.getOrDefault(SPOUT_NAME, 0),
(int) newPackingPlan.getInstanceCount());
AssertPacking.assertNumInstances(newPackingPlan.getContainers(), BOLT_NAME,
testBoltParallelism + componentChanges.getOrDefault(BOLT_NAME, 0));
AssertPacking.assertNumInstances(newPackingPlan.getContainers(), SPOUT_NAME,
testSpoutParallelism + componentChanges.getOrDefault(SPOUT_NAME, 0));
for (PackingPlan.ContainerPlan containerPlan : newPackingPlan.getContainers()) {
int instancesCount = containerPlan.getInstances().size();
if (!boltRam.isPresent() && !spoutRam.isPresent()) {
ByteAmount instanceRam = maxContainerResource.getRam()
.minus(padding.getRam()).divide(instancesCount);
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
Assert.assertEquals(instanceRam, instancePlan.getResource().getRam());
}
} else if (!boltRam.isPresent() || !spoutRam.isPresent()) {
String explicitComponent = boltRam.isPresent() ? BOLT_NAME : SPOUT_NAME;
String implicitComponent = boltRam.isPresent() ? SPOUT_NAME : BOLT_NAME;
ByteAmount explicitRam = boltRam.orElseGet(spoutRam::get);
int explicitCount = 0;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(explicitComponent)) {
Assert.assertEquals(explicitRam, instancePlan.getResource().getRam());
explicitCount++;
}
}
int implicitCount = instancesCount - explicitCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(implicitComponent)) {
Assert.assertEquals(
maxContainerResource.getRam()
.minus(explicitRam.multiply(explicitCount))
.minus(padding.getRam())
.divide(implicitCount),
instancePlan.getResource().getRam());
}
}
}
if (!boltCpu.isPresent() && !spoutCpu.isPresent()) {
double instanceCpu = (maxContainerResource.getCpu() - padding.getCpu()) / instancesCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
Assert.assertEquals(instanceCpu, instancePlan.getResource().getCpu(), DELTA);
}
} else if (!boltCpu.isPresent() || !spoutCpu.isPresent()) {
String explicitComponent = boltCpu.isPresent() ? BOLT_NAME : SPOUT_NAME;
String implicitComponent = boltCpu.isPresent() ? SPOUT_NAME : BOLT_NAME;
double explicitCpu = boltCpu.orElseGet(spoutCpu::get);
int explicitCount = 0;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(explicitComponent)) {
Assert.assertEquals(explicitCpu, instancePlan.getResource().getCpu(), DELTA);
explicitCount++;
}
}
int implicitCount = instancesCount - explicitCount;
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
if (instancePlan.getComponentName().equals(implicitComponent)) {
Assert.assertEquals(
(maxContainerResource.getCpu()
- explicitCpu * explicitCount
- padding.getCpu()) / implicitCount,
instancePlan.getResource().getCpu(), DELTA);
}
}
}
}
AssertPacking.assertInstanceIndices(newPackingPlan.getContainers(), BOLT_NAME, SPOUT_NAME);
AssertPacking.assertContainerRam(newPackingPlan.getContainers(), maxContainerResource.getRam());
AssertPacking.assertContainerCpu(newPackingPlan.getContainers(), maxContainerResource.getCpu());
return newPackingPlan;
}
protected void doScaleDownTest(Pair<Integer, InstanceId>[] initialComponentInstances,
Map<String, Integer> componentChanges,
Pair<Integer, InstanceId>[] expectedComponentInstances)
throws ConstraintViolationException {
String topologyId = this.topology.getId();
// The padding percentage used in repack() must be <= one as used in pack(), otherwise we can't
// reconstruct the PackingPlan, see https://github.com/apache/incubator-heron/issues/1577
PackingPlan initialPackingPlan = PackingTestHelper.addToTestPackingPlan(
topologyId, null, PackingTestHelper.toContainerIdComponentNames(initialComponentInstances),
DEFAULT_CONTAINER_PADDING_PERCENT);
AssertPacking.assertPackingPlan(topologyId, initialComponentInstances, initialPackingPlan);
PackingPlan newPackingPlan = repack(this.topology, initialPackingPlan, componentChanges);
AssertPacking.assertPackingPlan(topologyId, expectedComponentInstances, newPackingPlan);
}
}
|
9233b0598f3dec6c6525db1a93980fd47bf18da7 | 3,703 | java | Java | runescape-client/src/main/java/Bounds.java | Magnusrn/runelite | c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/Bounds.java | Magnusrn/runelite | c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/Bounds.java | Magnusrn/runelite | c77297f6d6e0e78a37fcdefe88a8e61bf060d4d4 | [
"BSD-2-Clause"
] | null | null | null | 23 | 123 | 0.639752 | 996,667 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("nm")
@Implements("Bounds")
public class Bounds {
@ObfuscatedName("v")
@ObfuscatedGetter(
intValue = -1496433009
)
@Export("lowX")
public int lowX;
@ObfuscatedName("c")
@ObfuscatedGetter(
intValue = 1348899275
)
@Export("lowY")
public int lowY;
@ObfuscatedName("i")
@ObfuscatedGetter(
intValue = 2132855023
)
@Export("highX")
public int highX;
@ObfuscatedName("f")
@ObfuscatedGetter(
intValue = 1258662357
)
@Export("highY")
public int highY;
public Bounds(int var1, int var2, int var3, int var4) {
this.setLow(var1, var2); // L: 14
this.setHigh(var3, var4); // L: 15
}
public Bounds(int var1, int var2) {
this(0, 0, var1, var2); // L: 10
} // L: 11
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "(III)V",
garbageValue = "691768070"
)
@Export("setLow")
public void setLow(int var1, int var2) {
this.lowX = var1; // L: 19
this.lowY = var2; // L: 20
} // L: 21
@ObfuscatedName("c")
@ObfuscatedSignature(
descriptor = "(III)V",
garbageValue = "1684494436"
)
@Export("setHigh")
public void setHigh(int var1, int var2) {
this.highX = var1; // L: 24
this.highY = var2; // L: 25
} // L: 26
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(III)Z",
garbageValue = "2065555787"
)
public boolean method6944(int var1, int var2) {
return var1 >= this.lowX && var1 < this.lowX + this.highX && var2 >= this.lowY && var2 < this.highY + this.lowY; // L: 29
}
@ObfuscatedName("f")
@ObfuscatedSignature(
descriptor = "(Lnm;Lnm;I)V",
garbageValue = "1872281468"
)
public void method6945(Bounds var1, Bounds var2) {
this.method6946(var1, var2); // L: 37
this.method6947(var1, var2); // L: 38
} // L: 39
@ObfuscatedName("b")
@ObfuscatedSignature(
descriptor = "(Lnm;Lnm;S)V",
garbageValue = "3154"
)
void method6946(Bounds var1, Bounds var2) {
var2.lowX = this.lowX; // L: 42
var2.highX = this.highX; // L: 43
if (this.lowX < var1.lowX) { // L: 44
var2.highX = (var2.highX * 1363895823 - (var1.lowX * 1363895823 - this.lowX * 1363895823)) * 2132855023; // L: 45
var2.lowX = var1.lowX; // L: 46
}
if (var2.method6965() > var1.method6965()) { // L: 48
var2.highX -= var2.method6965() - var1.method6965(); // L: 49
}
if (var2.highX < 0) { // L: 51
var2.highX = 0;
}
} // L: 52
@ObfuscatedName("n")
@ObfuscatedSignature(
descriptor = "(Lnm;Lnm;B)V",
garbageValue = "0"
)
void method6947(Bounds var1, Bounds var2) {
var2.lowY = this.lowY; // L: 55
var2.highY = this.highY; // L: 56
if (this.lowY < var1.lowY) { // L: 57
var2.highY = (var2.highY * 446318461 - (var1.lowY * 446318461 - this.lowY * 446318461)) * 1258662357; // L: 58
var2.lowY = var1.lowY; // L: 59
}
if (var2.method6949() > var1.method6949()) { // L: 61
var2.highY -= var2.method6949() - var1.method6949(); // L: 62
}
if (var2.highY < 0) { // L: 64
var2.highY = 0;
}
} // L: 65
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "(B)I",
garbageValue = "44"
)
int method6965() {
return this.highX + this.lowX; // L: 68
}
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "-1934877561"
)
int method6949() {
return this.highY + this.lowY; // L: 72
}
public String toString() {
return null; // L: 33
}
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "(Lln;I)V",
garbageValue = "1725122550"
)
public static void method6969(AbstractArchive var0) {
} // L: 16
}
|
9233b138723c3cece6bb0ff527d5e5fe32294168 | 4,129 | java | Java | util-core/src/test/java/com/indeed/util/core/datastruct/TestIteratorMultiHeap.java | dsitze/util | f79aaa72a960a374092b49592038339a230b174a | [
"Apache-2.0"
] | 132 | 2015-01-24T20:37:45.000Z | 2022-02-07T08:47:12.000Z | util-core/src/test/java/com/indeed/util/core/datastruct/TestIteratorMultiHeap.java | dsitze/util | f79aaa72a960a374092b49592038339a230b174a | [
"Apache-2.0"
] | 19 | 2015-11-26T01:35:13.000Z | 2022-01-19T14:16:46.000Z | util-core/src/test/java/com/indeed/util/core/datastruct/TestIteratorMultiHeap.java | dsitze/util | f79aaa72a960a374092b49592038339a230b174a | [
"Apache-2.0"
] | 67 | 2015-01-09T16:53:51.000Z | 2021-11-11T11:30:19.000Z | 33.032 | 143 | 0.564786 | 996,668 | package com.indeed.util.core.datastruct;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
/**
* @author jplaisance
*/
public final class TestIteratorMultiHeap extends TestCase {
private static final Logger log = Logger.getLogger(TestIteratorMultiHeap.class);
public static final class RandomIntIterator {
Random random;
int length;
int value = 0;
int i = 0;
public RandomIntIterator(Random random, int length) {
this.random = random;
this.length = length;
}
boolean next() {
if (i >= length) return false;
value+=random.nextInt(4)+1;
i++;
return true;
}
int value() {
return value;
}
void reset(Random random, int length) {
value = 0;
this.random = random;
i = 0;
this.length = length;
}
}
public void testHeap() {
final Random[] randoms = new Random[24];
for (int i = 0; i < randoms.length; i++) {
randoms[i] = new Random(i);
}
final List<RandomIntIterator> iterators = Lists.newArrayList();
for (final Random random : randoms) {
iterators.add(new RandomIntIterator(random, random.nextInt(128) + 128));
}
final IteratorMultiHeap<RandomIntIterator> heap = new IteratorMultiHeap<RandomIntIterator>(iterators.size(), RandomIntIterator.class) {
@Override
protected boolean next(final RandomIntIterator randomIntIterator) {
return randomIntIterator.next();
}
@Override
protected int compare(final RandomIntIterator a, final RandomIntIterator b) {
return Ints.compare(a.value(), b.value());
}
};
for (RandomIntIterator iterator : iterators) {
heap.add(iterator);
}
doTest(heap);
heap.clear();
for (int i = 0; i < randoms.length; i++) {
final Random random = new Random(i);
final RandomIntIterator iterator = iterators.get(i);
iterator.reset(random, random.nextInt(128) + 128);
heap.add(iterator);
}
doTest(heap);
}
public void doTest(IteratorMultiHeap<RandomIntIterator> heap) {
final Random[] randoms = new Random[24];
for (int i = 0; i < randoms.length; i++) {
randoms[i] = new Random(i);
}
final PriorityQueue<RandomIntIterator> queue = new PriorityQueue<RandomIntIterator>(24, new Comparator<RandomIntIterator>() {
@Override
public int compare(final RandomIntIterator o1, final RandomIntIterator o2) {
return Ints.compare(o1.value(), o2.value());
}
});
for (final Random random : randoms) {
final RandomIntIterator iterator = new RandomIntIterator(random, random.nextInt(128) + 128);
assertTrue(iterator.next());
queue.add(iterator);
}
while (heap.next()) {
assertFalse(queue.isEmpty());
final List<RandomIntIterator> mins = Lists.newArrayList();
final RandomIntIterator minValue = queue.peek();
while (!queue.isEmpty() && minValue.value() == queue.peek().value()) {
mins.add(queue.poll());
}
final RandomIntIterator[] min = heap.getMin();
final int minLength = heap.getMinLength();
assertEquals(mins.size(), minLength);
for (int i = 0; i < minLength; i++) {
assertEquals(minValue.value(), min[i].value());
}
for (RandomIntIterator iterator : mins) {
if (iterator.next()) {
queue.add(iterator);
}
}
}
assertTrue(queue.isEmpty());
}
}
|
9233b19764719cee2ad34bff89f5930a0770e858 | 3,858 | java | Java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/Statistics.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 1 | 2019-04-21T21:56:44.000Z | 2019-04-21T21:56:44.000Z | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/Statistics.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 110 | 2019-11-11T19:37:58.000Z | 2021-07-16T18:23:58.000Z | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/Statistics.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 1 | 2022-02-01T10:50:58.000Z | 2022-02-01T10:50:58.000Z | 28.791045 | 137 | 0.617418 | 996,669 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.iot.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A map of key-value pairs for all supported statistics. Currently, only count is supported.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Statistics implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The count of things that match the query.
* </p>
*/
private Integer count;
/**
* <p>
* The count of things that match the query.
* </p>
*
* @param count
* The count of things that match the query.
*/
public void setCount(Integer count) {
this.count = count;
}
/**
* <p>
* The count of things that match the query.
* </p>
*
* @return The count of things that match the query.
*/
public Integer getCount() {
return this.count;
}
/**
* <p>
* The count of things that match the query.
* </p>
*
* @param count
* The count of things that match the query.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Statistics withCount(Integer count) {
setCount(count);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCount() != null)
sb.append("Count: ").append(getCount());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Statistics == false)
return false;
Statistics other = (Statistics) obj;
if (other.getCount() == null ^ this.getCount() == null)
return false;
if (other.getCount() != null && other.getCount().equals(this.getCount()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCount() == null) ? 0 : getCount().hashCode());
return hashCode;
}
@Override
public Statistics clone() {
try {
return (Statistics) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iot.model.transform.StatisticsMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
9233b1b62eece12888dbeda5739699413efbc455 | 2,564 | java | Java | src/main/java/com/alipay/api/response/ZhimaMerchantOrderCreditPayResponse.java | guyueyingmu/alipay-sdk-java-all | 049aefbfa067197c2b559976a5f780a59f2030ca | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/ZhimaMerchantOrderCreditPayResponse.java | guyueyingmu/alipay-sdk-java-all | 049aefbfa067197c2b559976a5f780a59f2030ca | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/ZhimaMerchantOrderCreditPayResponse.java | guyueyingmu/alipay-sdk-java-all | 049aefbfa067197c2b559976a5f780a59f2030ca | [
"Apache-2.0"
] | 1 | 2019-07-25T11:28:09.000Z | 2019-07-25T11:28:09.000Z | 18.852941 | 79 | 0.716459 | 996,670 | package com.alipay.api.response;
import java.util.Date;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: zhima.merchant.order.credit.pay response.
*
* @author auto create
* @since 1.0, 2018-07-27 09:35:00
*/
public class ZhimaMerchantOrderCreditPayResponse extends AlipayResponse {
private static final long serialVersionUID = 3585638321936343459L;
/**
* 支付宝生成的资金流水号,用于商户与支付宝进行对账,无支付行为时为空
*/
@ApiField("alipay_fund_order_no")
private String alipayFundOrderNo;
/**
* 此字段来源于商户创建订单时传入的值,帮助商户定位订单来源
*/
@ApiField("channel")
private String channel;
/**
* 支付失败原因描述
*/
@ApiField("message")
private String message;
/**
* 外部订单号
*/
@ApiField("out_order_no")
private String outOrderNo;
/**
* 商户传入的资金交易号,无支付行为时为空
*/
@ApiField("out_trans_no")
private String outTransNo;
/**
* 本次处理支付金额,单位为元,精确到小数点后两位,无支付行为时为空
*/
@ApiField("pay_amount")
private String payAmount;
/**
* 支付结果状态,包括:支付成功(PAY_SUCCESS),支付失败(PAY_FAILED),支付处理中(PAY_INPROGRESS),无支付行为时为空
*/
@ApiField("pay_status")
private String payStatus;
/**
* 支付处理时间,无支付行为时为空
*/
@ApiField("pay_time")
private Date payTime;
/**
* 芝麻订单号,最长32位
*/
@ApiField("zm_order_no")
private String zmOrderNo;
public void setAlipayFundOrderNo(String alipayFundOrderNo) {
this.alipayFundOrderNo = alipayFundOrderNo;
}
public String getAlipayFundOrderNo( ) {
return this.alipayFundOrderNo;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getChannel( ) {
return this.channel;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage( ) {
return this.message;
}
public void setOutOrderNo(String outOrderNo) {
this.outOrderNo = outOrderNo;
}
public String getOutOrderNo( ) {
return this.outOrderNo;
}
public void setOutTransNo(String outTransNo) {
this.outTransNo = outTransNo;
}
public String getOutTransNo( ) {
return this.outTransNo;
}
public void setPayAmount(String payAmount) {
this.payAmount = payAmount;
}
public String getPayAmount( ) {
return this.payAmount;
}
public void setPayStatus(String payStatus) {
this.payStatus = payStatus;
}
public String getPayStatus( ) {
return this.payStatus;
}
public void setPayTime(Date payTime) {
this.payTime = payTime;
}
public Date getPayTime( ) {
return this.payTime;
}
public void setZmOrderNo(String zmOrderNo) {
this.zmOrderNo = zmOrderNo;
}
public String getZmOrderNo( ) {
return this.zmOrderNo;
}
}
|
9233b2b4e66d55aef7883d8f9ef04c5409cf19aa | 597 | java | Java | random-beans-java8/src/test/java/io/github/benas/randombeans/randomizers/java8/ZonedDateTimeRandomizerTest.java | feckertson/jPopulator | 80ef630abe345f793ccd61efa703084f2b955f7a | [
"MIT"
] | 1 | 2018-12-29T22:55:45.000Z | 2018-12-29T22:55:45.000Z | random-beans-java8/src/test/java/io/github/benas/randombeans/randomizers/java8/ZonedDateTimeRandomizerTest.java | feckertson/jPopulator | 80ef630abe345f793ccd61efa703084f2b955f7a | [
"MIT"
] | null | null | null | random-beans-java8/src/test/java/io/github/benas/randombeans/randomizers/java8/ZonedDateTimeRandomizerTest.java | feckertson/jPopulator | 80ef630abe345f793ccd61efa703084f2b955f7a | [
"MIT"
] | 2 | 2018-01-25T18:59:03.000Z | 2019-07-23T20:00:52.000Z | 23.88 | 79 | 0.745394 | 996,671 | package io.github.benas.randombeans.randomizers.java8;
import org.junit.Before;
import org.junit.Test;
import java.time.ZonedDateTime;
import static org.assertj.core.api.Assertions.assertThat;
public class ZonedDateTimeRandomizerTest {
private ZonedDateTimeRandomizer zonedDateTimeRandomizer;
@Before
public void setUp() {
zonedDateTimeRandomizer = new ZonedDateTimeRandomizer();
}
@Test
public void getRandomValue() {
ZonedDateTime zonedDateTime = zonedDateTimeRandomizer.getRandomValue();
assertThat(zonedDateTime).isNotNull();
}
}
|
9233b3a940a9535aa29caf9a127f5e2633784f0d | 7,172 | java | Java | src/source/Collection.java | ShuYiBin/PostmanToRetrofit2 | fb27c013ccb0ca7b481f1b4a7b28330c2088f831 | [
"MIT"
] | 21 | 2019-01-15T09:35:10.000Z | 2022-03-29T02:09:24.000Z | src/source/Collection.java | ShuYiBin/PostmanToRetrofit2 | fb27c013ccb0ca7b481f1b4a7b28330c2088f831 | [
"MIT"
] | 2 | 2021-02-12T22:07:35.000Z | 2021-05-24T04:04:49.000Z | src/source/Collection.java | ShuYiBin/PostmanToRetrofit2 | fb27c013ccb0ca7b481f1b4a7b28330c2088f831 | [
"MIT"
] | 6 | 2019-06-01T08:08:11.000Z | 2021-12-07T10:39:30.000Z | 25.342756 | 76 | 0.443252 | 996,672 | package source;
import java.util.List;
public class Collection {
private InfoBean info;
private List<?> variables;
private List<ItemBean> item;
public InfoBean getInfo() {
return info;
}
public void setInfo(InfoBean info) {
this.info = info;
}
public List<?> getVariables() {
return variables;
}
public void setVariables(List<?> variables) {
this.variables = variables;
}
public List<ItemBean> getItem() {
return item;
}
public void setItem(List<ItemBean> item) {
this.item = item;
}
public static class InfoBean {
private String name;
private String _postman_id;
private String description;
private String schema;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String get_postman_id() {
return _postman_id;
}
public void set_postman_id(String _postman_id) {
this._postman_id = _postman_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
public static class ItemBean {
private String name;
private RequestBean request;
private List<?> response;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RequestBean getRequest() {
return request;
}
public void setRequest(RequestBean request) {
this.request = request;
}
public List<?> getResponse() {
return response;
}
public void setResponse(List<?> response) {
this.response = response;
}
public static class RequestBean {
private Object url;
private String method;
private BodyBean body;
private String description;
private List<HeaderBean> header;
public Object getUrl() {
return url;
}
public void setUrl(Object url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public BodyBean getBody() {
return body;
}
public void setBody(BodyBean body) {
this.body = body;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<HeaderBean> getHeader() {
return header;
}
public void setHeader(List<HeaderBean> header) {
this.header = header;
}
public static class BodyBean {
private String mode;
private List<UrlencodedBean> urlencoded;
private List<FormdataBean> formdata;
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public List<UrlencodedBean> getUrlencoded() {
return urlencoded;
}
public void setUrlencoded(List<UrlencodedBean> urlencoded) {
this.urlencoded = urlencoded;
}
public List<FormdataBean> getFormdata() {
return formdata;
}
public void setFormdata(List<FormdataBean> formdata) {
this.formdata = formdata;
}
public static class UrlencodedBean {
private String key;
private String value;
private String description;
private String type;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public static class FormdataBean {
private String key;
private String value;
private String type;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
}
public static class HeaderBean {
private String key;
private String value;
private String description;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
}
}
|
9233b4359e7e8655298c3759f5a92ff96896a117 | 786 | java | Java | example/card-operations/src/test/java/com/ddd/BalanceArchitectureOnionTest.java | XavierLevaux/101-ddd | 219189bd8ecee6b6971693d3b122b154f0c9328e | [
"Apache-2.0"
] | 6 | 2021-08-10T17:10:25.000Z | 2022-01-22T16:47:28.000Z | example/card-operations/src/test/java/com/ddd/BalanceArchitectureOnionTest.java | XavierLevaux/101-ddd | 219189bd8ecee6b6971693d3b122b154f0c9328e | [
"Apache-2.0"
] | 13 | 2021-07-04T18:47:37.000Z | 2021-12-01T21:28:00.000Z | example/card-operations/src/test/java/com/ddd/BalanceArchitectureOnionTest.java | XavierLevaux/101-ddd | 219189bd8ecee6b6971693d3b122b154f0c9328e | [
"Apache-2.0"
] | 3 | 2021-09-11T17:14:42.000Z | 2021-12-04T16:09:11.000Z | 35.727273 | 101 | 0.703562 | 996,673 | package com.ddd;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.library.Architectures.onionArchitecture;
@AnalyzeClasses(packages = "com.ddd.balance", importOptions = {ImportOption.DoNotIncludeTests.class})
public class BalanceArchitectureOnionTest {
@ArchTest
static final ArchRule follow_onion_architecture_structure =
onionArchitecture()
.domainModels("..domain.model..")
.domainServices("..domain.service..")
.applicationServices("..application..")
.adapter("rest", "..infrastructure.rest..");
}
|
9233b5f384a728a1c7f6264227ea63c40ab5745c | 94 | java | Java | src/test/java/com/typemapper/namedresult/results/Enumeration.java | JanGorman/sproc-spring-mapper | 705d6cad1967aadb401667b7ad2b14e7bb7e70e4 | [
"Apache-2.0"
] | 1 | 2015-08-03T12:12:22.000Z | 2015-08-03T12:12:22.000Z | src/test/java/com/typemapper/namedresult/results/Enumeration.java | JanGorman/sproc-spring-mapper | 705d6cad1967aadb401667b7ad2b14e7bb7e70e4 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/typemapper/namedresult/results/Enumeration.java | JanGorman/sproc-spring-mapper | 705d6cad1967aadb401667b7ad2b14e7bb7e70e4 | [
"Apache-2.0"
] | 1 | 2019-05-08T06:24:27.000Z | 2019-05-08T06:24:27.000Z | 11.75 | 43 | 0.776596 | 996,674 | package com.typemapper.namedresult.results;
public enum Enumeration {
VALUE_1, VALUE_2
}
|
9233b66e1cd9646459fcf065b3a42cd1dd857049 | 653 | java | Java | app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java | aramadsanar/udacity-QuakeReport | 3609b5778adb73cdc8ac860259c1e7528d7f77ab | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java | aramadsanar/udacity-QuakeReport | 3609b5778adb73cdc8ac860259c1e7528d7f77ab | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java | aramadsanar/udacity-QuakeReport | 3609b5778adb73cdc8ac860259c1e7528d7f77ab | [
"Apache-2.0"
] | null | null | null | 27.208333 | 73 | 0.735069 | 996,675 | package com.example.android.quakereport;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import java.util.List;
import static com.example.android.quakereport.EarthquakeActivity.LOG_TAG;
public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>> {
private String mURL = "";
public EarthquakeLoader(Context context, String url) {
super(context);
mURL = url;
}
@Override
public List<Earthquake> loadInBackground() {
Log.d(LOG_TAG, "Invoking background downloader!!");
return DownloadUtility.fetchEarthquakeData(mURL);
}
}
|
9233b71b95960d73208f15ad1278b126152f2332 | 554 | java | Java | app/src/main/java/info/nissiy/gridlayoutsample/Util.java | zzztuzzz/Android-RecyclerEndressScroll | d62c3301873d689f2e6298e5e11b6aa7aa97d959 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/info/nissiy/gridlayoutsample/Util.java | zzztuzzz/Android-RecyclerEndressScroll | d62c3301873d689f2e6298e5e11b6aa7aa97d959 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/info/nissiy/gridlayoutsample/Util.java | zzztuzzz/Android-RecyclerEndressScroll | d62c3301873d689f2e6298e5e11b6aa7aa97d959 | [
"Apache-2.0"
] | null | null | null | 30.777778 | 108 | 0.747292 | 996,676 | package info.nissiy.gridlayoutsample;
import android.content.Context;
import android.content.res.Configuration;
public class Util {
private Util() {
}
//横回転の2-3列化
public static boolean isLandscape(Context context) {
System.out.println("isLandscape:context"+ context.getResources().getConfiguration().orientation );
System.out.println("isLandscape:configuration"+ Configuration.ORIENTATION_LANDSCAPE);
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
}
|
9233b754558ace6142755a6803a5e1318373aace | 1,900 | java | Java | fabric-renderer-indigo/src/main/java/net/fabricmc/fabric/mixin/client/indigo/renderer/MixinAmbientOcclusionCalculator.java | williewillus/fabric | e09978fc7cfa296e23e6dce33c12bb7b94af2681 | [
"Apache-2.0"
] | 1,433 | 2018-11-14T10:51:06.000Z | 2022-03-30T09:53:45.000Z | fabric-renderer-indigo/src/main/java/net/fabricmc/fabric/mixin/client/indigo/renderer/MixinAmbientOcclusionCalculator.java | williewillus/fabric | e09978fc7cfa296e23e6dce33c12bb7b94af2681 | [
"Apache-2.0"
] | 1,663 | 2018-11-18T08:34:53.000Z | 2022-03-29T16:39:17.000Z | fabric-renderer-indigo/src/main/java/net/fabricmc/fabric/mixin/client/indigo/renderer/MixinAmbientOcclusionCalculator.java | williewillus/fabric | e09978fc7cfa296e23e6dce33c12bb7b94af2681 | [
"Apache-2.0"
] | 465 | 2018-11-08T00:14:30.000Z | 2022-03-27T14:14:25.000Z | 35.185185 | 165 | 0.784737 | 996,677 | /*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.fabric.mixin.client.indigo.renderer;
import java.util.BitSet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockRenderView;
import net.fabricmc.fabric.impl.client.indigo.renderer.accessor.AccessAmbientOcclusionCalculator;
@Mixin(targets = "net.minecraft.client.render.block.BlockModelRenderer$AmbientOcclusionCalculator")
public abstract class MixinAmbientOcclusionCalculator implements AccessAmbientOcclusionCalculator {
@Shadow private float[] brightness;
@Shadow private int[] light;
@Shadow
public abstract void apply(BlockRenderView blockRenderView, BlockState blockState, BlockPos pos, Direction face, float[] aoData, BitSet controlBits, boolean shade);
@Override
public float[] fabric_colorMultiplier() {
return brightness;
}
@Override
public int[] fabric_brightness() {
return light;
}
@Override
public void fabric_apply(BlockRenderView blockRenderView, BlockState blockState, BlockPos pos, Direction face, float[] aoData, BitSet controlBits, boolean shade) {
apply(blockRenderView, blockState, pos, face, aoData, controlBits, shade);
}
}
|
9233b76d31531537542129161412affa84be5ddc | 250 | java | Java | litecart/src/test/java/stqa/litecart/com/Tests/LiteCartLoginTest.java | K7Gt/java_selenium-fg | 9409b4ced135a3394b321a17ec24294ee72da398 | [
"Apache-2.0"
] | null | null | null | litecart/src/test/java/stqa/litecart/com/Tests/LiteCartLoginTest.java | K7Gt/java_selenium-fg | 9409b4ced135a3394b321a17ec24294ee72da398 | [
"Apache-2.0"
] | null | null | null | litecart/src/test/java/stqa/litecart/com/Tests/LiteCartLoginTest.java | K7Gt/java_selenium-fg | 9409b4ced135a3394b321a17ec24294ee72da398 | [
"Apache-2.0"
] | null | null | null | 13.888889 | 50 | 0.668 | 996,678 | package stqa.litecart.com.Tests;
import org.junit.Test;
public class LiteCartLoginTest extends TestBase {
@Test
public void testLogin() {
app.getNavigationHelper().gotoAdminPage();
app.getHelperBase().login();
}
}
|
9233b8678278fb785ec086ba9c93d6951bb48bbd | 1,385 | java | Java | library/src/main/java/com/zenchn/inspection/library/eventbus/EventCenter.java | dxxxyy/MvpBaseApp-master | 08b93bfe28998b4ba234caa28127c9e3ec861f1e | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/zenchn/inspection/library/eventbus/EventCenter.java | dxxxyy/MvpBaseApp-master | 08b93bfe28998b4ba234caa28127c9e3ec861f1e | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/zenchn/inspection/library/eventbus/EventCenter.java | dxxxyy/MvpBaseApp-master | 08b93bfe28998b4ba234caa28127c9e3ec861f1e | [
"Apache-2.0"
] | null | null | null | 22 | 75 | 0.626984 | 996,679 | /*
* Copyright (c) 2015 efpyi@example.com | tchen0707@gmail.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.zenchn.inspection.library.eventbus;
/**
* Author: xuxu
* Date: 2017/6/29
* Description:
*/
public class EventCenter<T> {
/**
* reserved data
*/
private T data;
/**
* this code distinguish between different events
*/
private int eventCode = -1;
public EventCenter(int eventCode) {
this(eventCode, null);
}
public EventCenter(int eventCode, T data) {
this.eventCode = eventCode;
this.data = data;
}
/**
* get event code
*
* @return
*/
public int getEventCode() {
return this.eventCode;
}
/**
* get event reserved data
*
* @return
*/
public T getData() {
return this.data;
}
}
|
9233b8afedf4ff949968785e1cb856c05e1476cf | 1,602 | java | Java | app/src/main/java/com/lezhitech/mobilesafe/activity/BaseSetupActivity.java | gogoDoPeter/mobileSafeSample | 10f1ad79288561d3986403fd405d9a6a16bb68dd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lezhitech/mobilesafe/activity/BaseSetupActivity.java | gogoDoPeter/mobileSafeSample | 10f1ad79288561d3986403fd405d9a6a16bb68dd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lezhitech/mobilesafe/activity/BaseSetupActivity.java | gogoDoPeter/mobileSafeSample | 10f1ad79288561d3986403fd405d9a6a16bb68dd | [
"Apache-2.0"
] | null | null | null | 30.807692 | 102 | 0.622347 | 996,680 | package com.lezhitech.mobilesafe.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public abstract class BaseSetupActivity extends AppCompatActivity {
private GestureDetector gestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//2,创建手势管理对象,用作管理在onTouchEvent(MotionEvent event)中传递过来的手势动作
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//监听手势的移动
if (e1.getX() - e2.getX() > 0) {
//从右向左滑动,下一页
showNextPage();
}
if (e1.getX() - e2.getX() < 0) {
//从左向右滑动,上一页
showPrePage();
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
protected abstract void showNextPage();
protected abstract void showPrePage();
//1,监听屏幕上响应的事件类型
@Override
public boolean onTouchEvent(MotionEvent event) {
//3,通过手势处理类接收多种类型事件,用于处理
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
public void nextPage(View view){
showNextPage();
}
public void prePage(View view){
showPrePage();
}
}
|
9233b8da21e202fcf77bd52bb99b507e4aa84498 | 4,795 | java | Java | src/main/java/com/blockchaintp/sawtooth/timekeeper/processor/ParticipantTimeState.java | blockchaintp/timekeeper | df7b13b1b08a8fae9c2a49973d9a36c90b322407 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/blockchaintp/sawtooth/timekeeper/processor/ParticipantTimeState.java | blockchaintp/timekeeper | df7b13b1b08a8fae9c2a49973d9a36c90b322407 | [
"Apache-2.0"
] | 3 | 2021-06-25T10:35:16.000Z | 2021-09-29T04:52:06.000Z | src/main/java/com/blockchaintp/sawtooth/timekeeper/processor/ParticipantTimeState.java | blockchaintp/timekeeper | df7b13b1b08a8fae9c2a49973d9a36c90b322407 | [
"Apache-2.0"
] | 1 | 2020-06-30T17:05:35.000Z | 2020-06-30T17:05:35.000Z | 33.298611 | 114 | 0.708029 | 996,681 | /*
* Copyright 2019 Blockchain Technology Partners
*
* 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.blockchaintp.sawtooth.timekeeper.processor;
import java.util.ArrayList;
import java.util.List;
import com.blockchaintp.sawtooth.timekeeper.exceptions.TimeKeeperException;
import com.blockchaintp.sawtooth.timekeeper.protobuf.TimeKeeperRecord;
import com.blockchaintp.sawtooth.timekeeper.protobuf.TimeKeeperRecord.Builder;
import com.blockchaintp.sawtooth.timekeeper.protobuf.TimeKeeperUpdate;
import com.blockchaintp.sawtooth.timekeeper.protobuf.TimeKeeperVersion;
import com.google.protobuf.Timestamp;
/**
* Handles the time values of a given participant.
*/
public final class ParticipantTimeState {
/**
* Default maximum history to keep.
*/
private static final int DEFAULT_MAX_HISTORY = 100;
private static final int DEFAULT_MAX_DEVIATION = 200;
private Timestamp currentTime;
private List<Timestamp> history;
private TimeKeeperVersion version;
private int maxHistory;
private int maxDeviation;
/**
* Create a new ParticipantTimeState based on the provided record.
*
* @param tkRecord
* the record of this participant
*/
public ParticipantTimeState(final TimeKeeperRecord tkRecord) {
this.history = new ArrayList<>();
this.currentTime = tkRecord.getLastCalculatedTime();
history.addAll(tkRecord.getTimeHistoryList());
this.version = tkRecord.getVersion();
this.maxDeviation = DEFAULT_MAX_DEVIATION;
this.maxHistory = DEFAULT_MAX_HISTORY;
}
/**
* Create an initial state from an individual TimeKeeperUpdate.
*
* @param update
* the update to initialize with
*/
public ParticipantTimeState(final TimeKeeperUpdate update) {
currentTime = update.getTimeUpdate();
history = new ArrayList<>(List.of(update.getTimeUpdate()));
this.version = update.getVersion();
if (TimeKeeperVersion.V_1_0.equals(this.version)) {
this.maxHistory = DEFAULT_MAX_HISTORY;
this.maxDeviation = DEFAULT_MAX_DEVIATION;
} else {
this.maxHistory = update.getMaxHistory();
this.maxDeviation = update.getMaxDeviation();
}
}
/**
* Update this time state with and update from this participant.
*
* @param update
* the update
* @throws TimeKeeperException
* when an incorrect style of update is sent to this ParticipantTimeState
*/
public void addUpdate(final TimeKeeperUpdate update) throws TimeKeeperException {
if (update.getVersion().equals(TimeKeeperVersion.V_1_0)) {
// Then we have a TimeKeeperVersion.V_1_0 update
if (!this.version.equals(TimeKeeperVersion.V_1_0)) {
// a version one update to greater than version one record
// This should throw an error, no backsteps
throw new TimeKeeperException(
String.format("Invalid update version=%s for record version=%s", update.getVersion(), this.version));
}
} else {
// then this is other than TimeKeeperVersion.V_1_0 update
if (this.version.equals(TimeKeeperVersion.V_1_0)) {
// upgrade the record
this.version = update.getVersion();
}
if (update.getMaxDeviation() > 0) {
this.maxDeviation = update.getMaxDeviation();
}
if (update.getMaxHistory() > 0) {
this.maxHistory = update.getMaxHistory();
}
}
history.add(update.getTimeUpdate());
currentTime = TimestampUtils.max(currentTime, history);
pruneHistory();
}
private void pruneHistory() {
if (history.size() > maxHistory) {
history = history.subList(history.size() - maxHistory, history.size());
}
}
/**
* Reify this state as a TimeKeeperRecord.
*
* @return the record
*/
public TimeKeeperRecord toTimeKeeperRecord() {
Builder builder = TimeKeeperRecord.newBuilder().setLastCalculatedTime(currentTime).addAllTimeHistory(history);
if (!version.equals(TimeKeeperVersion.V_1_0)) {
builder = builder.setVersion(this.version);
if (maxDeviation != DEFAULT_MAX_DEVIATION) {
builder = builder.setMaxDeviation(maxDeviation);
}
if (maxHistory != DEFAULT_MAX_HISTORY) {
builder = builder.setMaxHistory(maxHistory);
}
}
return builder.build();
}
}
|
9233ba072501db6f3c62dc0cf570f89700a85f59 | 1,400 | java | Java | api/src/main/java/codes/writeonce/deltastore/api/SmartIterator.java | alexey-romenskiy/deltastore | fdf2b64183f39c0cc75d9fda09a04c4d883b6f8e | [
"Apache-2.0"
] | null | null | null | api/src/main/java/codes/writeonce/deltastore/api/SmartIterator.java | alexey-romenskiy/deltastore | fdf2b64183f39c0cc75d9fda09a04c4d883b6f8e | [
"Apache-2.0"
] | null | null | null | api/src/main/java/codes/writeonce/deltastore/api/SmartIterator.java | alexey-romenskiy/deltastore | fdf2b64183f39c0cc75d9fda09a04c4d883b6f8e | [
"Apache-2.0"
] | 1 | 2021-11-18T13:02:57.000Z | 2021-11-18T13:02:57.000Z | 21.538462 | 95 | 0.571429 | 996,682 | package codes.writeonce.deltastore.api;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
public interface SmartIterator<T> extends Iterator<T>, Spliterator<T>, Supplier<T>, Closeable {
default boolean skip() {
if (hasNext()) {
next();
return true;
} else {
return false;
}
}
default int skip(int count) {
int skipped = 0;
while (skipped < count && skip()) {
skipped++;
}
return skipped;
}
@Nonnull
@Override
default T next() throws NoSuchElementException {
final var next = get();
if (next == null) {
throw new NoSuchElementException();
}
return next;
}
@Override
@Nullable
T get();
@Override
default void forEachRemaining(Consumer<? super T> action) {
requireNonNull(action);
while (true) {
final var next = get();
if (next == null) {
break;
}
action.accept(next);
}
}
@Override
default void close() {
// empty
}
}
|
9233bac0cb5589fdfab085de5a98f24754cf6760 | 2,591 | java | Java | javacord-core/src/main/java/org/javacord/core/util/logging/LoggerUtil.java | PhoenixInvertigo/Javacord | c770bfd99899bdb85b01530eeb186dd59a0eb239 | [
"Apache-2.0"
] | 3 | 2018-07-15T01:59:02.000Z | 2021-04-13T00:43:58.000Z | javacord-core/src/main/java/org/javacord/core/util/logging/LoggerUtil.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 1 | 2018-12-28T01:43:24.000Z | 2018-12-28T01:43:24.000Z | javacord-core/src/main/java/org/javacord/core/util/logging/LoggerUtil.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 3 | 2018-04-17T08:09:38.000Z | 2018-07-17T17:54:26.000Z | 37.014286 | 120 | 0.640293 | 996,683 | package org.javacord.core.util.logging;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.simple.SimpleLogger;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.ProviderUtil;
import org.javacord.api.util.logging.FallbackLoggerConfiguration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* This class is used to get a {@link Logger} instance.
*/
public class LoggerUtil {
private static final AtomicReference<Boolean> initialized = new AtomicReference<>(false);
private static final AtomicBoolean noLogger = new AtomicBoolean();
private static final Map<String, Logger> loggers = new ConcurrentHashMap<>();
/**
* Get or create a logger with the given name.
*
* @param name The name of the logger.
* @return The logger with the given name.
*/
public static Logger getLogger(String name) {
AtomicBoolean logWarning = new AtomicBoolean(false);
initialized.updateAndGet(initialized -> {
if (!initialized && !ProviderUtil.hasProviders()) {
noLogger.set(true);
logWarning.set(true);
}
return true;
});
if (noLogger.get()) {
return loggers.computeIfAbsent(name, key -> {
Level level = FallbackLoggerConfiguration.isTraceEnabled()
? Level.TRACE
: (FallbackLoggerConfiguration.isDebugEnabled() ? Level.DEBUG : Level.INFO);
Logger logger = new SimpleLogger(name, level, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
new PropertiesUtil(new Properties()), System.out);
if (logWarning.get()) {
logger.info("No Log4j2 compatible logger was found. Using default Javacord implementation!");
}
return new PrivacyProtectionLogger(logger);
});
} else {
return new PrivacyProtectionLogger(LogManager.getLogger(name));
}
}
/**
* Gets or creates a logger for the given name.
*
* @param clazz The class of the logger.
* @return A logger for the given class.
*/
public static Logger getLogger(Class clazz) {
return getLogger(clazz.getName());
}
}
|
9233bbf8e150e0b72def5fea625b7cc00300a304 | 4,199 | java | Java | aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/ContainerRecipeSummaryMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/ContainerRecipeSummaryMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/ContainerRecipeSummaryMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 53.151899 | 158 | 0.763039 | 996,684 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.imagebuilder.model.transform;
import java.util.Map;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.imagebuilder.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ContainerRecipeSummaryMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ContainerRecipeSummaryMarshaller {
private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("arn").build();
private static final MarshallingInfo<String> CONTAINERTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("containerType").build();
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("name").build();
private static final MarshallingInfo<String> PLATFORM_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("platform").build();
private static final MarshallingInfo<String> OWNER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("owner").build();
private static final MarshallingInfo<String> PARENTIMAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("parentImage").build();
private static final MarshallingInfo<String> DATECREATED_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("dateCreated").build();
private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("tags").build();
private static final ContainerRecipeSummaryMarshaller instance = new ContainerRecipeSummaryMarshaller();
public static ContainerRecipeSummaryMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ContainerRecipeSummary containerRecipeSummary, ProtocolMarshaller protocolMarshaller) {
if (containerRecipeSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerRecipeSummary.getArn(), ARN_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getContainerType(), CONTAINERTYPE_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getName(), NAME_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getPlatform(), PLATFORM_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getOwner(), OWNER_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getParentImage(), PARENTIMAGE_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getDateCreated(), DATECREATED_BINDING);
protocolMarshaller.marshall(containerRecipeSummary.getTags(), TAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
9233bc1b84e39db542c737b40fff13ffab5c1092 | 8,651 | java | Java | src/app/voltdb/voltdb_src/src/frontend/org/voltdb/export/StreamBlock.java | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/src/frontend/org/voltdb/export/StreamBlock.java | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/src/frontend/org/voltdb/export/StreamBlock.java | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | 35.747934 | 110 | 0.686973 | 996,685 | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.export;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicInteger;
import org.voltcore.utils.DBBPool.BBContainer;
import org.voltdb.VoltDB;
import org.voltdb.exportclient.ExportRowSchema;
import org.voltdb.exportclient.PersistedMetadata;
import org.voltdb.iv2.UniqueIdGenerator;
import org.voltdb.utils.BinaryDequeReader;
/*
* The stream block has a default reference count of 1 for being in the queue.
* It acquires another if it is handed of for processing in another thread.
*
* This prevents the memory from being deallocated when the data is pushed to disk
* as part of a sync. In those scenarios we let the processing thread deallocate
* when it is finished, and the ack will handle deleting the persisted version of the block.
*
* For buffers that are disk backed they won't go through that
* transition without the coop of the processor so there is no race.
*
* There are basically two schemes for tracking data, reference counting for managing allocations
* and acking for the logical stream data and they serve different purposes. Acking determines
* when the data needs to go away. Reference counting is just there to gracefully handle data being
* pushed to disk while it is being processed.
*
* Interactions with disk based data are serialized through the ExportDataSource thread while
* freeing the memory can be done safely from either thread because the allocator is concurrent.
*/
public class StreamBlock {
// start seq number(8) + committed seq number (8) + row count(4) + uniqueId (8)
public static final int HEADER_SIZE = 28;
public static final int SEQUENCE_NUMBER_OFFSET = 0;
public static final int COMMIT_SEQUENCE_NUMBER_OFFSET = 8;
public static final int ROW_NUMBER_OFFSET = 16;
public static final int UNIQUE_ID_OFFSET = 20;
private final AtomicInteger m_refCount = new AtomicInteger(1);
private final long m_startSequenceNumber;
private final long m_committedSequenceNumber;
private final int m_rowCount;
private final long m_uniqueId;
private final long m_totalSize;
private final BinaryDequeReader.Entry<PersistedMetadata> m_entry;
// index of the last row that has been released.
private int m_releaseOffset = -1;
// If true free entry rather than releasing it
private volatile boolean m_freeOnly = false;
public static StreamBlock from(BinaryDequeReader.Entry<PersistedMetadata> entry) {
ByteBuffer b = entry.getData();
b.order(ByteOrder.LITTLE_ENDIAN);
long seqNo = b.getLong(StreamBlock.SEQUENCE_NUMBER_OFFSET);
long committedSeqNo = b.getLong(StreamBlock.COMMIT_SEQUENCE_NUMBER_OFFSET);
int tupleCount = b.getInt(StreamBlock.ROW_NUMBER_OFFSET);
long uniqueId = b.getLong(StreamBlock.UNIQUE_ID_OFFSET);
return new StreamBlock(entry, seqNo, committedSeqNo, tupleCount, uniqueId);
}
public StreamBlock(BinaryDequeReader.Entry<PersistedMetadata> entry, long startSequenceNumber,
long committedSequenceNumber, int rowCount, long uniqueId) {
assert(entry != null);
m_entry = entry;
m_startSequenceNumber = startSequenceNumber;
m_committedSequenceNumber = committedSequenceNumber;
m_rowCount = rowCount;
m_uniqueId = uniqueId;
// The first 20 bytes are space for us to store the sequence number, row count and uniqueId
// if we end up persisting
m_entry.getData().position(HEADER_SIZE);
m_totalSize = m_entry.getData().remaining();
}
/*
* Call discard on the underlying buffer used for storage
*/
public void discard() {
decrementReference(false);
}
public ExportRowSchema getSchema() {
return m_entry.getExtraHeader().getSchema();
}
public PersistedMetadata getMetadata() {
return m_entry.getExtraHeader();
}
public long startSequenceNumber() {
return m_startSequenceNumber;
}
public long lastSequenceNumber() {
return m_startSequenceNumber + m_rowCount - 1;
}
public long committedSequenceNumber() {
return m_committedSequenceNumber;
}
/**
* Returns the sequence number of the first unreleased export row in this block
*/
public long unreleasedSequenceNumber()
{
return m_startSequenceNumber + m_releaseOffset + 1;
}
public int rowCount() {
return m_rowCount;
}
public long uniqueId() {
return m_uniqueId;
}
public long getTimestampMs() {
return UniqueIdGenerator.getTimestampFromUniqueId(m_uniqueId);
}
public long getTimestamp() {
return getTimestampMs() * 1000;
}
/**
* Returns the total amount of bytes in the stream
* @return
*/
public long totalSize() {
return m_totalSize;
}
/**
* Returns the number of the unreleased rows in this block.
*/
long unreleasedRowCount()
{
return m_rowCount - (m_releaseOffset + 1);
}
// The sequence number for export rows up to which are being released
public void releaseTo(long releaseSequenceNumber)
{
assert(releaseSequenceNumber >= m_startSequenceNumber);
m_releaseOffset = releaseSequenceNumber >= lastSequenceNumber() ?
(m_rowCount - 1) : (int)(releaseSequenceNumber - m_startSequenceNumber);
}
/**
* Use this when we need a copy BBContainer with refcount incremented.
*
* @return A BBContainer with same bytes. Discard of the returned BBContainer will trigger a
* discard on this BBContainer when all the references are released.
*/
public BBContainer unreleasedContainer() {
m_refCount.incrementAndGet();
return getRefCountingContainer(m_entry.getData().slice().asReadOnlyBuffer());
}
private BBContainer getRefCountingContainer(ByteBuffer buf) {
return new BBContainer(buf) {
@Override
public void discard() {
checkDoubleFree();
StreamBlock.this.discard();
}
};
}
/**
* Put header data at the start of the ByteBuffer and return a container wrapping it for read-only access.
*
* Does not increment the refcount, uses the implicit 1 count
* and should only be called once to get a container for pushing the data to disk.
*/
public BBContainer asBBContainer() {
ByteBuffer b = m_entry.getData();
b.order(ByteOrder.LITTLE_ENDIAN);
b.putLong(SEQUENCE_NUMBER_OFFSET, startSequenceNumber());
b.putLong(COMMIT_SEQUENCE_NUMBER_OFFSET, committedSequenceNumber());
b.putInt(ROW_NUMBER_OFFSET, rowCount());
b.putLong(UNIQUE_ID_OFFSET, uniqueId());
b.order(ByteOrder.BIG_ENDIAN);
ByteBuffer view = b.asReadOnlyBuffer();
view.position(SEQUENCE_NUMBER_OFFSET);
return getRefCountingContainer(view);
}
/**
* Free the memory backed by this entry but do not release the entries
*/
public void free() {
decrementReference(true);
}
private void decrementReference(boolean freeOnly) {
m_freeOnly |= freeOnly;
final int count = m_refCount.decrementAndGet();
if (count == 0) {
if (m_freeOnly) {
m_entry.free();
} else {
m_entry.release();
}
} else if (count < 0) {
VoltDB.crashLocalVoltDB("Broken refcounting in export", true, null);
}
}
@Override
public String toString() {
return "StreamBlock [m_startSequenceNumber=" + m_startSequenceNumber + ", m_committedSequenceNumber="
+ m_committedSequenceNumber + ", m_rowCount=" + m_rowCount + ", m_uniqueId=" + m_uniqueId
+ ", m_totalSize=" + m_totalSize + "]";
}
}
|
9233bd12b85ad3c5ba432e55eb8e71d64e76abdb | 900 | java | Java | src/main/java/com/hugeinc/web/SolrSpringWebApplicationInitializer.java | napoleon1889/solr-barcore | 42bff43c2a4bbf5b4d66220d354d6bf409689dee | [
"MIT"
] | null | null | null | src/main/java/com/hugeinc/web/SolrSpringWebApplicationInitializer.java | napoleon1889/solr-barcore | 42bff43c2a4bbf5b4d66220d354d6bf409689dee | [
"MIT"
] | 1 | 2022-01-21T23:13:13.000Z | 2022-01-21T23:13:13.000Z | src/main/java/com/hugeinc/web/SolrSpringWebApplicationInitializer.java | napoleon1889/solr-barcore | 42bff43c2a4bbf5b4d66220d354d6bf409689dee | [
"MIT"
] | null | null | null | 34.615385 | 99 | 0.827778 | 996,686 | package com.hugeinc.web;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class SolrSpringWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(SolrSpringConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"dispatcher", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/app/*");
}
}
|
9233bd28fc45441dc30964fc8ca5397089b915a3 | 1,482 | java | Java | src/main/java/org/netbeans/modules/atom/electron/actions/RunAction.java | Mario-S/netbeans-electron-support | 3fb33dc12be64a0dd96334d6d6712c47b5a93b3d | [
"Apache-2.0"
] | 1 | 2016-06-17T21:57:30.000Z | 2016-06-17T21:57:30.000Z | src/main/java/org/netbeans/modules/atom/electron/actions/RunAction.java | Mario-S/netbeans-electron-support | 3fb33dc12be64a0dd96334d6d6712c47b5a93b3d | [
"Apache-2.0"
] | 2 | 2015-11-01T22:02:16.000Z | 2015-11-14T10:50:15.000Z | src/main/java/org/netbeans/modules/atom/electron/actions/RunAction.java | Mario-S/netbeans-electron-support | 3fb33dc12be64a0dd96334d6d6712c47b5a93b3d | [
"Apache-2.0"
] | null | null | null | 36.146341 | 118 | 0.753711 | 996,687 | package org.netbeans.modules.atom.electron.actions;
import static org.netbeans.modules.atom.electron.cmd.AbstractCommandFactory.createCommand;
import java.awt.event.ActionEvent;
import org.netbeans.api.extexecution.ExecutionService;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.loaders.DataObject;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Build",
id = "org.netbeans.modules.atom.electron.RunAction"
)
@ActionRegistration(
displayName = "#CTL_RunAction"
)
@ActionReferences({
@ActionReference(path = "Shortcuts", name = "C-F6"),
@ActionReference(path = "Loaders/text/javascript/Actions", position = 655),
@ActionReference(path = "Editors/text/javascript/Popup", position = 5055)
})
@Messages("CTL_RunAction=Run with Electron")
public class RunAction extends AbstractElectronAction {
private static final String PROCESS_NAME = "Electron";
public RunAction(DataObject context) {
super(context);
DefaultCommandType type = createCommandType(DefaultCommandType.Type.ELECTRON_RUN);
setCommand(createCommand(type));
}
@Override
public void actionPerformed(ActionEvent ev) {
ExecutionService service = ExecutionService.newService(createProcessBuilder(), getDescriptor(), PROCESS_NAME);
createObserver().observe(service.run());
}
}
|
9233bddf23240dc575e60de0519d9490d7e9af47 | 3,789 | java | Java | archive/icbm/sentry/platform/gui/GuiTurretPlatform.java | Jorch72/ICBM | bd09eeeca326be958e4801778cd3e572cf6f9018 | [
"Unlicense"
] | null | null | null | archive/icbm/sentry/platform/gui/GuiTurretPlatform.java | Jorch72/ICBM | bd09eeeca326be958e4801778cd3e572cf6f9018 | [
"Unlicense"
] | null | null | null | archive/icbm/sentry/platform/gui/GuiTurretPlatform.java | Jorch72/ICBM | bd09eeeca326be958e4801778cd3e572cf6f9018 | [
"Unlicense"
] | null | null | null | 43.056818 | 239 | 0.67696 | 996,688 | package icbm.sentry.platform.gui;
import icbm.Reference;
import icbm.sentry.interfaces.IEnergyTurret;
import icbm.sentry.interfaces.IEnergyWeapon;
import icbm.sentry.interfaces.IWeaponProvider;
import icbm.sentry.platform.TileTurretPlatform;
import icbm.sentry.turret.block.TileTurret;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.ForgeDirection;
import org.lwjgl.opengl.GL11;
import resonant.lib.gui.GuiContainerBase;
import resonant.lib.render.EnumColor;
import universalelectricity.api.energy.IEnergyContainer;
import universalelectricity.api.energy.UnitDisplay.Unit;
public class GuiTurretPlatform extends GuiContainerBase
{
public static final ResourceLocation TERMINAL_TEXTURE = new ResourceLocation(Reference.DOMAIN, Reference.GUI_PATH + "gui_platform_terminal.png");
private TileTurretPlatform tile;
public GuiTurretPlatform(EntityPlayer player, TileTurretPlatform tile)
{
super(new ContainerTurretPlatform(player.inventory, tile));
this.tile = tile;
}
/** Draw the foreground layer for the GuiContainer (everything in front of the items) */
@Override
public void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
this.fontRenderer.drawString(tile.getInvName(), 52, 6, 4210752);
// TODO: Add different directions in the future.
TileTurret turret = tile.getTurret(ForgeDirection.UP);
if (turret != null)
{
//TODO: re-add when rotation is implemented for sentries
//fontRenderer.drawString("Position: " + ForgeDirection.UP, 8, 20, 4210752);
if (turret.getTurret() instanceof IEnergyContainer && ((IEnergyContainer) turret.getTurret()).getEnergyCapacity(ForgeDirection.UNKNOWN) > 0)
{
fontRenderer.drawString(EnumColor.BRIGHT_GREEN + "Energy", 8, 30, 4210752);
renderUniversalDisplay(8, 40, ((IEnergyContainer) turret.getTurret()).getEnergy(ForgeDirection.UNKNOWN), ((IEnergyContainer) turret.getTurret()).getEnergyCapacity(ForgeDirection.UNKNOWN), mouseX, mouseY, Unit.JOULES, true);
}
if (turret.getTurret() instanceof IEnergyTurret)
{
fontRenderer.drawString(EnumColor.BRIGHT_GREEN + "Per Tick Cost", 8, 50, 4210752);
renderUniversalDisplay(8, 60, ((IEnergyTurret) turret.getTurret()).getRunningCost(), mouseX, mouseY, Unit.JOULES, true);
}
if (turret.getTurret() instanceof IWeaponProvider && ((IWeaponProvider) turret.getTurret()).getWeaponSystem() instanceof IEnergyWeapon)
{
fontRenderer.drawString(EnumColor.BRIGHT_GREEN + "Weapon Cost", 8, 75, 4210752);
renderUniversalDisplay(8, 85, ((IEnergyWeapon) ((IWeaponProvider) turret.getTurret()).getWeaponSystem()).getEnergyPerShot(), mouseX, mouseY, Unit.JOULES, true);
}
}
}
/** Draw the background layer for the GuiContainer (everything behind the items) */
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int x, int y)
{
super.drawGuiContainerBackgroundLayer(par1, x, y);
this.mc.renderEngine.bindTexture(TERMINAL_TEXTURE);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// drawTexturedModalRect(this.containerWidth, this.containerHeight, 0, 0, this.xSize,
// this.ySize);
for (int xSlot = 0; xSlot < 4; xSlot++)
{
for (int ySlot = 0; ySlot < 3; ySlot++)
{
this.drawSlot(95 + 18 * xSlot - 1, 18 + 18 * ySlot - 1);
}
}
for (int xSlot = 0; xSlot < 4; xSlot++)
{
this.drawSlot(95 + 18 * xSlot - 1, 89);
}
}
} |
9233be6252dc8a1f37bfc75d13b1fb4d1c456a1d | 1,431 | java | Java | servicebus/azure-spring-cloud-stream-binder-servicebus-queue/servicebus-queue-binder/src/main/java/com/azure/spring/sample/servicebus/queue/binder/ServiceProducerController.java | Netyyyy/azure-spring-boot-samples | 803e5a1f54bb00c67e298f3877eca7a96834e5fc | [
"MIT"
] | 35 | 2021-07-12T02:34:31.000Z | 2022-03-31T03:23:55.000Z | servicebus/azure-spring-cloud-stream-binder-servicebus-queue/servicebus-queue-binder/src/main/java/com/azure/spring/sample/servicebus/queue/binder/ServiceProducerController.java | Netyyyy/azure-spring-boot-samples | 803e5a1f54bb00c67e298f3877eca7a96834e5fc | [
"MIT"
] | 106 | 2021-07-05T07:45:10.000Z | 2022-03-30T03:13:29.000Z | servicebus/azure-spring-cloud-stream-binder-servicebus-queue/servicebus-queue-binder/src/main/java/com/azure/spring/sample/servicebus/queue/binder/ServiceProducerController.java | Netyyyy/azure-spring-boot-samples | 803e5a1f54bb00c67e298f3877eca7a96834e5fc | [
"MIT"
] | 69 | 2021-06-24T03:58:01.000Z | 2022-03-31T03:23:56.000Z | 35.775 | 105 | 0.781272 | 996,689 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.sample.servicebus.queue.binder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Sinks;
@RestController
@Profile("manual")
public class ServiceProducerController {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusQueueBinderApplication.class);
@Autowired
private Sinks.Many<Message<String>> many;
@PostMapping("/messages")
public ResponseEntity<String> sendMessage(@RequestParam String message) {
LOGGER.info("Going to add message {} to Sinks.Many.", message);
many.emitNext(MessageBuilder.withPayload(message).build(), Sinks.EmitFailureHandler.FAIL_FAST);
return ResponseEntity.ok("Sent!");
}
@GetMapping("/")
public String welcome() {
return "welcome";
}
}
|
9233bee2ec0ded8182671bccfe3c56554f90b48d | 5,774 | java | Java | src/main/java/krpc/rpc/impl/DefaultProxyGenerator.java | bruceran/krpc | 33c83d78574a472e3cbfc75afa87ec57253cc90c | [
"Apache-2.0"
] | 43 | 2018-05-26T02:31:46.000Z | 2022-02-25T08:15:30.000Z | src/main/java/krpc/rpc/impl/DefaultProxyGenerator.java | jeffreyxqf/krpc | fbfcdb4fecef515077e848d119a1deacd6d80c17 | [
"Apache-2.0"
] | 6 | 2020-03-04T21:42:54.000Z | 2022-03-31T18:34:36.000Z | src/main/java/krpc/rpc/impl/DefaultProxyGenerator.java | jeffreyxqf/krpc | fbfcdb4fecef515077e848d119a1deacd6d80c17 | [
"Apache-2.0"
] | 21 | 2018-08-04T08:55:13.000Z | 2022-02-25T08:13:07.000Z | 50.649123 | 197 | 0.623311 | 996,690 | package krpc.rpc.impl;
import javassist.*;
import krpc.rpc.core.ProxyGenerator;
import krpc.rpc.core.ReflectionUtils;
import krpc.rpc.core.RpcCallable;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.Map;
public class DefaultProxyGenerator implements ProxyGenerator {
ClassPool pool;
ClassLoader loader;
public DefaultProxyGenerator() {
loader = Thread.currentThread().getContextClassLoader();
pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
}
public Object generateReferer(Class<?> intf, RpcCallable callable) {
try {
String infName = intf.getName();
String packageName = getPackageName(infName);
String implPackageName = packageName + ".proxy";
String implSimpleName = intf.getSimpleName() + "Proxy";
String implClsName = implPackageName + "." + implSimpleName;
CtClass cls = pool.makeClass(implClsName);
cls.addInterface(pool.get(infName));
cls.addField(CtField.make("private krpc.rpc.core.RpcCallable client;", cls));
cls.addConstructor(CtNewConstructor.make("public " + implSimpleName + "(krpc.rpc.core.RpcCallable client) {this.client = client;}", cls));
// public LoginRes login(LoginReq req) { return (LoginRes)client.call(100,1,req); }
int serviceId = ReflectionUtils.getServiceId(intf);
if (serviceId <= 1) throw new RuntimeException("serviceId must > 1");
HashMap<Integer, String> msgIdMap = ReflectionUtils.getMsgIds(intf);
HashMap<String, Object> msgNameMap = ReflectionUtils.getMethodInfo(intf);
for (Map.Entry<Integer, String> entry : msgIdMap.entrySet()) {
int msgId = entry.getKey();
String msgName = entry.getValue();
if (msgId < 1) throw new RuntimeException("msgId must > 0");
Class<?> reqCls = (Class<?>) msgNameMap.get(msgName + "-req");
Class<?> resCls = (Class<?>) msgNameMap.get(msgName + "-res");
StringBuilder code = new StringBuilder();
code.append("public ").append(resCls.getName()).append(" ").append(msgName);
code.append("(").append(reqCls.getName()).append(" req)");
code.append("{ return (").append(resCls.getName()).append(")client.call(").append(serviceId).append(",").append(msgId).append(",req);").append("}");
cls.addMethod(CtNewMethod.make(code.toString(), cls));
}
ProtectionDomain pd = getClass().getProtectionDomain();
Class<?> proxyClass = cls.toClass(loader, pd);
return ReflectionUtils.newRefererObject(proxyClass, callable);
} catch (Exception e) {
throw new RuntimeException("generateReferer exception", e);
}
}
public Object generateAsyncReferer(Class<?> intf, RpcCallable callable) {
try {
String infName = intf.getName();
String packageName = getPackageName(infName);
String implPackageName = packageName + ".proxy";
String implSimpleName = intf.getSimpleName() + "Proxy";
String implClsName = implPackageName + "." + implSimpleName;
CtClass cls = pool.makeClass(implClsName);
cls.addInterface(pool.get(infName));
cls.addField(CtField.make("private krpc.rpc.core.RpcCallable client;", cls));
cls.addConstructor(CtNewConstructor.make("public " + implSimpleName + "(krpc.rpc.core.RpcCallable client) {this.client = client;}", cls));
int serviceId = ReflectionUtils.getServiceId(intf);
if (serviceId <= 1) throw new RuntimeException("serviceId must > 1");
HashMap<Integer, String> msgIdMap = ReflectionUtils.getMsgIds(intf);
HashMap<String, Object> msgNameMap = ReflectionUtils.getAsyncMethodInfo(intf);
for (Map.Entry<Integer, String> entry : msgIdMap.entrySet()) {
int msgId = entry.getKey();
String msgName = entry.getValue();
if (msgId < 1) throw new RuntimeException("msgId must > 0");
Class<?> reqCls = (Class<?>) msgNameMap.get(msgName + "-req");
//Class<?> resCls = (Class<?>)msgNameMap.get(msgName+"-res");
StringBuilder code = new StringBuilder();
// template is not supported by javassist
/*
code.append("public java.util.concurrent.CompletableFuture<").append(resCls.getName()).append("> ").append(msgName);
code.append("(").append(reqCls.getName()).append(" req)");
code.append("{ return (java.util.concurrent.CompletableFuture<").append(resCls.getName()).append(">)client.callAsync(").append(serviceId).append(",").append(msgId).append(",req);").append("}");
*/
code.append("public java.util.concurrent.CompletableFuture ").append(msgName);
code.append("(").append(reqCls.getName()).append(" req)");
code.append("{ return (java.util.concurrent.CompletableFuture)client.callAsync(").append(serviceId).append(",").append(msgId).append(",req);").append("}");
cls.addMethod(CtNewMethod.make(code.toString(), cls));
}
ProtectionDomain pd = getClass().getProtectionDomain();
Class<?> proxyClass = cls.toClass(loader, pd);
return ReflectionUtils.newRefererObject(proxyClass, callable);
} catch (Exception e) {
throw new RuntimeException("generateReferer exception", e);
}
}
String getPackageName(String clsName) {
int p = clsName.lastIndexOf(".");
return clsName.substring(0, p);
}
}
|
9233c0a782539e5a7761715ad8afb2f87ce93c8d | 3,893 | java | Java | hive-udfs/src/main/java/com/thenetcircle/service/data/hive/udf/commons/UDFCfgs.java | John1Tang/data-misc-tools | a2bbec49f066deb5126739292d73ad8ed77ad800 | [
"Apache-2.0"
] | 3 | 2020-06-12T06:40:25.000Z | 2022-02-18T06:49:17.000Z | hive-udfs/src/main/java/com/thenetcircle/service/data/hive/udf/commons/UDFCfgs.java | John1Tang/data-misc-tools | a2bbec49f066deb5126739292d73ad8ed77ad800 | [
"Apache-2.0"
] | null | null | null | hive-udfs/src/main/java/com/thenetcircle/service/data/hive/udf/commons/UDFCfgs.java | John1Tang/data-misc-tools | a2bbec49f066deb5126739292d73ad8ed77ad800 | [
"Apache-2.0"
] | null | null | null | 44.747126 | 139 | 0.737221 | 996,691 | package com.thenetcircle.service.data.hive.udf.commons;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StandardMapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static java.lang.String.format;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardMapObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaStringObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils.PrimitiveGrouping.STRING_GROUP;
@Description(
name = "cfgs",
value = "_FUNC_(key_regex_pattern:string, value_regex_pattern:string) - return variables whose keys or values match the regex pattern")
@UDFType(deterministic = true, stateful = false, distinctLike = true)
public class UDFCfgs extends GenericUDF {
public static final StandardMapObjectInspector CFGS_INSP = getStandardMapObjectInspector(
javaStringObjectInspector,
javaStringObjectInspector
);
private transient StringObjectInspector patternStrInsp;
private transient StandardMapObjectInspector retInsp;
private transient PrimitiveCategory[] inputTypes = new PrimitiveCategory[1];
@Override
public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
checkArgsSize(args, 0, 1);
if (args.length == 0) {
return CFGS_INSP;
}
checkArgPrimitive(args, 0);
checkArgGroups(args, 0, inputTypes, STRING_GROUP);
if (!(args[0] instanceof StringObjectInspector)) {
throw new UDFArgumentTypeException(0, "Pattern parameter must be String:\n\t" + args[0]);
}
patternStrInsp = (StringObjectInspector) args[0];
return CFGS_INSP;
}
@Override
public Object evaluate(DeferredObject[] args) throws HiveException {
LinkedHashMap<String, String> reMap = new LinkedHashMap<>();
DeferredObject keyPatternArg = args[0];
String keyPatternStr = patternStrInsp.getPrimitiveJavaObject(keyPatternArg);
DeferredObject valuePatternArg = args[1];
String valuePatternStr = patternStrInsp.getPrimitiveJavaObject(valuePatternArg);
SessionState ss = SessionState.get();
Set<Map.Entry<Object, Object>> entries = ss.getConf().getAllProperties().entrySet();
Pattern kp = StringUtils.isNoneBlank(keyPatternStr) ? Pattern.compile(keyPatternStr) : null;
Pattern vp = StringUtils.isNoneBlank(valuePatternStr) ? Pattern.compile(valuePatternStr) : null;
for (Map.Entry<Object, Object> en : entries) {
String keyStr = en.getKey().toString();
String valStr = String.valueOf(en.getValue());
if ((kp == null || kp.matcher(keyStr).find())
&& (vp == null || vp.matcher(valStr).find())) {
reMap.put(keyStr, valStr);
}
}
return reMap;
}
@Override
public String getDisplayString(String[] children) {
return format("cfgs(%s)", StringUtils.join(children, ", "));
}
}
|
9233c0cfc815a6354ba6ed04c504f7067eb4e375 | 756 | java | Java | src/main/java/ui/tools/menuTools/JMenusItems/ExitJMenuItem.java | PeterSalamun/NEMESYS-application | bb8ac772b6e22ea9a2e53e459a142c7e19133474 | [
"MIT"
] | null | null | null | src/main/java/ui/tools/menuTools/JMenusItems/ExitJMenuItem.java | PeterSalamun/NEMESYS-application | bb8ac772b6e22ea9a2e53e459a142c7e19133474 | [
"MIT"
] | null | null | null | src/main/java/ui/tools/menuTools/JMenusItems/ExitJMenuItem.java | PeterSalamun/NEMESYS-application | bb8ac772b6e22ea9a2e53e459a142c7e19133474 | [
"MIT"
] | null | null | null | 25.2 | 72 | 0.665344 | 996,692 | package ui.tools.menuTools.JMenusItems;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ExitJMenuItem extends BasicJMenuItem {
//Constructor
public ExitJMenuItem(JMenu parent, String name) {
super(parent, name);
}
//MODIFIES: JMenuItem
//EFFECTS: adds Listener to JMenuItem
@Override
protected void addListener() {
menuItem.addActionListener(new ExitJMenuItemClickHandler());
}
private class ExitJMenuItemClickHandler implements ActionListener {
//EFFECTS: Ends application
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.exit(0);
}
}
}
|
9233c0f2ea30c35f76097f75385931391e203571 | 2,529 | java | Java | tcwebhooks-core/src/main/java/webhook/teamcity/auth/bearer/BearerAuthenticator.java | wegtam/tcWebHooks | 58655bb05d2fe93830a15cb9b25845b327bd2518 | [
"MIT"
] | 134 | 2015-07-17T09:14:53.000Z | 2022-03-21T07:18:12.000Z | tcwebhooks-core/src/main/java/webhook/teamcity/auth/bearer/BearerAuthenticator.java | wegtam/tcWebHooks | 58655bb05d2fe93830a15cb9b25845b327bd2518 | [
"MIT"
] | 171 | 2015-01-24T01:58:20.000Z | 2022-03-21T06:04:48.000Z | tcwebhooks-core/src/main/java/webhook/teamcity/auth/bearer/BearerAuthenticator.java | wegtam/tcWebHooks | 58655bb05d2fe93830a15cb9b25845b327bd2518 | [
"MIT"
] | 33 | 2015-07-15T23:26:06.000Z | 2020-09-01T11:41:44.000Z | 42.15 | 138 | 0.786872 | 996,693 | package webhook.teamcity.auth.bearer;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.impl.client.BasicAuthCache;
import webhook.teamcity.auth.AbstractWebHookAuthenticator;
import webhook.teamcity.auth.WebHookAuthenticator;
public class BearerAuthenticator extends AbstractWebHookAuthenticator implements WebHookAuthenticator {
public static final String BEARER_AUTH_SCHEME_TYPE = "Bearer";
public static final String KEY_BEARER = "bearer";
public static final String KEY_REALM = "realm";
@Override
public void addAuthentication(CredentialsProvider credentialsProvider, HttpClientContext httpClientContext, String url) {
if (config.getParameters().containsKey(KEY_BEARER)){
URI uri = URI.create(url);
RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();
BearerAuthSchemeFactory bearerAuthSchemeFactory = new BearerAuthSchemeFactory();
Registry<AuthSchemeProvider> authSchemeRegistry = registryBuilder.register(BEARER_AUTH_SCHEME_TYPE, bearerAuthSchemeFactory).build();
httpClientContext.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, BEARER_AUTH_SCHEME_TYPE);
Credentials creds = new TokenCredentials(config.getParameters().get(KEY_BEARER));
credentialsProvider.setCredentials(scope, creds);
httpClientContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);
if (config.getPreemptive()) {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate Bearer scheme object and add it to the local auth cache
AuthScheme bearerAuth = bearerAuthSchemeFactory.create(httpClientContext);
authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), bearerAuth);
// Add AuthCache to the execution context
httpClientContext.setAuthCache(authCache);
}
}
}
@Override
public String getWwwAuthenticateChallengePrefix() {
return BEARER_AUTH_SCHEME_TYPE;
}
}
|
9233c1710e0deefa248cf9ed24f0af76b6fb5617 | 2,342 | java | Java | src/test/java/org/folio/calendar/integration/calendar/periods/get/GetPeriodAbstractTest.java | Infinite-graph/mod-calendar | f4bdd128a3971b7b2c2bce0fda8f3b901393e8e4 | [
"Apache-2.0"
] | 1 | 2022-02-20T03:43:34.000Z | 2022-02-20T03:43:34.000Z | src/test/java/org/folio/calendar/integration/calendar/periods/get/GetPeriodAbstractTest.java | Infinite-graph/mod-calendar | f4bdd128a3971b7b2c2bce0fda8f3b901393e8e4 | [
"Apache-2.0"
] | 45 | 2021-10-29T19:12:03.000Z | 2022-03-29T20:28:56.000Z | src/test/java/org/folio/calendar/integration/calendar/periods/get/GetPeriodAbstractTest.java | Infinite-graph/mod-calendar | f4bdd128a3971b7b2c2bce0fda8f3b901393e8e4 | [
"Apache-2.0"
] | 3 | 2021-12-16T18:54:15.000Z | 2022-02-19T20:05:02.000Z | 30.815789 | 94 | 0.644321 | 996,694 | package org.folio.calendar.integration.calendar.periods.get;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.time.LocalDate;
import java.util.UUID;
import org.folio.calendar.integration.calendar.periods.AbstractExistingCalendarTest;
import org.junit.jupiter.api.Tag;
/**
* Setup an environment for testing GET /calendar/periods.
*
* <ul>
* <li>On service point 0:</li>
* <li>
* <ul>
* <li>Calendar 2021-01-01 to 2021-04-30 ({@code PERIOD_FULL_EXAMPLE_F}, ID A)</li>
* <li>Calendar 2021-05-01 to 2021-09-22 ({@code PERIOD_FULL_EXAMPLE_G}, ID B)</li>
* <li>Exception 2021-03-16 to 2021-04-30 ({@code PERIOD_FULL_EXCEPTIONAL_F}, ID F)</li>
* <li>Exception 2021-07-04 to 2021-09-22 ({@code PERIOD_FULL_EXCEPTIONAL_G}, ID 0)</li>
* </ul>
* </li>
* <li>On service point 1:</li>
* <li>
* <ul>
* <li>Calendar 2021-05-01 to 2021-09-22 ({@code PERIOD_FULL_EXAMPLE_D}, ID D)</li>
* </ul>
* </li>
* <li>On service point 5:</li>
* <li>
* <ul>
* <li>Exception 2021-01-01 to 2021-01-04 ({@code PERIOD_FULL_EXCEPTIONAL_C}, ID C)</li>
* </ul>
* </li>
* </ul>
*/
@Tag("idempotent")
public abstract class GetPeriodAbstractTest extends AbstractExistingCalendarTest {
public static final String GET_PERIOD_API_ROUTE = "/calendar/periods";
protected Response sendRequest(
UUID servicePointId,
LocalDate startDate,
LocalDate endDate,
Boolean includeClosedDays,
Boolean actualOpening,
Integer offset,
Integer limit
) {
RequestSpecification ra = ra();
if (servicePointId != null) {
ra = ra.queryParam("servicePointId", servicePointId);
}
if (startDate != null) {
ra = ra.queryParam("startDate", startDate.toString());
}
if (endDate != null) {
ra = ra.queryParam("endDate", endDate.toString());
}
if (includeClosedDays != null) {
ra = ra.queryParam("includeClosedDays", includeClosedDays);
}
if (actualOpening != null) {
ra = ra.queryParam("actualOpening", actualOpening);
}
if (offset != null) {
ra = ra.queryParam("offset", offset);
}
if (limit != null) {
ra = ra.queryParam("limit", limit);
}
return ra.get(getRequestUrl(GET_PERIOD_API_ROUTE));
}
}
|
9233c17f61a92edd1e5e171656118c4ed03f57f4 | 38,241 | java | Java | Agents/MoDSMechCalibAgent/src/main/java/uk/ac/cam/cares/jps/agent/file_management/marshallr/ModelKineticsSRM.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 21 | 2021-03-08T01:58:25.000Z | 2022-03-09T15:46:16.000Z | Agents/MoDSMechCalibAgent/src/main/java/uk/ac/cam/cares/jps/agent/file_management/marshallr/ModelKineticsSRM.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 63 | 2021-05-04T15:05:30.000Z | 2022-03-23T14:32:29.000Z | Agents/MoDSMechCalibAgent/src/main/java/uk/ac/cam/cares/jps/agent/file_management/marshallr/ModelKineticsSRM.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 15 | 2021-03-08T07:52:03.000Z | 2022-03-29T04:46:20.000Z | 36.73487 | 164 | 0.724824 | 996,695 | package uk.ac.cam.cares.jps.agent.file_management.marshallr;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.codehaus.plexus.util.FileUtils;
import org.json.JSONObject;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cmclinnovations.ontochem.model.converter.owl.OwlConverter;
import com.cmclinnovations.ontochem.model.exception.OntoException;
import com.jayway.jsonpath.JsonPath;
import uk.ac.cam.cares.jps.agent.configuration.MoDSMechCalibAgentProperty;
import uk.ac.cam.cares.jps.agent.file_management.mods.parameters.Parameter;
import uk.ac.cam.cares.jps.agent.json.parser.JSonRequestParser;
import uk.ac.cam.cares.jps.agent.mechanism.calibration.MoDSMechCalibAgentException;
import uk.ac.cam.cares.jps.agent.mechanism.calibration.Property;
import uk.ac.cam.cares.jps.kg.OntoChemExpKG;
import uk.ac.cam.cares.jps.kg.OntoKinKG;
import uk.ac.cam.cares.jps.kg.OntoChemExpKG.DataTable;
public class ModelKineticsSRM extends MoDSMarshaller implements IModel {
private static Logger logger = LoggerFactory.getLogger(ModelKineticsSRM.class);
private MoDSMechCalibAgentProperty modsMechCalibAgentProperty;
private int numOfReactions;
private String modelName = new String();
private LinkedHashMap<String, String> activeParameters = new LinkedHashMap<String, String>(); // linkedHashMap?
private List<String> passiveParameters = new ArrayList<>();
private List<String> outputResponses = new ArrayList<>();
private List<String> expFiles = new ArrayList<>();
private List<String> modelFiles = new ArrayList<>();
private List<String> caseNames = new ArrayList<>();
private String ignDelayMethod = "2";
private String ignDelaySpecies = "AR";
private String numOfSobolPoints = "1000";
private String numOfInitPoints = "1";
private String outputInterval = "1";
private String simEnd = "200";
private String nIters = "400";
private String rho = "0.2";
private String rhoFactor = "0.5";
private String epsilon = "0.001";
private String objectiveFunction = "SumOfSquares";
private String responseRatio = "1.0";
private String rangeOfMultipliers = "100.0";
private String ignDelayScaling = "logarithmic";
private String activeParamScaling = "logarithmic";
private boolean evalFirst = false;
public String getIgnDelayMethod() {
return ignDelayMethod;
}
public void setIgnDelayMethod(String ignDelayMethod) {
this.ignDelayMethod = ignDelayMethod;
}
public String getIgnDelaySpecies() {
return ignDelaySpecies;
}
public void setIgnDelaySpecies(String ignDelaySpecies) {
this.ignDelaySpecies = ignDelaySpecies;
}
public String getNumOfSobolPoints() {
return numOfSobolPoints;
}
public void setNumOfSobolPoints(String numOfSobolPoints) {
this.numOfSobolPoints = numOfSobolPoints;
}
public String getNumOfInitPoints() {
return numOfInitPoints;
}
public void setNumOfInitPoints(String numOfInitPoints) {
this.numOfInitPoints = numOfInitPoints;
}
public String getOutputInterval() {
return outputInterval;
}
public void setOutputInterval(String outputInterval) {
this.outputInterval = outputInterval;
}
public String getSimEnd() {
return simEnd;
}
public void setSimEnd(String simEnd) {
this.simEnd = simEnd;
}
public String getnIters() {
return nIters;
}
public void setnIters(String nIters) {
this.nIters = nIters;
}
public String getRho() {
return rho;
}
public void setRho(String rho) {
this.rho = rho;
}
public String getRhoFactor() {
return rhoFactor;
}
public void setRhoFactor(String rhoFactor) {
this.rhoFactor = rhoFactor;
}
public String getEpsilon() {
return epsilon;
}
public void setEpsilon(String epsilon) {
this.epsilon = epsilon;
}
public String getObjectiveFunction() {
return objectiveFunction;
}
public void setObjectiveFunction(String objectiveFunction) {
this.objectiveFunction = objectiveFunction;
}
public String getResponseRatio() {
return responseRatio;
}
public void setResponseRatio(String responseRatio) {
this.responseRatio = responseRatio;
}
public String getRangeOfMultipliers() {
return rangeOfMultipliers;
}
public void setRangeOfMultipliers(String rangeOfMultipliers) {
this.rangeOfMultipliers = rangeOfMultipliers;
}
public String getIgnDelayScaling() {
return ignDelayScaling;
}
public void setIgnDelayScaling(String ignDelayScaling) {
this.ignDelayScaling = ignDelayScaling;
}
public String getActiveParamScaling() {
return activeParamScaling;
}
public void setActiveParamScaling(String activeParamScaling) {
this.activeParamScaling = activeParamScaling;
}
public boolean isEvalFirst() {
return evalFirst;
}
public void setEvalFirst(boolean evalFirst) {
this.evalFirst = evalFirst;
}
public ModelKineticsSRM(MoDSMechCalibAgentProperty modsMechCalibAgentProperty) {
super(modsMechCalibAgentProperty);
this.modsMechCalibAgentProperty = modsMechCalibAgentProperty;
}
/**
* Collect all information required by MoDS to execute the model kineticsSRM.
* The information required:
* 1. model name - the name of the executable;
* 2. active parameters - the optimisable parameters of the model;
* 3. passive parameters - the experiment settings;
* 4. output response - the experimental observations;
* 5. exp files - list of files that contains experiment data and model to be calibrated;
* 6. case names - list of individual experiment;
* Input to this function:
* 1. experimentIRI - get all experimental observations, i.e., passive parameters and output responses.
* Also, set up case name list
* 2. mechanismIRI - download mechanism file
* 3. reactionIRIList - get list of reactions to be optimised, i.e., active parameters
*
* @param experimentIRI
* @param mechanismIRI
* @param reactionIRIList
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public ExecutableModel formExecutableModel(List<String> experimentIRI, String mechanismIRI, List<String> reactionIRIList)
throws IOException, MoDSMechCalibAgentException {
// check if the target folder exist
checkFolderPath(folderTemporaryPath);
// create ontology kg instance for query
OntoKinKG ontoKinKG = new OntoKinKG(modsMechCalibAgentProperty);
// query active parameters
LinkedHashMap<String, String> activeParameters = ontoKinKG.queryReactionsToOptimise(mechanismIRI, reactionIRIList);
// collect experiment information
List<List<String>> headers = new ArrayList<List<String>>();
List<List<String>> dataCollection = new ArrayList<List<String>>();
for (String experiment : experimentIRI) {
OntoChemExpKG ocekg = new OntoChemExpKG(modsMechCalibAgentProperty);
DataTable dataTable = ocekg.formatExperimentDataTable(experiment);
headers.add(dataTable.getTableHeader());
dataCollection.addAll(dataTable.getTableData());
}
for (int i = 1; i < headers.size(); i++) {
if (!headers.get(i).equals(headers.get(i-1))) {
logger.error("The heasers of all experimental data tables should be consistent.");
}
}
// if (!headers.get(0).equals(headers.get(1)) || !headers.get(1).equals(headers.get(2))) {
// logger.error("The heasers of all experimental data tables should be consistent.");
// }
// form exp data csv file
List<String[]> dataLines;
dataLines = new ArrayList<>();
dataLines.add(headers.get(0).toArray(new String[0]));
List<String> caseList = new ArrayList<>();
int i = 0;
for (List<String> dataSingleLine : dataCollection) {
dataLines.add(dataSingleLine.toArray(new String[0]));
// generate the list of cases
caseList.add(Property.MODEL_KINETICS.getPropertyName().concat("_case_"+i));
i += 1;
}
File expDataCSV = new File(folderTemporaryPath.concat(FRONTSLASH).concat(Property.MODEL_KINETICS.getPropertyName().concat(UNDERSCORE+FILE_MODEL_EXPDATA_SUFFIX)));
try (PrintWriter pw = new PrintWriter(expDataCSV)) {
dataLines.stream()
.map(this::convertToCSV)
.forEach(pw::println);
}
// obtain passive parameters and output responses from header of exp data csv file
List<String> passiveParameters = new ArrayList<>();
List<String> outputResponses = new ArrayList<>();
for (String param : headers.get(0)) {
if (param.contains("Igni") && param.contains("Delay")) {
outputResponses.add(param);
} else if (param.contains("Unit")) {
} else if (param.contains("Phi")) {
} else {
passiveParameters.add(param);
}
}
// download the mechanism owl file, and convert it to xml format
String mechHttpPath = mechanismIRI.substring(0, mechanismIRI.indexOf("#"));
String mechOWL = folderTemporaryPath.concat(FRONTSLASH).concat(mechHttpPath.substring(mechHttpPath.lastIndexOf("/")+1));
try {
ontoKinKG.downloadMechanism(mechHttpPath.substring(mechHttpPath.lastIndexOf("/")+1), mechHttpPath, mechOWL);
} catch (uk.ac.cam.cares.jps.kg.OntoException e1) {
e1.printStackTrace();
}
OwlConverter owlConverter = new OwlConverter();
ArrayList<String> mechanismOwlFiles = new ArrayList<>();
mechanismOwlFiles.add(mechOWL);
try {
owlConverter.convert(mechanismOwlFiles, folderTemporaryPath.replace("\\", "/"));
} catch (OWLOntologyCreationException | OntoException e) {
e.printStackTrace();
}
File mechXMLToCopy = new File(mechOWL.replace(".owl", ".xml"));
File mechXML = new File(folderTemporaryPath.concat(FRONTSLASH).concat(FILE_MECHANISM));
try {
FileUtils.copyFile(mechXMLToCopy, mechXML);
} catch (IOException e) {
e.printStackTrace();
}
// create model instance
ExecutableModel kineticsSRM = new ExecutableModel();
// set up model name
kineticsSRM.setModelName(Property.MODEL_KINETICS.getPropertyName());
// set up model active parameters
kineticsSRM.setActiveParameters(activeParameters);
// set up model passive parameters
kineticsSRM.setPassiveParameters(passiveParameters);
// set up model output response
kineticsSRM.setOutputResponses(outputResponses);
// set up model exp files
List<String> expFiles = new ArrayList<>();
expFiles.add(expDataCSV.getName());
expFiles.add(mechXML.getName());
kineticsSRM.setExpFiles(expFiles);
// set up model case names
kineticsSRM.setCaseNames(caseList);
// query number of reactions
List<List<String>> numOfReactionsResults = ontoKinKG.queryNumOfReactions(mechanismIRI);
numOfReactions = Integer.parseInt(numOfReactionsResults.get(1).get(0));
logger.info("Executable model kineticsSRM is prepared. ");
return kineticsSRM;
}
/**
* Form all files required by MoDS to execute the model kineticsSRM. This method
* replace the method in IModel.
*
* @param exeModel
* @param ignDelayOption
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public List<String> formFiles(ExecutableModel exeModel, String otherOptions) throws IOException, MoDSMechCalibAgentException {
// check if the target folder exist
checkFolderPath(folderInitialPath);
checkFolderPath(folderAllPath);
// get the basic information of executable kineticsSRM
modelName = exeModel.getModelName();
activeParameters = exeModel.getActiveParameters();
expFiles = exeModel.getExpFiles();
caseNames = exeModel.getCaseNames();
outputResponses = exeModel.getOutputResponses();
passiveParameters = exeModel.getPassiveParameters();
// set up the ignition delay option that will be used for generating InputParams.xml file
String method = JSonRequestParser.getIgnDelayMethod(otherOptions);
if (method != null && !method.isEmpty()) {
setIgnDelayMethod(method);
}
String species = JSonRequestParser.getIgnDelaySpecies(otherOptions);
if (species != null && !species.isEmpty()) {
setIgnDelaySpecies(species);
}
// set up the sobol points option that will be used for generating MoDS_inputs.xml file
String numSobol = JSonRequestParser.getNumOfSobolPoints(otherOptions);
if (numSobol != null && !numSobol.isEmpty()) {
setNumOfSobolPoints(numSobol);
}
// set up the output interval of sobol sampling that will be used for generating MoDS_inputs.xml file
String outputInterval = JSonRequestParser.getOutputInterval(otherOptions);
if (outputInterval != null && !outputInterval.isEmpty()) {
setOutputInterval(outputInterval);
}
// set up the initial points option that will be used for generating MoDS_inputs.xml file
String numInit = JSonRequestParser.getNumOfInitPoints(otherOptions);
if (numInit != null && !numInit.isEmpty()) {
setNumOfInitPoints(numInit);
}
// set up the simulation end time for generating InputParams.xml file
String simEnd = JSonRequestParser.getSimEnd(otherOptions);
if (simEnd != null && !simEnd.isEmpty()) {
setSimEnd(simEnd);
}
// set up Hooke-Jeeves algorithms parameters
String nIters = JSonRequestParser.getNIters(otherOptions);
if (nIters != null && !nIters.isEmpty()) {
setnIters(nIters);
}
String rho = JSonRequestParser.getRho(otherOptions);
if (rho != null && !rho.isEmpty()) {
setRho(rho);;
}
String rhoFactor = JSonRequestParser.getRhoFactor(otherOptions);
if (rhoFactor != null && !rhoFactor.isEmpty()) {
setRhoFactor(rhoFactor);;
}
String eps = JSonRequestParser.getEpsilon(otherOptions);
if (eps != null && !eps.isEmpty()) {
setEpsilon(eps);
}
// set up the objective function that will be used for generating MoDS_inputs.xml file
String objectiveFunction = JSonRequestParser.getObjectiveFunction(otherOptions);
if (objectiveFunction != null && !objectiveFunction.isEmpty()) {
setObjectiveFunction(objectiveFunction);
}
// set up the response ratio between two responses
String responseRatio = JSonRequestParser.getIgnDelayResponseRatio(otherOptions);
if (responseRatio != null && !responseRatio.isEmpty()) {
setResponseRatio(responseRatio);
}
// set up the range of multipliers
String rangeOfMultipliers = JSonRequestParser.getRangeOfMultipliers(otherOptions);
if (rangeOfMultipliers != null && !rangeOfMultipliers.isEmpty()) {
setRangeOfMultipliers(rangeOfMultipliers);
}
// set up the scaling for ignition delay response
String ignDelayScaling = JSonRequestParser.getIgnDelayScaling(otherOptions);
if (ignDelayScaling != null && !ignDelayScaling.isEmpty()) {
setIgnDelayScaling(ignDelayScaling);
}
// set up scaling for active parameters
String activeParamScaling = JSonRequestParser.getActiveParamScaling(otherOptions);
if (activeParamScaling != null && !activeParamScaling.isEmpty()) {
setActiveParamScaling(activeParamScaling);
}
boolean evalFirst = JSonRequestParser.getIfEvalFirst(otherOptions);
setEvalFirst(evalFirst);
// process the active parameters to be only the equation of reactions
List<String> processedActiveParam = new ArrayList<>();
for (String activeParamNo : activeParameters.keySet()) {
processedActiveParam.add(activeParameters.get(activeParamNo));
}
// create list to store all files used/produced when executing kineticsSRM model
// get the name of files in the initial folder
List<String> folderInitialFiles = createFolderInitial(processedActiveParam);
// get the name of files in the all folder
List<String> folderAllFiles = createFolderAll(processedActiveParam);
// name the output file of the model
String outputFile = Property.MODEL_KINETICS_OUTPUT.getPropertyName();
// append all names to modelFiles
modelFiles.addAll(folderInitialFiles);
modelFiles.addAll(folderAllFiles);
modelFiles.add(outputFile);
logger.info("Files required by "+modelName+" is prepared. ");
return modelFiles;
}
/**
* Create the files used during the 'initial read' when executing the kineticsSRM model.
*
* @param initial
* @param modelName
* @param processedActiveParam
* @param caseNames
* @param expFiles
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public List<String> createFolderInitial(List<String> processedActiveParam) throws IOException, MoDSMechCalibAgentException {
// set the active parameter csv file and passive parameter csv file path
File activeParameterFilePath = new File(folderInitialPath
.concat(FRONTSLASH+FILE_MODS_PREFIX+UNDERSCORE+modelName+UNDERSCORE+FILE_MODS_ACTIVE_SUFFIX));
File passiveParametersAndOutputsFilePath = new File(folderInitialPath
.concat(FRONTSLASH+FILE_MODS_PREFIX+UNDERSCORE+modelName+UNDERSCORE+FILE_MODS_PASSIVE_SUFFIX));
// get the filePath of experimental data
File expData = null;
for (String expFilePath : expFiles) {
if (expFilePath.contains(FILE_MODEL_EXPDATA_SUFFIX) && expFilePath.contains(modelName)) {
expData = new File(folderTemporaryPath.concat(FRONTSLASH+expFilePath));
}
}
// create files in the initial folder
List<String> initialFiles = new ArrayList<>();
String initialActiveFile = createActiveParametersFile(activeParameterFilePath, processedActiveParam, expData, caseNames);
String initialPassiveFile = createPassiveParametersAndOutputsFile(passiveParametersAndOutputsFilePath, expData, caseNames);
initialFiles.add(initialActiveFile);
initialFiles.add(initialPassiveFile);
logger.info("Folder /Initial required by "+modelName+" is prepared. ");
return initialFiles;
}
/**
* Create the files used during the 'working write' when executing the kineticsSRM model.
*
* @param initial
* @param modelName
* @param processedActiveParam
* @param caseNames
* @param expFiles
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public List<String> createFolderAll(List<String> processedActiveParam) throws IOException, MoDSMechCalibAgentException {
// set the mechanism file and inputParams.xml file path
File copyOfMechanismFilePath = new File(folderAllPath.concat(FRONTSLASH+FILE_MECHANISM));
File inputParamsFilePath = new File(folderAllPath.concat(FRONTSLASH+FILE_KINETICS_INPUTPARAMS));
// get the filePath of experimental data and mechanism
File expData = null;
File mechanism = null;
for (String expFilePath : expFiles) {
if (expFilePath.contains(FILE_MODEL_EXPDATA_SUFFIX) && expFilePath.contains(modelName)) {
expData = new File(folderTemporaryPath.concat(FRONTSLASH+expFilePath));
} else if (expFilePath.contains(FILE_MECHANISM)) {
mechanism = new File(folderTemporaryPath.concat(FRONTSLASH+expFilePath));
}
}
// create files in the initial folder
List<String> allFiles = new ArrayList<>();
allFiles.add(copyMechanismFile(copyOfMechanismFilePath, mechanism));
allFiles.add(createInputParamsFile(inputParamsFilePath, expData));
logger.info("Folder /All required by "+modelName+" is prepared. ");
return allFiles;
}
/**
* Set up all the components of executable in the MoDS input file.
*
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public void setUpMoDS() throws IOException, MoDSMechCalibAgentException {
// set up algorithms
String active_subtype = new String();
for (String i : activeParameters.keySet()) {
active_subtype = active_subtype.concat(" subtype_"+"rxn_"+i);
}
LinkedHashMap<String, LinkedHashMap<String, String>> algorithms = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> algoSampling = new LinkedHashMap<String, String>();
algoSampling.put("optimisable_param_subtypes", active_subtype.substring(1));
algoSampling.put("response_param_subtypes", "subtype_".concat(outputResponses.get(0)));
algoSampling.put("algorithm_type", "Sobol");
// algoSampling.put("model_name", "exe");
algoSampling.put("objective_function", getObjectiveFunction());
algoSampling.put("output_by_case", "false");
algoSampling.put("output_values", "true");
algoSampling.put("n_points", getNumOfSobolPoints());
algoSampling.put("seed", "1");
algoSampling.put("output_interval", getOutputInterval());
algoSampling.put("previous_algorithm", "Initial");
LinkedHashMap<String, String> algoCalibration = new LinkedHashMap<String, String>();
algoCalibration.put("optimisable_param_subtypes", active_subtype.substring(1));
algoCalibration.put("response_param_subtypes", "subtype_".concat(outputResponses.get(0)));
algoCalibration.put("algorithm_type", "Hooke_Jeeves");
// algoCalibration.put("model_name", "exe");
algoCalibration.put("objective_function", getObjectiveFunction());
algoCalibration.put("output_by_case", "false");
algoCalibration.put("output_values", "true");
algoCalibration.put("n_iters", getnIters());
algoCalibration.put("n_initial_points", getNumOfInitPoints());
algoCalibration.put("constrained", "true");
algoCalibration.put("rho", getRho());
algoCalibration.put("rho_factor", getRhoFactor());
algoCalibration.put("epsilon", getEpsilon());
algoCalibration.put("previous_algorithm", "SamplingAlg");
if (isEvalFirst()) {
LinkedHashMap<String, String> algoEvaluation = new LinkedHashMap<String, String>();
algoEvaluation.put("algorithm_type", "Run");
algoEvaluation.put("n_run", "0");
algoEvaluation.put("response_param_subtypes", "subtype_".concat(outputResponses.get(0)));
algorithms.put("Evaluation", algoEvaluation);
}
algorithms.put("SamplingAlg", algoSampling);
algorithms.put("CalibrationAlg", algoCalibration);
collectAlgorithms(algorithms);
// set up model
LinkedHashMap<String, LinkedHashMap<String, String>> models = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> model = new LinkedHashMap<String, String>();
model.put("executable_name", Property.MODEL_KINETICS_EXE.getPropertyName());
model.put("working_directory", "");
model.put("args", modsMechCalibAgentProperty.getKineticsFolderPath().concat(SPACE).concat(modsMechCalibAgentProperty.getKineticsExecutableName()));
model.put("max_tries", "2");
models.put(modelName, model);
collectModels(models);
// set up cases
LinkedHashMap<String, List<String>> cases = new LinkedHashMap<String, List<String>>();
List<String> caseModel = new ArrayList<>();
caseModel.add(modelName);
for (String caseName : caseNames) {
cases.put(caseName, caseModel);
}
collectCases(cases);
// set up files
LinkedHashMap<String, LinkedHashMap<String, String>> files = new LinkedHashMap<String, LinkedHashMap<String, String>>();
for (String modelFile : modelFiles) {
LinkedHashMap<String, String> file = new LinkedHashMap<String, String>();
if (modelFile.endsWith(".xml")) {
file.put("file_type", "XML");
if (modelFile.contains(FILE_KINETICS_INPUTPARAMS)) {
file.put("XML_namespace", "http://como.cheng.cam.ac.uk/srm");
}
} else if (modelFile.endsWith(".csv")) {
file.put("file_type", "DSV");
file.put("delimiter", ",");
}
files.put(modelFile, file);
}
collectFiles(files);
// set up parameters
List<Parameter> parameters = new ArrayList<>();
// constructing row, lbFactor, and ubFactor
String row = "";
String lbFactor = "";
String ubFactor = "";
double sqrtRatio = Math.sqrt(Double.valueOf(getResponseRatio()));
double errFrac = 0.20;
double lb_fac = (1-errFrac)/sqrtRatio;
double ub_fac = (1+errFrac)/sqrtRatio;
for (int j = 0; j < caseNames.size(); j++) {
row = row.concat(";"+j);
lbFactor = lbFactor.concat(";"+lb_fac);
ubFactor = ubFactor.concat(";"+ub_fac);
}
row = row.substring(1);
lbFactor = lbFactor.substring(1);
ubFactor = ubFactor.substring(1);
// active parameters
for (String i : activeParameters.keySet()) {
Parameter param = new Parameter();
param.setType("active_input");
param.setName("rxn_"+i);
param.setSubtype("subtype_"+"rxn_"+i);
param.setPreserveWhiteSpace("true");
param.setScaling(getActiveParamScaling());
param.setCaseNamesList(caseNames);
param.setModelList(caseModel);
LinkedHashMap<String, LinkedHashMap<String, String>> fileHash = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> initialRead = new LinkedHashMap<String, String>();
initialRead.put("column", activeParameters.get(i));
initialRead.put("row", "0");
initialRead.put("read_function", "Get_DSV_double");
initialRead.put("lb_abs", String.valueOf(1/Double.valueOf(getRangeOfMultipliers())));
initialRead.put("ub_abs", String.valueOf(Double.valueOf(getRangeOfMultipliers())));
LinkedHashMap<String, String> workingWrite = new LinkedHashMap<String, String>();
workingWrite.put("path", "//srm_inputs/property_group[@ref='Chemistry']/property[@ref='ReactionRate_A_Modifiers']/value[@index='"+i+"']");
workingWrite.put("write_function", "Set_XML_double");
fileHash.put("initialRead "+FILE_MODS_PREFIX+UNDERSCORE+modelName+UNDERSCORE+FILE_MODS_ACTIVE_SUFFIX, initialRead);
fileHash.put("workingWrite "+FILE_KINETICS_INPUTPARAMS, workingWrite);
param.setFileHash(fileHash);
parameters.add(param);
}
// passive parameters
for (String i : passiveParameters) {
Parameter param = new Parameter();
param.setType("passive_input");
param.setName(i);
param.setSubtype("subtype_"+i);
param.setCaseDetailSep(";");
param.setPreserveWhiteSpace("true");
param.setCaseNamesList(caseNames);
param.setModelList(caseModel);
String path = new String();
if (i.contains("Temp")) {
path = "//srm_inputs/property_group[@ref='Reactor']/property[@ref='IniTemp']/value";
} else if (i.contains("Pres")) {
path = "//srm_inputs/property_group[@ref='Reactor']/property[@ref='IniPres']/value";
} else {
path = "//srm_inputs/mixtures[@type='composition']/composition[@name='"+NAME_OXIDISER+"']/value[@species='"+i+"']";
}
LinkedHashMap<String, LinkedHashMap<String, String>> fileHash = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> initialRead = new LinkedHashMap<String, String>();
initialRead.put("column", i);
initialRead.put("row", row);
initialRead.put("read_function", "Get_DSV_double");
LinkedHashMap<String, String> workingWrite = new LinkedHashMap<String, String>();
workingWrite.put("path", path);
workingWrite.put("write_function", "Set_XML_double");
fileHash.put("initialRead "+FILE_MODS_PREFIX+UNDERSCORE+modelName+UNDERSCORE+FILE_MODS_PASSIVE_SUFFIX, initialRead);
fileHash.put("workingWrite "+FILE_KINETICS_INPUTPARAMS, workingWrite);
param.setFileHash(fileHash);
parameters.add(param);
}
// output response
for (String i : outputResponses) {
Parameter param = new Parameter();
param.setType("active_output");
param.setSubtype("subtype_"+i);
param.setName(i);
param.setCaseDetailSep(";");
param.setNParamsPerCase("1");
param.setPreserveWhiteSpace("true");
param.setScaling(getIgnDelayScaling());
param.setCaseNamesList(caseNames);
param.setModelList(caseModel);
String column = new String();
if (i.toLowerCase().contains("igni") && i.toLowerCase().contains("delay")) {
column = "Ignition time [ms]";
} else if (i.toLowerCase().contains("flame") && i.toLowerCase().contains("speed")) {
column = "Laminar flame speed [cm/s]";
} // TODO further parameterise this
LinkedHashMap<String, LinkedHashMap<String, String>> fileHash = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> initialRead = new LinkedHashMap<String, String>();
initialRead.put("column", i);
initialRead.put("row", row);
initialRead.put("read_function", "Get_DSV_double");
initialRead.put("lb_factor", lbFactor);
initialRead.put("ub_factor", ubFactor);
LinkedHashMap<String, String> workingRead = new LinkedHashMap<String, String>();
workingRead.put("column", column);
workingRead.put("row", "0");
workingRead.put("read_function", "Get_DSV_double");
fileHash.put("initialRead "+FILE_MODS_PREFIX+UNDERSCORE+modelName+UNDERSCORE+FILE_MODS_PASSIVE_SUFFIX, initialRead);
fileHash.put("workingRead "+Property.MODEL_KINETICS_OUTPUT.getPropertyName(), workingRead);
param.setFileHash(fileHash);
parameters.add(param);
}
collectParameters(parameters);
logger.info("Information related to "+modelName+" in MoDS_inputs XML file is collected. ");
}
/**
* Set up the simulation script required for the model to execute.
*
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
@Override
public void placeScript() throws IOException, MoDSMechCalibAgentException {
File srcScript = new File(getClass().getClassLoader().getResource(Property.MODEL_KINETICS_SCRIPT.getPropertyName()).getFile());
File jobScript = new File(jobFolderPath.concat(FRONTSLASH+FILE_KINETICSSRM_SCRIPT));
// create the BufferedReader and BufferedWriter to read and write files
BufferedReader br = null;
BufferedWriter bw = null;
// copy the runKineticsSRM.sh script
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(srcScript)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jobScript)));
String line = new String();
while ((line = br.readLine()) != null) {
bw.write(line.concat("\n"));
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Create case file that contains the active parameters used by executable kineticsSRM.
*
* @param activeParameterFilePath
* @param processedActiveParam
* @param expData
* @param caseNames
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
private String createActiveParametersFile(File activeParameterFilePath, List<String> processedActiveParam, File expData,
List<String> caseNames) throws IOException, MoDSMechCalibAgentException {
// construct the title of columns
List<String> columnTitle = new ArrayList<>();
columnTitle.add("Case name");
columnTitle.addAll(processedActiveParam);
// construct the reactionMultipliers, serving the initial read of active parameters
List<String> reactionMultipliers = new ArrayList<>();
for (int i = 0; i < processedActiveParam.size(); i++) {
reactionMultipliers.add("1");
}
// create the BufferedReader and BufferedWriter to read and write files
BufferedReader br = null;
BufferedWriter bw = null;
// create the active parameters csv file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(expData)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(activeParameterFilePath), "UTF-8"));
// add the column title
br.readLine();
bw.write(convertToCSV(columnTitle.toArray(new String[0])).concat("\n"));
// add the cases
int i = 0;
while ((br.readLine()) != null) {
bw.write(caseNames.get(i).concat(",").concat(convertToCSV(reactionMultipliers.toArray(new String[0]))).concat("\n"));
i += 1;
}
// additional check if all cases are added
if (i != caseNames.size()) {
System.out.println("The number of cases does NOT match the number of experimental observations.");
}
// close files
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return activeParameterFilePath.getName();
}
/**
* Create case file that contains the passive parameters used by executable kineticsSRM,
* also the output response of executable kineticsSRM.
*
* @param passiveParametersAndOutputsFilePath
* @param expData
* @param caseNames
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
private String createPassiveParametersAndOutputsFile(File passiveParametersAndOutputsFilePath, File expData,
List<String> caseNames) throws IOException, MoDSMechCalibAgentException {
// create the BufferedReader and BufferedWriter to read and write files
// add the caseNames to the start of each line of experimental data file
BufferedReader br = null;
BufferedWriter bw = null;
// create the passive parameters and output response csv file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(expData)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(passiveParametersAndOutputsFilePath), "UTF-8"));
// add the column title
String line = br.readLine();
bw.write("Case name".concat(",").concat(line).concat("\n"));
// add the data part
int i = 0;
while ((line = br.readLine()) != null) {
bw.write(caseNames.get(i).concat(",").concat(line).concat("\n"));
i += 1;
}
// additional check if all cases are added
if (i != caseNames.size()) {
logger.error("The number of cases does NOT match the number of experimental observations.");
}
// close files
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return passiveParametersAndOutputsFilePath.getName();
}
/**
* Create the mechanism file used by the executable kineticsSRM.
*
* @param mechanism
* @param copyOfMechanism
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
private String copyMechanismFile(File copyOfMechanismFilePath, File mechanism) throws IOException, MoDSMechCalibAgentException {
// create the BufferedReader and BufferedWriter to read and write files
BufferedReader br = null;
BufferedWriter bw = null;
// copy mechanism file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(mechanism)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(copyOfMechanismFilePath), "UTF-8"));
String line = new String();
while ((line = br.readLine()) != null) {
bw.write(line+"\n");
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return copyOfMechanismFilePath.getName();
}
/**
* Create the InputParams.xml file required by the executable kineticsSRM.
*
* @param inputParamsFilePath
* @param expData
* @param mechName
* @return
* @throws IOException
* @throws MoDSMechCalibAgentException
*/
private String createInputParamsFile(File inputParamsFilePath, File expData) throws IOException, MoDSMechCalibAgentException {
// read the first case of experiment
String[] headerLine = null;
String[] firstData = null;
if (expData.isFile()) {
BufferedReader expReader = new BufferedReader(new FileReader(expData));
headerLine = expReader.readLine().split(",");
firstData = expReader.readLine().split(",");
expReader.close();
}
// prepare the variables to be passed to InputParams.xml file
String iniTemp = null;
String iniTempUnit = null;
String iniPres = null;
String iniPresUnit = null;
ArrayList<String> species = new ArrayList<String>();
// ignition delay, uncomment corresponding method below
String ignDelayDeltaT = "400";
String ignDelayShowAll = "1";
String ignDelayModel = getIgnDelayMethod();
String ignDelaySpeciesIndex = getIgnDelaySpecies();
// -Method 0. Searching for the maximum rate of temperature increase.
// String ignDelayModel = "0";
// String ignDelaySpeciesIndex = "AR";
// -Method 1. Searching for the maximum rate of pressure increase.
// String ignDelayModel = "1";
// String ignDelaySpeciesIndex = "AR";
// -Method 2. Searching for the point at which temperature increase exceeds 400 K.
// String ignDelayModel = "2";
// String ignDelaySpeciesIndex = "AR";
// -Method 3. Searching for the maximum mole fraction of species "x".
// String ignDelayModel = "3";
// String ignDelaySpeciesIndex = "OH";
// -Method 4. Searching for the maximum rate of increase of the mole fraction of species "x".
// String ignDelayModel = "4";
// String ignDelaySpeciesIndex = "CO";
String oxidiser = NAME_OXIDISER; // this name is to be further parameterised, also to be connected to MoDS_Inputs.xml
for (int i = 0; i < headerLine.length; i++) {
if (headerLine[i].contains("Temp")) {
if (headerLine[i].contains("Unit")) {
iniTempUnit = firstData[i];
} else {
iniTemp = firstData[i];
}
} else if (headerLine[i].contains("Pres")) {
if (headerLine[i].contains("Unit")) {
iniPresUnit = firstData[i];
} else {
iniPres = firstData[i];
}
} else if (headerLine[i].contains("DMM3")
|| headerLine[i].contains("O2")
|| headerLine[i].contains("N2")) {
species.add(headerLine[i]);
species.add(firstData[i]);
}
}
String jsonString = new JSONObject()
.put("kinetics",
new JSONObject()
.put("filePath", inputParamsFilePath.getAbsolutePath())
.put("reactor", new JSONObject()
.put("iniTemp", new JSONObject()
.put("value", iniTemp)
.put("unit", iniTempUnit))
.put("iniPres", new JSONObject()
.put("value", iniPres)
.put("unit", iniPresUnit)))
.put("chemistry", new JSONObject()
.put("mechFile", FILE_MECHANISM)
.put("numOfReactions", numOfReactions))
.put("numerical", new JSONObject()
.put("simEnd", getSimEnd()))
.put("oxidiser", oxidiser)
.put("ignDelayPostProcessor", new JSONObject()
.put("ignDelayModel", ignDelayModel)
.put("ignDelayDeltaT", ignDelayDeltaT)
.put("ignDelaySpeciesIndex", ignDelaySpeciesIndex)
.put("ignDelayShowAll", ignDelayShowAll))
.put("mixtures", new JSONObject()
.put("composition", species))).toString();
InputParamsBuilder inputParamsBuilder = new InputParamsBuilder();
File inputParams = inputParamsBuilder.formInputParamsXML(jsonString);
return inputParams.getName();
}
}
|
9233c1cf6116fef5d3279ca66ead22824366ca30 | 5,379 | java | Java | src/main/java/net/smoofyuniverse/mirage/api/modifier/ChunkModifier.java | Yeregorix/Mirage | 403690d1d583e96cf29d52be3ccb5502443be6e3 | [
"MIT"
] | 14 | 2018-06-05T08:31:41.000Z | 2022-02-08T07:54:18.000Z | src/main/java/net/smoofyuniverse/mirage/api/modifier/ChunkModifier.java | Yeregorix/Mirage | 403690d1d583e96cf29d52be3ccb5502443be6e3 | [
"MIT"
] | 43 | 2018-07-02T23:55:55.000Z | 2021-01-31T15:25:44.000Z | src/main/java/net/smoofyuniverse/mirage/api/modifier/ChunkModifier.java | Yeregorix/Mirage | 403690d1d583e96cf29d52be3ccb5502443be6e3 | [
"MIT"
] | 1 | 2020-06-20T21:49:48.000Z | 2020-06-20T21:49:48.000Z | 36.591837 | 179 | 0.753114 | 996,696 | /*
* Copyright (c) 2018-2021 Hugo Dupanloup (Yeregorix)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.smoofyuniverse.mirage.api.modifier;
import co.aikar.timings.Timing;
import co.aikar.timings.Timings;
import com.flowpowered.math.vector.Vector3i;
import net.smoofyuniverse.mirage.api.cache.Signature;
import net.smoofyuniverse.mirage.api.volume.BlockView;
import net.smoofyuniverse.mirage.api.volume.ChunkView;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.util.annotation.CatalogedBy;
import org.spongepowered.api.world.DimensionType;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.Random;
/**
* This object is used to modify chunk per chunk the view of the world sent to players.
*/
@CatalogedBy(ChunkModifiers.class)
public abstract class ChunkModifier implements CatalogType {
private final Timing timing;
private final String id, name;
/**
* @param plugin The plugin owning this modifier
* @param name The name of this modifier
*/
public ChunkModifier(Object plugin, String name) {
if (name == null || name.isEmpty())
throw new IllegalArgumentException("Name");
PluginContainer container = Sponge.getGame().getPluginManager().fromInstance(plugin).orElseThrow(() -> new IllegalArgumentException("Provided object is not a plugin instance"));
this.timing = Timings.of(container, "Modifier: " + name);
this.id = container.getId() + ":" + name.toLowerCase();
this.name = name;
}
@Override
public final String getId() {
return this.id;
}
@Override
public final String getName() {
return this.name;
}
/**
* @return A Timing that will be used to monitor performances of this modifier
*/
public final Timing getTiming() {
return this.timing;
}
/**
* @return false if this modifier is lightweight and cache is useless, true otherwise
*/
public boolean requireCache() {
return true;
}
/**
* @param world The world
* @return true if this modifier is compatible with this world
*/
public boolean isCompatible(WorldProperties world) {
return true;
}
/**
* Generates a configuration from the given node.
*
* @param node The configuration node (mutable)
* @param dimension The dimension defined in the main configuration, might differ from the actual world dimension
* @param preset An optional preset
* @return The configuration
*/
public abstract Object loadConfiguration(ConfigurationNode node, DimensionType dimension, String preset) throws ObjectMappingException;
/**
* Generates a cache signature to make a summary of all elements that may impact the aspect of the modified chunk.
* A different signature from the cached one will cause the cached object to be invalidated.
*
* @param builder The signature builder
* @param config The configuration
*/
public abstract void appendSignature(Signature.Builder builder, Object config);
/**
* Checks whether this modifier requires that the neighbor chunks are loaded.
*
* @return true if this modifier requires that the neighbor chunks are loaded.
*/
public boolean requireNeighborsLoaded() {
return true;
}
/**
* Modifies the ChunkView that will be send to players.
* This method might check and modify thousands blocks and thus must optimized to be as fast as possible.
*
* @param view The ChunkView to modify
* @param r The Random object that should be used by the modifier
* @param config The configuration
*/
public void modify(ChunkView view, Random r, Object config) {
modify(view, view.getBlockMin(), view.getBlockMax(), r, config);
}
/**
* Modifies the BlockView that will be send to players.
* This method might check and modify thousands blocks and thus must optimized to be as fast as possible.
*
* @param view The BlockView to modify
* @param min The lowest block location to modify
* @param max The highest block location to modify
* @param r The Random object that should be used by the modifier
* @param config The configuration
*/
public abstract void modify(BlockView view, Vector3i min, Vector3i max, Random r, Object config);
}
|
9233c2e675d528ff7fb8afba52cb9dae9859a652 | 1,577 | java | Java | backend/de.metas.adempiere.adempiere/base/src/test/java/org/adempiere/ad/table/SqlWithParamsTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/base/src/test/java/org/adempiere/ad/table/SqlWithParamsTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/base/src/test/java/org/adempiere/ad/table/SqlWithParamsTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | 32.183673 | 106 | 0.736208 | 996,697 | package org.adempiere.ad.table;
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.Timestamp;
import org.adempiere.ad.table.RecordChangeLogEntryLoader.SqlWithParams;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableList;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2019 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
class SqlWithParamsTest
{
@Test
void test()
{
final SqlWithParams result = SqlWithParams
.createEmpty()
.add(new SqlWithParams("string1", ImmutableList.of(1, 2, "3")))
.add(new SqlWithParams("string2", ImmutableList.of(4, 5, Timestamp.valueOf("2019-08-22 11:01:23"))))
.withFinalOrderByClause("ORDER BY whatever");
assertThat(result.getSql()).isEqualTo("string1\n UNION\nstring2\nORDER BY whatever");
assertThat(result.getSqlParams()).containsExactly(1,2,"3",4,5,Timestamp.valueOf("2019-08-22 11:01:23"));
}
}
|
9233c308513bbfc15c708a8593ddb8baa47bf12f | 339 | java | Java | src/main/java/dev/tdz/services/UserRoleService.java | dcheun/2102GCP-P2-backend | 0fc08f407e6714e87195a610f073c5bcae57ede5 | [
"MIT"
] | null | null | null | src/main/java/dev/tdz/services/UserRoleService.java | dcheun/2102GCP-P2-backend | 0fc08f407e6714e87195a610f073c5bcae57ede5 | [
"MIT"
] | 2 | 2021-03-19T16:49:28.000Z | 2021-03-24T21:09:16.000Z | src/main/java/dev/tdz/services/UserRoleService.java | dcheun/2102GCP-P2-backend | 0fc08f407e6714e87195a610f073c5bcae57ede5 | [
"MIT"
] | 1 | 2021-03-31T21:11:01.000Z | 2021-03-31T21:11:01.000Z | 16.95 | 47 | 0.755162 | 996,698 | package dev.tdz.services;
import dev.tdz.entities.UserRole;
import java.util.Set;
public interface UserRoleService {
UserRole createUserRole(UserRole userRole);
UserRole getUserRoleById(int id);
Set<UserRole> getAllUserRoles();
UserRole updateUserRole(UserRole userRole);
boolean deleteUserRoleById(int id);
}
|
9233c35ea2f8d62ab878ab9cb1944ba0516e0f3e | 2,356 | java | Java | src/main/java/me/linusdev/lapi/api/objects/message/embed/EmbedType.java | lni-dev/lapi | 1aa178491f12db47f6c266b3990e0031273775ae | [
"Apache-2.0"
] | null | null | null | src/main/java/me/linusdev/lapi/api/objects/message/embed/EmbedType.java | lni-dev/lapi | 1aa178491f12db47f6c266b3990e0031273775ae | [
"Apache-2.0"
] | null | null | null | src/main/java/me/linusdev/lapi/api/objects/message/embed/EmbedType.java | lni-dev/lapi | 1aa178491f12db47f6c266b3990e0031273775ae | [
"Apache-2.0"
] | null | null | null | 24.28866 | 234 | 0.632428 | 996,699 | /*
* Copyright 2022 Linus Andera
*
* 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 me.linusdev.lapi.api.objects.message.embed;
import me.linusdev.data.SimpleDatable;
import org.jetbrains.annotations.NotNull;
/**
* Embed types are "loosely defined" and, for the most part, are not used by our clients for rendering. Embed attributes power what is rendered. Embed types should be considered deprecated and might be removed in a future API version.
*
* @see <a href="https://discord.com/developers/docs/resources/channel#embed-object-embed-types" target="_top">Embed Types</a>
*/
public enum EmbedType implements SimpleDatable {
/**
* generic embed rendered from embed attributes
*/
RICH("rich"),
/**
* image embed
*/
IMAGE("image"),
/**
* video embed
*/
VIDEO("video"),
/**
* animated gif image embed rendered as a video embed
*/
GIFV("gifv"),
/**
* article embed
*/
ARTICLE("article"),
/**
* link embed
*/
LINK("link"),
;
private final @NotNull String type;
EmbedType(String type){
this.type = type;
}
/**
*
* @param type String of Type
* @return {@link EmbedType} corresponding to given type or {@link #RICH} if no {@link EmbedType} matched
*/
public static EmbedType fromTypeString(String type){
for(EmbedType embedType : values()){
if(embedType.type.equalsIgnoreCase(type)){
return embedType;
}
}
return RICH;
}
@Override
public String toString() {
return type;
}
/**
* String used in Json from Discord
*/
public String asTypeString(){
return type;
}
@Override
public Object simplify() {
return asTypeString();
}
}
|
9233c40c741da0c1ce2355b33a92425b1b29a5a7 | 2,653 | java | Java | src/main/java/edu/ie3/datamodel/models/timeseries/individual/IndividualTimeSeries.java | ie3-institute/PSDM_jenkinsDev | 1e9e8b1c2f2808a81400a21b29350b2def7777c1 | [
"BSD-3-Clause"
] | 16 | 2020-01-30T10:41:32.000Z | 2021-12-20T21:23:55.000Z | src/main/java/edu/ie3/datamodel/models/timeseries/individual/IndividualTimeSeries.java | ie3-institute/PowerSystemDataModel | 0ea1ec578704fe2bd44d5b4bb4feeacc2d08f046 | [
"BSD-3-Clause"
] | 544 | 2020-01-27T15:03:27.000Z | 2022-03-31T18:30:26.000Z | src/main/java/edu/ie3/datamodel/models/timeseries/individual/IndividualTimeSeries.java | ie3-institute/PSDM_jenkinsDev | 1e9e8b1c2f2808a81400a21b29350b2def7777c1 | [
"BSD-3-Clause"
] | 11 | 2020-03-30T11:45:42.000Z | 2021-12-20T21:24:03.000Z | 32.753086 | 100 | 0.715793 | 996,700 | /*
* © 2021. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.models.timeseries.individual;
import edu.ie3.datamodel.models.timeseries.TimeSeries;
import edu.ie3.datamodel.models.value.Value;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
/** Describes a TimeSeries with individual values per time step */
public class IndividualTimeSeries<V extends Value> extends TimeSeries<TimeBasedValue<V>, V> {
/** Maps a time to its respective value to retrieve faster */
private final Map<ZonedDateTime, TimeBasedValue<V>> timeToValue;
public IndividualTimeSeries(UUID uuid, Set<TimeBasedValue<V>> values) {
super(uuid, values);
timeToValue =
values.stream()
.collect(Collectors.toMap(TimeBasedValue::getTime, timeBasedValue -> timeBasedValue));
}
/**
* Returns the sorted set of all entries known to this time series
*
* @return An unmodifiable sorted set of all known time based values of this time series
*/
@Override
public SortedSet<TimeBasedValue<V>> getEntries() {
TreeSet<TimeBasedValue<V>> sortedEntries = new TreeSet<>(timeToValue.values());
return Collections.unmodifiableSortedSet(sortedEntries);
}
@Override
public Optional<TimeBasedValue<V>> getTimeBasedValue(ZonedDateTime time) {
return Optional.ofNullable(timeToValue.get(time));
}
@Override
public Optional<V> getValue(ZonedDateTime time) {
return getTimeBasedValue(time).map(TimeBasedValue::getValue);
}
@Override
protected Optional<ZonedDateTime> getPreviousDateTime(ZonedDateTime time) {
return timeToValue.keySet().stream()
.filter(valueTime -> valueTime.compareTo(time) <= 0)
.max(Comparator.naturalOrder());
}
@Override
protected Optional<ZonedDateTime> getNextDateTime(ZonedDateTime time) {
return timeToValue.keySet().stream()
.filter(valueTime -> valueTime.compareTo(time) >= 0)
.min(Comparator.naturalOrder());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
IndividualTimeSeries<?> that = (IndividualTimeSeries<?>) o;
return timeToValue.equals(that.timeToValue);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), timeToValue);
}
@Override
public String toString() {
return "IndividualTimeSeries{" + "uuid=" + getUuid() + ", #entries=" + timeToValue.size() + '}';
}
}
|
9233c60f7884100f2d1448876f663bed4b8202c2 | 338 | java | Java | src/main/java/org/sistemafinanciero/exception/IllegalResultException.java | Softgreen/SISTCOOP_REST | ac5679f95fa7b12d4ec7338f09808270e702928e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sistemafinanciero/exception/IllegalResultException.java | Softgreen/SISTCOOP_REST | ac5679f95fa7b12d4ec7338f09808270e702928e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sistemafinanciero/exception/IllegalResultException.java | Softgreen/SISTCOOP_REST | ac5679f95fa7b12d4ec7338f09808270e702928e | [
"Apache-2.0"
] | null | null | null | 24.142857 | 65 | 0.739645 | 996,701 | package org.sistemafinanciero.exception;
public class IllegalResultException extends Exception {
private static final long serialVersionUID = 1L;
public IllegalResultException(String message, Throwable cause) {
super(message, cause);
}
public IllegalResultException(String message) {
super(message);
}
}
|
9233c6ac3929e1022cb51b55b722c94d44316a11 | 1,600 | java | Java | src/SChemP/Wavefunction.java | ScottKolo/SChemP | 5e0d0dc601f3c9805671d78a975add68010113df | [
"Apache-2.0"
] | 1 | 2020-12-28T22:48:49.000Z | 2020-12-28T22:48:49.000Z | src/SChemP/Wavefunction.java | ScottKolo/SChemP | 5e0d0dc601f3c9805671d78a975add68010113df | [
"Apache-2.0"
] | null | null | null | src/SChemP/Wavefunction.java | ScottKolo/SChemP | 5e0d0dc601f3c9805671d78a975add68010113df | [
"Apache-2.0"
] | null | null | null | 18.390805 | 86 | 0.629375 | 996,702 | package SChemP;
public class Wavefunction
{
int n;
int l;
int m;
double theta;
double phi;
public Wavefunction(Electron e)
{
n = e.getN();
l = e.getL();
m = e.getM();
theta = 0;
phi = 0;
}
public Wavefunction(int n, int l, int m)
{
this.n = n;
this.l = l;
this.m = m;
theta = 0;
phi = 0;
}
public Wavefunction(Electron e, double theta, double phi)
{
n = e.getN();
l = e.getL();
m = e.getM();
this.theta = theta;
this.phi = phi;
}
public Wavefunction(int n, int l, int m, double theta, double phi)
{
this.n = n;
this.l = l;
this.m = m;
this.theta = theta;
this.phi = phi;
}
public int getN()
{
return n;
}
public int getL()
{
return l;
}
public int getM()
{
return m;
}
public double calculateWavefunction(double r)
{
return QuantumMechanics.calculateHydrogenWavefunction(n, l, m, r, theta, phi);
}
public double calculateWavefunction(double r, double theta, double phi)
{
return QuantumMechanics.calculateHydrogenWavefunction(n, l, m, r, theta, phi);
}
public double calculateWavefunction(double constant, double r)
{
return QuantumMechanics.calculateHydrogenWavefunction(constant, n, l, m, r);
}
public double calculateWavefunctionConstant()
{
return QuantumMechanics.calculateHydrogenWavefunctionConstant(n, l, m, theta, phi);
}
public double calculateWavefunctionConstant(double theta, double phi)
{
return QuantumMechanics.calculateHydrogenWavefunctionConstant(n, l, m, theta, phi);
}
}
|
9233c6ae6d156ce9cd508e3bc0c500af951b38ac | 1,917 | java | Java | src/main/java/Core/Commands/Price.java | Wotee/StonksBot | 513ed5039680e376554e49f86f43e49b35e42c18 | [
"Apache-2.0"
] | null | null | null | src/main/java/Core/Commands/Price.java | Wotee/StonksBot | 513ed5039680e376554e49f86f43e49b35e42c18 | [
"Apache-2.0"
] | null | null | null | src/main/java/Core/Commands/Price.java | Wotee/StonksBot | 513ed5039680e376554e49f86f43e49b35e42c18 | [
"Apache-2.0"
] | null | null | null | 32.491525 | 107 | 0.663015 | 996,703 | package Core.Commands;
import Core.Configuration.ConfigLoader;
import Core.YahooAPI.DataStructures.AssetPriceIntraInfo;
import Core.YahooAPI.YahooConnectorImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
/**
* Used for querying latest price info for a single stock
* @author etsubu
* @version 29 Aug 2018
*
*/
@Component
public class Price extends Command {
private static final Logger log = LoggerFactory.getLogger(Price.class);
private final YahooConnectorImpl api;
/**
* Initializes Price
* @param api AlphaVantageConnector for querying information
*/
public Price(YahooConnectorImpl api, ConfigLoader configLoader) {
super(List.of("price", "hinta", "p"), configLoader, true);
this.api = api;
log.info("Initialized price command");
}
@Override
public CommandResult exec(String command) {
if(command.isBlank()) {
return new CommandResult("You need to specify stock name to query, see !help price", false);
}
log.info("Querying asset with: " + command);
try {
Optional<AssetPriceIntraInfo> info = api.queryCurrentIntraPriceInfo(command);
if(info.isEmpty()) {
return new CommandResult("Failed to request intraday info", false);
}
return new CommandResult(info.get().toString(), true);
} catch (IOException | InterruptedException e) {
return new CommandResult("Did not find a stock with they keyword '" + command + "'", false, e);
}
}
@Override
public String help() {
return "Displays intraday price data for the given stock\nUsage !" + String.join("/", super.names)
+ " [stockname/ticker]\nExample: !price msft";
}
}
|
9233c79fae33b777913dd375cef0280b057d9b0e | 1,260 | java | Java | src/main/java/com/ericsson/gerrit/plugins/highavailability/peers/PluginConfigPeerInfoProvider.java | GerritForge/plugins_high-availability | c9da6378515e81d69d81fe5dd9d71500273dd6a2 | [
"Apache-2.0"
] | 2 | 2019-01-15T10:59:21.000Z | 2021-05-28T07:18:17.000Z | src/main/java/com/ericsson/gerrit/plugins/highavailability/peers/PluginConfigPeerInfoProvider.java | GerritCodeReview/plugins_high-availability | b9b921d1bea184bf837a0bea9a512a8c92a36347 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ericsson/gerrit/plugins/highavailability/peers/PluginConfigPeerInfoProvider.java | GerritCodeReview/plugins_high-availability | b9b921d1bea184bf837a0bea9a512a8c92a36347 | [
"Apache-2.0"
] | 5 | 2018-02-21T17:15:34.000Z | 2021-06-14T03:37:15.000Z | 32.307692 | 96 | 0.764286 | 996,704 | // Copyright (C) 2017 The Android Open Source 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.ericsson.gerrit.plugins.highavailability.peers;
import com.ericsson.gerrit.plugins.highavailability.Configuration;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.util.Set;
import java.util.stream.Collectors;
@Singleton
public class PluginConfigPeerInfoProvider implements Provider<Set<PeerInfo>> {
private final Set<PeerInfo> peers;
@Inject
PluginConfigPeerInfoProvider(Configuration cfg) {
peers = cfg.peerInfoStatic().urls().stream().map(PeerInfo::new).collect(Collectors.toSet());
}
@Override
public Set<PeerInfo> get() {
return peers;
}
}
|
9233c7c574640ca28b965cf40c22ffdca780e4fb | 1,654 | java | Java | ARRAYS/SortRightDiagnal.java | vanshika1009/DASA | 518ded5ab4d5aa14f2204449d36135e5e310f4bf | [
"MIT"
] | null | null | null | ARRAYS/SortRightDiagnal.java | vanshika1009/DASA | 518ded5ab4d5aa14f2204449d36135e5e310f4bf | [
"MIT"
] | null | null | null | ARRAYS/SortRightDiagnal.java | vanshika1009/DASA | 518ded5ab4d5aa14f2204449d36135e5e310f4bf | [
"MIT"
] | null | null | null | 18.175824 | 110 | 0.533857 | 996,705 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SortRightDiagnal
{
public static void main(String agrs[]) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter the size of the array");
int n = Integer.parseInt(br.readLine());
int a[][] = new int[n][n];
System.out.println("Start entering the elements of matrix");
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
a[i][j] = Integer.parseInt(br.readLine());
}
}
print(a);
System.out.println();
right_diagnal(a);
}
static void print(int a[][])
{
int N = a.length;
for (int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
System.out.print(a[i][j]+", ");
}
System.out.println();
}
}
static void right_diagnal(int a[][])
{
int i, j;
int b[] = new int[a.length];
for (i=0; i<a.length; i++)
{
for (j=0; j<a[i].length; j++)
{
if((i+j) == 2)
{
b[i] = a[i][j];
}
}
}
Arrays.sort(b);
for (i=0; i<a.length; i++)
{
for (j=0; j<a[i].length; j++)
{
if((i+j) == 2)
{
a[i][j] = b[i];
}
}
}
print(a);
}
/*Use this optimised method if you want to solve it with one loop thus reducing the complexity of the program
static void right_diagnal(int a[][])
{
int i, j=0;
int b[] = new int[a.length];
for (i=2; i>=0; i--, j++)
{
b[i] = a[i][j];
}
Arrays.sort(b);
for (i=2, j=0; i>=0; i--, j++)
{
a[i][j] = b[i];
}
print(a);
}*/
}
|
9233c993445fc30640b372c777d6fc58240a812a | 1,705 | java | Java | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/BRLConditionVariableColumn.java | tomasdavidorg/drools | 938df6f2cfc8e233d2843d1eea9edc02bdba6e02 | [
"Apache-2.0"
] | null | null | null | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/BRLConditionVariableColumn.java | tomasdavidorg/drools | 938df6f2cfc8e233d2843d1eea9edc02bdba6e02 | [
"Apache-2.0"
] | null | null | null | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/BRLConditionVariableColumn.java | tomasdavidorg/drools | 938df6f2cfc8e233d2843d1eea9edc02bdba6e02 | [
"Apache-2.0"
] | null | null | null | 29.396552 | 80 | 0.639883 | 996,706 | /*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.drools.workbench.models.guided.dtable.shared.model;
/**
* A column representing a single BRL fragment variable
*/
public class BRLConditionVariableColumn extends ConditionCol52
implements
BRLVariableColumn {
private static final long serialVersionUID = 540l;
private String varName;
private String factType;
public BRLConditionVariableColumn() {
}
public BRLConditionVariableColumn( String varName,
String fieldType ) {
this.varName = varName;
super.setFieldType( fieldType );
}
public BRLConditionVariableColumn( String varName,
String fieldType,
String factType,
String factField ) {
this.varName = varName;
this.factType = factType;
super.setFactField( factField );
super.setFieldType( fieldType );
}
public String getVarName() {
return varName;
}
public String getFactType() {
return factType;
}
}
|
9233c9ebc68883d86439b0a501bb43d381065613 | 118 | java | Java | settings-datastructures-yaml/src/test/java/org/xbib/settings/datastructures/yaml/test/package-info.java | jprante/content | 54b000429de330c7bc54ee0838ecf7537825085f | [
"Apache-2.0"
] | null | null | null | settings-datastructures-yaml/src/test/java/org/xbib/settings/datastructures/yaml/test/package-info.java | jprante/content | 54b000429de330c7bc54ee0838ecf7537825085f | [
"Apache-2.0"
] | null | null | null | settings-datastructures-yaml/src/test/java/org/xbib/settings/datastructures/yaml/test/package-info.java | jprante/content | 54b000429de330c7bc54ee0838ecf7537825085f | [
"Apache-2.0"
] | null | null | null | 23.6 | 57 | 0.771186 | 996,707 | /**
* Testing YAML settings with the datastructures package.
*/
package org.xbib.settings.datastructures.yaml.test;
|
9233ca15308392736e3026be041da65335bc0c6f | 6,074 | java | Java | core/src/test/java/org/elasticsearch/action/main/MainResponseTests.java | ammar27/elasticsearch | dbb15bbf20b0c065ae4c1f225b2386d97c5be84b | [
"Apache-2.0"
] | 3 | 2017-06-13T03:32:36.000Z | 2021-07-21T08:46:35.000Z | core/src/test/java/org/elasticsearch/action/main/MainResponseTests.java | saaed64/elasticsearch | 9d2293b381415f86994d04d7f6c6598062d8eec4 | [
"Apache-2.0"
] | 68 | 2017-03-13T23:49:58.000Z | 2017-04-03T04:32:40.000Z | core/src/test/java/org/elasticsearch/action/main/MainResponseTests.java | saaed64/elasticsearch | 9d2293b381415f86994d04d7f6c6598062d8eec4 | [
"Apache-2.0"
] | 61 | 2017-03-14T01:00:29.000Z | 2017-03-24T06:06:39.000Z | 45.328358 | 136 | 0.679289 | 996,708 | /*
* Licensed to Elasticsearch 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.action.main;
import org.elasticsearch.Build;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
import java.io.IOException;
import java.util.Date;
import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
public class MainResponseTests extends ESTestCase {
public static MainResponse createTestItem() {
String clusterUuid = randomAsciiOfLength(10);
ClusterName clusterName = new ClusterName(randomAsciiOfLength(10));
String nodeName = randomAsciiOfLength(10);
Build build = new Build(randomAsciiOfLength(8), new Date(randomNonNegativeLong()).toString(), randomBoolean());
Version version = VersionUtils.randomVersion(random());
boolean available = randomBoolean();
return new MainResponse(nodeName, version, clusterName, clusterUuid , build, available);
}
public void testFromXContent() throws IOException {
MainResponse mainResponse = createTestItem();
XContentType xContentType = randomFrom(XContentType.values());
boolean humanReadable = randomBoolean();
BytesReference originalBytes = toXContent(mainResponse, xContentType, humanReadable);
MainResponse parsed;
try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
parsed = MainResponse.fromXContent(parser);
assertNull(parser.nextToken());
}
assertEquals(mainResponse.getClusterUuid(), parsed.getClusterUuid());
assertEquals(mainResponse.getClusterName(), parsed.getClusterName());
assertEquals(mainResponse.getNodeName(), parsed.getNodeName());
assertEquals(mainResponse.getBuild(), parsed.getBuild());
assertEquals(mainResponse.getVersion(), parsed.getVersion());
// we cannot recreate the "available" flag from xContent, but should be "true" if request came through
assertEquals(true, parsed.isAvailable());
assertToXContentEquivalent(originalBytes, toXContent(parsed, xContentType, humanReadable), xContentType);
}
public void testToXContent() throws IOException {
Build build = new Build("buildHash", "2016-11-15".toString(), true);
Version version = Version.V_2_4_5;
MainResponse response = new MainResponse("nodeName", version, new ClusterName("clusterName"), "clusterUuid", build, true);
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
assertEquals("{"
+ "\"name\":\"nodeName\","
+ "\"cluster_name\":\"clusterName\","
+ "\"cluster_uuid\":\"clusterUuid\","
+ "\"version\":{"
+ "\"number\":\"2.4.5\","
+ "\"build_hash\":\"buildHash\","
+ "\"build_date\":\"2016-11-15\","
+ "\"build_snapshot\":true,"
+ "\"lucene_version\":\"5.5.2\"},"
+ "\"tagline\":\"You Know, for Search\""
+ "}", builder.string());
}
public void testEqualsAndHashcode() {
MainResponse original = createTestItem();
checkEqualsAndHashCode(original, MainResponseTests::copy, MainResponseTests::mutate);
}
private static MainResponse copy(MainResponse o) {
return new MainResponse(o.getNodeName(), o.getVersion(), o.getClusterName(), o.getClusterUuid(), o.getBuild(), o.isAvailable());
}
private static MainResponse mutate(MainResponse o) {
String clusterUuid = o.getClusterUuid();
boolean available = o.isAvailable();
Build build = o.getBuild();
Version version = o.getVersion();
String nodeName = o.getNodeName();
ClusterName clusterName = o.getClusterName();
switch (randomIntBetween(0, 5)) {
case 0:
clusterUuid = clusterUuid + randomAsciiOfLength(5);
break;
case 1:
nodeName = nodeName + randomAsciiOfLength(5);
break;
case 2:
available = !available;
break;
case 3:
// toggle the snapshot flag of the original Build parameter
build = new Build(build.shortHash(), build.date(), !build.isSnapshot());
break;
case 4:
version = randomValueOtherThan(version, () -> VersionUtils.randomVersion(random()));
break;
case 5:
clusterName = new ClusterName(clusterName + randomAsciiOfLength(5));
break;
}
return new MainResponse(nodeName, version, clusterName, clusterUuid, build, available);
}
}
|
9233cb5c187b37be35662f47479e7ba5b826f78d | 3,533 | java | Java | src/main/java/cn/ac/dicp/group1809/utilities/mzIdentML_reader/io/input/SearchDatabaseReader.java | ZhengFang9502/mzIdentML-reader | f5a157e6e908c2f330b7a3da031588a6ed2217d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/ac/dicp/group1809/utilities/mzIdentML_reader/io/input/SearchDatabaseReader.java | ZhengFang9502/mzIdentML-reader | f5a157e6e908c2f330b7a3da031588a6ed2217d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/ac/dicp/group1809/utilities/mzIdentML_reader/io/input/SearchDatabaseReader.java | ZhengFang9502/mzIdentML-reader | f5a157e6e908c2f330b7a3da031588a6ed2217d1 | [
"Apache-2.0"
] | null | null | null | 33.971154 | 110 | 0.733937 | 996,709 | package cn.ac.dicp.group1809.utilities.mzIdentML_reader.io.input;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.CVParam;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.FileFormat;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.Param;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.SearchDatabase;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.adapter.DateAdapter;
import cn.ac.dicp.group1809.utilities.mzIdentML_reader.model.adapter.UriAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author ZhengFang 2018/9/20
* @since V1.0
*/
public class SearchDatabaseReader {
private static Logger logger = LoggerFactory.getLogger(SearchDatabaseReader.class);
public static SearchDatabase read(XMLStreamReader reader) throws XMLStreamException {
String name = reader.getLocalName();
SearchDatabase searchDatabase = new SearchDatabase();
ExternalDataReader.read(reader, searchDatabase);
Map<String, String> attributes = AttributeReader.getAttributes(reader);
for (String attributeName : attributes.keySet()) {
String attributeValue = attributes.get(attributeName);
switch (attributeName) {
case "version":
searchDatabase.setVersion(attributeValue);
break;
case "releaseDate":
try {
searchDatabase.setReleaseDate(new DateAdapter().unmarshal(attributeValue));
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
break;
case "numDatabaseSequences":
searchDatabase.setNumDatabaseSequences(Long.valueOf(attributeValue));
break;
case "numResidues":
searchDatabase.setNumResidues(Long.valueOf(attributeValue));
break;
case "id":
case "name":
case "location":
break;
default:
logger.error("Invalid attribute name in SearchDatabase section: " + attributeName);
throw new IllegalArgumentException("Invalid attribute name in SearchDatabase section: " + attributeName);
}
}
List<CVParam> cvParams = new ArrayList<>();
String localName;
loop:
while (reader.hasNext()) {
int next = reader.next();
switch (next) {
case XMLStreamReader.START_ELEMENT:
localName = reader.getLocalName();
switch (localName) {
case "ExternalFormatDocumentation":
searchDatabase.setExternalFormatDocumentation(new UriAdapter().unmarshal(reader.getElementText()));
break;
case "FileFormat":
FileFormat fileFormat = FileFormatReader.read(reader);
searchDatabase.setFileFormat(fileFormat);
break;
case "DatabaseName":
Param databaseName = ParamReader.read(reader);
searchDatabase.setDatabaseName(databaseName);
break;
case "cvParam":
CVParam cvParam = CVParamReader.read(reader);
cvParams.add(cvParam);
break;
default:
logger.error("Invalid local name in SearchDatabase section: " + localName);
throw new IllegalArgumentException("Invalid local name in SearchDatabase section: " + localName);
}
break;
case XMLStreamConstants.END_ELEMENT:
localName = reader.getLocalName();
if (name.equals(localName)) {
break loop;
}
}
}
searchDatabase.setCvParam(cvParams);
return searchDatabase;
}
}
|
9233cc17db05332c7faec4f393df19b0897656bc | 1,452 | java | Java | viikko4/MaksukorttiMockito/src/test/java/ohtu/matkakortti/KassapaateTest.java | ripa1002/ohtu-tehtavat | 140166719620e6c47c7f33271465a299e9674a41 | [
"MIT"
] | null | null | null | viikko4/MaksukorttiMockito/src/test/java/ohtu/matkakortti/KassapaateTest.java | ripa1002/ohtu-tehtavat | 140166719620e6c47c7f33271465a299e9674a41 | [
"MIT"
] | null | null | null | viikko4/MaksukorttiMockito/src/test/java/ohtu/matkakortti/KassapaateTest.java | ripa1002/ohtu-tehtavat | 140166719620e6c47c7f33271465a299e9674a41 | [
"MIT"
] | null | null | null | 25.928571 | 71 | 0.657713 | 996,710 |
package ohtu.matkakortti;
import ohtu.matkakortti.Maksukortti;
import ohtu.matkakortti.Kassapaate;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class KassapaateTest {
Kassapaate kassa;
Maksukortti kortti;
@Before
public void setUp() {
kassa = new Kassapaate();
kortti = mock(Maksukortti.class);
}
@Test
public void kortiltaVelotetaanHintaJosRahaaOn() {
when(kortti.getSaldo()).thenReturn(10);
kassa.ostaLounas(kortti);
verify(kortti, times(1)).getSaldo();
verify(kortti).osta(eq(Kassapaate.HINTA));
}
@Test
public void kortiltaEiVelotetaJosRahaEiRiita() {
when(kortti.getSaldo()).thenReturn(4);
kassa.ostaLounas(kortti);
verify(kortti, times(1)).getSaldo();
verify(kortti, times(0)).osta(anyInt());
}
@Test
public void kortilleLadataanRahaaJosSummaOnPositiivinen() {
kassa.lataa(kortti, 10);
verify(kortti).lataa(eq(10));
}
@Test
public void kortilleEiLadataRahaaJosSummaOnNegatiivinen() {
kassa.lataa(kortti, -10);
verify(kortti, times(0)).lataa(anyInt());
}
}
|
9233cc5a80012fde7f4909a3b581fc8143db8a9a | 1,923 | java | Java | Chapter6-todolist/ui/NoteListAdapter.java | yangzheming123/yangzheming | 192d28d794d926cb32130fe3a0a7c9f42d1db7b3 | [
"CC0-1.0"
] | null | null | null | Chapter6-todolist/ui/NoteListAdapter.java | yangzheming123/yangzheming | 192d28d794d926cb32130fe3a0a7c9f42d1db7b3 | [
"CC0-1.0"
] | null | null | null | Chapter6-todolist/ui/NoteListAdapter.java | yangzheming123/yangzheming | 192d28d794d926cb32130fe3a0a7c9f42d1db7b3 | [
"CC0-1.0"
] | null | null | null | 28.352941 | 83 | 0.640041 | 996,711 | package com.byted.camp.todolist.ui;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.byted.camp.todolist.NoteOperator;
import com.byted.camp.todolist.R;
import com.byted.camp.todolist.beans.Note;
import java.util.ArrayList;
import java.util.List;
/**
* Created on 2019/1/23.
*
* @author hzdkv@example.com (Yingyi Xu)
*/
public class NoteListAdapter extends RecyclerView.Adapter<NoteViewHolder> {
private final NoteOperator operator;
private final List<Note> notes = new ArrayList<>();
public NoteListAdapter(NoteOperator operator) {
this.operator = operator;
}
public void refresh(List<Note> newNotes) {
notes.clear();
if (newNotes != null) {
notes.addAll(newNotes);
}
notifyDataSetChanged();
}
@NonNull
@Override
public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int pos) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_note, parent, false);
return new NoteViewHolder(itemView, operator);
}
@Override
public void onBindViewHolder(@NonNull NoteViewHolder holder, final int pos) {
holder.bind(notes.get(pos));
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
operator.deleteNote(notes.get(pos));
notes.remove(pos);
notifyItemRemoved(pos);
notifyItemChanged(pos,getItemCount());
}
});
}
@Override
public int getItemCount() {
return notes.size();
}
}
|
9233ccb9d75f24116a7d6c22c35cdd58f1a0282e | 16,556 | java | Java | Corpus/birt/6392.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | 1 | 2022-01-15T02:47:45.000Z | 2022-01-15T02:47:45.000Z | Corpus/birt/6392.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | Corpus/birt/6392.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | 35.30064 | 96 | 0.739611 | 996,712 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.adapter.oda.api;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.model.adapter.oda.IModelOdaAdapter;
import org.eclipse.birt.report.model.adapter.oda.ModelOdaAdapter;
import org.eclipse.birt.report.model.adapter.oda.model.DesignValues;
import org.eclipse.birt.report.model.adapter.oda.model.ModelFactory;
import org.eclipse.birt.report.model.adapter.oda.model.util.SchemaConversionUtil;
import org.eclipse.birt.report.model.adapter.oda.util.BaseTestCase;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.elements.structures.OdaDataSetParameter;
import org.eclipse.datatools.connectivity.oda.design.DataElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
import org.eclipse.datatools.connectivity.oda.design.DataSetParameters;
import org.eclipse.datatools.connectivity.oda.design.DataSourceDesign;
import org.eclipse.datatools.connectivity.oda.design.DesignFactory;
import org.eclipse.datatools.connectivity.oda.design.ElementNullability;
import org.eclipse.datatools.connectivity.oda.design.InputElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.InputParameterAttributes;
import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition;
import org.eclipse.datatools.connectivity.oda.design.ParameterMode;
import org.eclipse.datatools.connectivity.oda.design.Properties;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* Test cases to convert Oda data set parameters and ROM data set parameter and
* linked report parameters.
*
*/
public class DataSetParameterAdapterTest extends BaseTestCase
{
/**
* Test parameter count.
*
* @param setHandle
* oda dataset handle.
*/
private void testParametersCount( OdaDataSetHandle setHandle,
int expectValue )
{
int count = 0;
Iterator iterator = setHandle.parametersIterator( );
while ( iterator.hasNext( ) )
{
iterator.next( );
++count;
}
assertEquals( expectValue, count );
}
/**
* Test New rule of merge parameter between <code>DataSetDesign</code> and
* <code>DataSetHandle</code>
*
* @throws Exception
*/
public void testMergeParamDefnFromDesignToHandle( ) throws Exception
{
openDesign( "DataSetMergeTest.xml" ); //$NON-NLS-1$
OdaDataSetHandle setHandle = (OdaDataSetHandle) designHandle
.findDataSet( "Data Set" ); //$NON-NLS-1$
DataSetDesign setDesign = new ModelOdaAdapter( )
.createDataSetDesign( setHandle );
setHandle.setProperty( OdaDataSetHandle.PARAMETERS_PROP, null );
// Parameters defined in DataSetDesign , but not in DataSetHandle
IModelOdaAdapter adapter = new ModelOdaAdapter( );
adapter.updateDataSetHandle( setDesign, setHandle, false );
testParametersCount( setHandle, 3 );
// Parameter 2 defined in DataSetHandle , but not in DataSetDesign.
setHandle.setDesignerValues( null );
PropertyHandle propHandle = setHandle
.getPropertyHandle( OdaDataSetHandle.PARAMETERS_PROP );
OdaDataSetParameter parameter = (OdaDataSetParameter) propHandle
.getAt( 2 ).getStructure( ).copy( );
propHandle.removeItem( 2 );
DataSetDesign setDesign2 = new ModelOdaAdapter( )
.createDataSetDesign( setHandle );
propHandle.addItem( parameter );
adapter.updateDataSetHandle( setDesign2, setHandle, false );
testParametersCount( setHandle, 3 );
}
/**
* Test case:
*
* <ul>
* <li>when convert default value, string type should distinguish expression
* and literal.
* <li>When convert oda data set parameter to ROM data set parameter.
* Default values are kept. <br>
* And the data type is kept even the native data type is unknown.
* </ul>
*
* @throws Exception
*/
public void testDataTypeConversion( ) throws Exception
{
// create oda set handle.
openDesign( "DataSetParamConvertTest_1.xml" ); //$NON-NLS-1$
OdaDataSetHandle setHandle = (OdaDataSetHandle) designHandle
.findDataSet( "myDataSet1" ); //$NON-NLS-1$
DataSetDesign setDesign = new ModelOdaAdapter( )
.createDataSetDesign( setHandle );
DesignValues values = ModelFactory.eINSTANCE.createDesignValues( );
values.setDataSetParameters( SchemaConversionUtil
.convertToAdapterParameters( EcoreUtil.copy( setDesign
.getParameters( ) ) ) );
saveDesignValuesToFile( values );
assertTrue( compareTextFile( "DataSetParamConvertTest_golden_1.xml" ) ); //$NON-NLS-1$
new ModelOdaAdapter( )
.updateDataSetHandle( setDesign, setHandle, false );
save( );
assertTrue( compareTextFile( "DataSetParamConvertTest_golden_2.xml" ) ); //$NON-NLS-1$
}
/**
* Test case:
*
* <ul>
* <li>Convert values from ODA parameter definition to ROM data set
* parameter. Focus on default values.
* </ul>
*
* @throws Exception
*/
public void testValuesConversion( ) throws Exception
{
// create oda set handle.
openDesign( "DataSetParamConvertTest_1.xml" ); //$NON-NLS-1$
OdaDataSetHandle setHandle = (OdaDataSetHandle) designHandle
.findDataSet( "myDataSet1" ); //$NON-NLS-1$
DataSetDesign setDesign = new ModelOdaAdapter( )
.createDataSetDesign( setHandle );
// oda data set design changed, update ROM values. still keep report
// parameter link.
DataSetParameters params = setDesign.getParameters( );
ParameterDefinition param = (ParameterDefinition) params
.getParameterDefinitions( ).get( 0 );
updateParameterDefinition1( param );
new ModelOdaAdapter( )
.updateDataSetHandle( setDesign, setHandle, false );
save( );
assertTrue( compareTextFile( "DataSetParamConvertTest_golden_3.xml" ) ); //$NON-NLS-1$
}
/**
* Updates a oda parameter definition. Keep the direction.
*
* @param param
*/
private void updateParameterDefinition1( ParameterDefinition param )
{
DataElementAttributes dataAttrs = param.getAttributes( );
dataAttrs.setNullability( ElementNullability
.get( ElementNullability.NOT_NULLABLE ) );
InputParameterAttributes paramAttrs = param.getInputAttributes( );
InputElementAttributes elementAttrs = paramAttrs.getElementAttributes( );
elementAttrs
.setDefaultScalarValue( "new default value for report param 1" ); //$NON-NLS-1$
elementAttrs.setOptional( true );
}
/**
* Tests the algorithm to create unique data set parameter names.
*
* @throws Exception
*/
public void testDataSetParamNames( ) throws Exception
{
DataSetDesign setDesign = createDataSetDesignForParamNames( );
createDesign( );
OdaDataSetHandle setHandle = new ModelOdaAdapter( )
.createDataSetHandle( setDesign, designHandle );
designHandle.getDataSets( ).add( setHandle );
save( );
assertTrue( compareTextFile( "DataSetParameterNameTest_golden.xml" ) ); //$NON-NLS-1$
setDesign = createDataSetDesignForParamNames1( );
setHandle = new ModelOdaAdapter( ).createDataSetHandle( setDesign,
designHandle );
List params = (List) setHandle
.getProperty( OdaDataSetHandle.PARAMETERS_PROP );
OdaDataSetParameter param = (OdaDataSetParameter) params.get( 0 );
assertEquals( 0, param.getPosition( ).intValue( ) );
param = (OdaDataSetParameter) params.get( 1 );
assertEquals( 1, param.getPosition( ).intValue( ) );
setDesign = createDataSetDesignForParamNames1( );
// should not exception
setHandle = new ModelOdaAdapter( ).createDataSetHandle( setDesign,
designHandle );
}
/**
* Creates a new <code>DataSetDesign</code>.
*
* @return an object of <code>DataSetDesign</code>.
*/
static DataSetDesign createDataSetDesignForParamNames( )
{
DataSetDesign setDesign = DesignFactory.eINSTANCE.createDataSetDesign( );
setDesign.setName( "myDataSet1" ); //$NON-NLS-1$
setDesign.setDisplayName( "data set display name" ); //$NON-NLS-1$
setDesign
.setOdaExtensionDataSetId( OdaDataSetAdapterTest.DATA_SET_EXTENSIONID );
Properties props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new public query time out" ); //$NON-NLS-1$//$NON-NLS-2$
setDesign.setPublicProperties( props );
props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new private query time out" ); //$NON-NLS-1$ //$NON-NLS-2$
setDesign.setPrivateProperties( props );
DataSetParameters params = DesignFactory.eINSTANCE
.createDataSetParameters( );
ParameterDefinition paramDefn = DesignFactory.eINSTANCE
.createParameterDefinition( );
DataElementAttributes dataAttrs = DesignFactory.eINSTANCE
.createDataElementAttributes( );
dataAttrs.setName( "nativeName1" ); //$NON-NLS-1$
dataAttrs.setPosition( 1 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
paramDefn = DesignFactory.eINSTANCE.createParameterDefinition( );
dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( );
dataAttrs.setName( "" ); //$NON-NLS-1$
dataAttrs.setPosition( 2 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
paramDefn = DesignFactory.eINSTANCE.createParameterDefinition( );
dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( );
dataAttrs.setName( "nativeName1" ); //$NON-NLS-1$
dataAttrs.setPosition( 3 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
setDesign.setParameters( params );
setDesign.setPrimaryResultSetName( "resultset1" ); //$NON-NLS-1$
setDesign.setQueryText( "new query text" ); //$NON-NLS-1$
// create the corresponding data source design
setDesign.setDataSourceDesign( createDataSourceDesign( ) );
return setDesign;
}
/**
* Creates a new <code>DataSourceDesign</code>.
*
* @return an object of <code>DataSourceDesign</code>.
*/
private static DataSourceDesign createDataSourceDesign( )
{
DataSourceDesign sourceDesign = DesignFactory.eINSTANCE
.createDataSourceDesign( );
sourceDesign.setName( "myDataSource1" ); //$NON-NLS-1$
sourceDesign.setDisplayName( "data source display name" ); //$NON-NLS-1$
sourceDesign
.setOdaExtensionId( OdaDataSetAdapterTest.DATA_SOURCE_EXTENSIONID );
Properties props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "odaDriverClass", "new drivers" ); //$NON-NLS-1$//$NON-NLS-2$
props.setProperty( "odaURL", "jdbc:sqlserver://localhost" ); //$NON-NLS-1$//$NON-NLS-2$
props.setProperty( "odaUser", "new user" ); //$NON-NLS-1$ //$NON-NLS-2$
sourceDesign.setPublicProperties( props );
props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "odaDriverClass", "new drivers" ); //$NON-NLS-1$ //$NON-NLS-2$
props.setProperty( "odaPassword", "new password" ); //$NON-NLS-1$ //$NON-NLS-2$
sourceDesign.setPrivateProperties( props );
return sourceDesign;
}
/**
* Creates a new <code>DataSetDesign</code>. Parameter positions are not
* set.
*
* @return an object of <code>DataSetDesign</code>.
*/
static DataSetDesign createDataSetDesignForParamNames1( )
{
DataSetDesign setDesign = DesignFactory.eINSTANCE.createDataSetDesign( );
setDesign.setName( "myDataSet1" ); //$NON-NLS-1$
setDesign.setDisplayName( "data set display name" ); //$NON-NLS-1$
setDesign
.setOdaExtensionDataSetId( OdaDataSetAdapterTest.DATA_SET_EXTENSIONID );
Properties props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new public query time out" ); //$NON-NLS-1$//$NON-NLS-2$
setDesign.setPublicProperties( props );
props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new private query time out" ); //$NON-NLS-1$ //$NON-NLS-2$
setDesign.setPrivateProperties( props );
DataSetParameters params = DesignFactory.eINSTANCE
.createDataSetParameters( );
ParameterDefinition paramDefn = DesignFactory.eINSTANCE
.createParameterDefinition( );
DataElementAttributes dataAttrs = DesignFactory.eINSTANCE
.createDataElementAttributes( );
dataAttrs.setName( "nativeName1" ); //$NON-NLS-1$
dataAttrs.setPosition( 0 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
paramDefn = DesignFactory.eINSTANCE.createParameterDefinition( );
dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( );
dataAttrs.setName( "" ); //$NON-NLS-1$
dataAttrs.setPosition( 1 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
params.getParameterDefinitions( ).add( paramDefn );
setDesign.setParameters( params );
setDesign.setPrimaryResultSetName( "resultset1" ); //$NON-NLS-1$
setDesign.setQueryText( "new query text" ); //$NON-NLS-1$
// create the corresponding data source design
setDesign.setDataSourceDesign( createDataSourceDesign( ) );
return setDesign;
}
/**
* Creates a new <code>DataSetDesign</code>. Parameters positions are
* duplicate.
*
* @return an object of <code>DataSetDesign</code>.
*/
static DataSetDesign createDataSetDesignForParamNames2( )
{
DataSetDesign setDesign = DesignFactory.eINSTANCE.createDataSetDesign( );
setDesign.setName( "myDataSet1" ); //$NON-NLS-1$
setDesign.setDisplayName( "data set display name" ); //$NON-NLS-1$
setDesign
.setOdaExtensionDataSetId( OdaDataSetAdapterTest.DATA_SET_EXTENSIONID );
Properties props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new public query time out" ); //$NON-NLS-1$//$NON-NLS-2$
setDesign.setPublicProperties( props );
props = DesignFactory.eINSTANCE.createProperties( );
props.setProperty( "queryTimeOut", "new private query time out" ); //$NON-NLS-1$ //$NON-NLS-2$
setDesign.setPrivateProperties( props );
DataSetParameters params = DesignFactory.eINSTANCE
.createDataSetParameters( );
ParameterDefinition paramDefn = DesignFactory.eINSTANCE
.createParameterDefinition( );
DataElementAttributes dataAttrs = DesignFactory.eINSTANCE
.createDataElementAttributes( );
dataAttrs.setName( "nativeName1" ); //$NON-NLS-1$
dataAttrs.setPosition( 1 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
paramDefn = DesignFactory.eINSTANCE.createParameterDefinition( );
dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( );
dataAttrs.setName( "" ); //$NON-NLS-1$
dataAttrs.setPosition( 1 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
paramDefn = DesignFactory.eINSTANCE.createParameterDefinition( );
dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( );
dataAttrs.setName( "nativeName1" ); //$NON-NLS-1$
dataAttrs.setPosition( 3 );
dataAttrs.setNativeDataTypeCode( 1 );
paramDefn.setAttributes( dataAttrs );
paramDefn.setInOutMode( ParameterMode.get( ParameterMode.IN_OUT ) );
params.getParameterDefinitions( ).add( paramDefn );
setDesign.setParameters( params );
setDesign.setPrimaryResultSetName( "resultset1" ); //$NON-NLS-1$
setDesign.setQueryText( "new query text" ); //$NON-NLS-1$
// create the corresponding data source design
setDesign.setDataSourceDesign( createDataSourceDesign( ) );
return setDesign;
}
}
|
9233ccf6f514030d858565127b88b33867e15395 | 12,198 | java | Java | tools/cytoscape-gpml/src/org/pathvisio/cytoscape/GpmlConverter.java | kozo2/pathvisio | 67f66da1fb76a001a5e5cbbf5f6bff3dc555be83 | [
"Apache-2.0"
] | null | null | null | tools/cytoscape-gpml/src/org/pathvisio/cytoscape/GpmlConverter.java | kozo2/pathvisio | 67f66da1fb76a001a5e5cbbf5f6bff3dc555be83 | [
"Apache-2.0"
] | null | null | null | tools/cytoscape-gpml/src/org/pathvisio/cytoscape/GpmlConverter.java | kozo2/pathvisio | 67f66da1fb76a001a5e5cbbf5f6bff3dc555be83 | [
"Apache-2.0"
] | null | null | null | 30.044335 | 98 | 0.673881 | 996,713 | // PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.cytoscape;
import giny.view.GraphView;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.model.ConverterException;
import org.pathvisio.core.model.GpmlFormat;
import org.pathvisio.core.model.ObjectType;
import org.pathvisio.core.model.Pathway;
import org.pathvisio.core.model.PathwayElement;
import org.pathvisio.core.model.GraphLink.GraphIdContainer;
import org.pathvisio.core.model.PathwayElement.MAnchor;
import cytoscape.CyEdge;
import cytoscape.CyNode;
import cytoscape.Cytoscape;
import cytoscape.CytoscapeInit;
import cytoscape.groups.CyGroup;
import cytoscape.groups.CyGroupManager;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.layout.CyLayouts;
import cytoscape.view.CyNetworkView;
/**
* Converts GPML or fragments of GPML to a network.
* Invoked both by direct loading from file, or by clipboard actions.
*/
public class GpmlConverter {
public static final String PROP_LABEL_AS_NODE = "gpml.label.as.node";
List<CyEdge> edges = new ArrayList<CyEdge>();
Map<GraphIdContainer, CyNode> nodeMap = new HashMap<GraphIdContainer, CyNode>();
Map<PathwayElement, String[]> edgeMap = new HashMap<PathwayElement, String[]>();
GpmlHandler gpmlHandler;
Pathway pathway;
private boolean loadAsNetwork = false;
private GpmlConverter(GpmlHandler h) {
gpmlHandler = h;
}
public GpmlConverter(GpmlHandler gpmlHandler, Pathway p) {
this(gpmlHandler);
pathway = p;
convert();
}
public GpmlConverter(GpmlHandler gpmlHandler, Pathway p, boolean loadAsNetwork) {
this(gpmlHandler);
this.loadAsNetwork = loadAsNetwork;
pathway = p;
convert();
}
public GpmlConverter(GpmlHandler gpmlHandler, String gpml) throws ConverterException {
this(gpmlHandler);
pathway = new Pathway();
GpmlFormat.readFromXml(pathway, new StringReader(gpml), true);
convert();
}
private void convert() {
edgeMap.clear();
edges.clear();
nodeMap.clear();
nodeIds.clear();
findNodes();
findEdges();
}
public Pathway getPathway() {
return pathway;
}
Map<GraphIdContainer, String> nodeIds = new HashMap<GraphIdContainer, String>();
private String generateNodeId(GraphIdContainer o, String preferred) {
String id = preferred;
if(id != null) {
CyNode node = Cytoscape.getCyNode(id, false);
if(node != null) {
if(loadAsNetwork) {
Logger.log.trace("Adding id " + id);
nodeIds.put(o, id);
return id;
}
id = null; //Node already exists, use graphId instead!
}
}
if(id == null || "".equals(id)) {
id = o.getGraphId();
//Get an id if it's not already there
if(id == null) {
id = pathway.getUniqueGraphId();
o.setGraphId(id);
}
}
Logger.log.trace("Adding id " + id);
nodeIds.put(o, id);
return id;
}
private String getNodeId(GraphIdContainer o) {
return nodeIds.get(o);
}
private void findNodes() {
for(PathwayElement o : pathway.getDataObjects()) {
ObjectType type = o.getObjectType();
if(
type == ObjectType.BIOPAX ||
type == ObjectType.LEGEND ||
type == ObjectType.INFOBOX ||
type == ObjectType.MAPPINFO
) {
continue;
}
if(loadAsNetwork && (type == ObjectType.LABEL || type == ObjectType.SHAPE)) {
continue;
}
String id = generateNodeId(o, o.getTextLabel());
CyNode n = null;
switch(type) {
case GROUP:
Logger.log.trace("Creating group: " + id);
n = addGroup(o);
if(n == null) {
Logger.log.error("Group node is null");
} else {
Logger.log.trace("Created group node: " + n.getIdentifier());
}
break;
case LINE:
if(isEdge(o)) {
continue; //Don't add an annotation node for an edge
}
default:
//Create a node for every pathway element
Logger.log.trace("Creating node: " + id + " for " + o.getGraphId() + "@" + o.getObjectType());
n = Cytoscape.getCyNode(id, true);
}
gpmlHandler.addNode(n, o);
nodeMap.put(o, n);
}
processGroups();
}
private boolean isEdge(PathwayElement e) {
GraphIdContainer start = pathway.getGraphIdContainer(e.getMStart().getGraphRef());
GraphIdContainer end = pathway.getGraphIdContainer(e.getMEnd().getGraphRef());
Logger.log.trace("Checking if edge " + e.getGraphId() + ": " +
isNode(start) + ", " + isNode(end)
);
return isNode(start) && isNode(end);
}
private boolean isNode(GraphIdContainer idc) {
if(idc instanceof MAnchor) {
//only valid if the parent line is an edge
return isEdge(((MAnchor)idc).getParent());
} else if(idc instanceof PathwayElement) {
ObjectType ot = ((PathwayElement)idc).getObjectType();
if(loadAsNetwork && ot == ObjectType.LABEL) return false;
return
ot == ObjectType.DATANODE ||
ot == ObjectType.GROUP ||
(labelAsNode() && ot == ObjectType.LABEL);
} else {
return false;
}
}
/**
* Should labels be treated as nodes or as annotations?
* This can be controlled by the Cytoscape property named
* {@link #PROP_LABEL_AS_NODE}. If set to "true", labels will
* be treated as nodes.
*/
public static boolean labelAsNode() {
Properties p = CytoscapeInit.getProperties();
String value = (String)p.get(PROP_LABEL_AS_NODE);
return Boolean.parseBoolean(value); //Defaults to false
}
private void findEdges() {
Logger.log.trace("Start finding edges");
//First find edges that contain anchors
//Add an AnchorNode for that line
for(PathwayElement pe : pathway.getDataObjects()) {
if(pe.getObjectType() == ObjectType.LINE) {
if(pe.getMAnchors().size() > 0 && isEdge(pe)) {
CyNode n = Cytoscape.getCyNode(generateNodeId(pe, pe.getGraphId()), true);
gpmlHandler.addAnchorNode(n, pe);
for(MAnchor a : pe.getMAnchors()) {
nodeMap.put(a, n);
nodeIds.put(a, n.getIdentifier());
}
}
}
}
//Create the cytoscape edges for each line for which
//both the start and end points connect to a node
for(PathwayElement pe : pathway.getDataObjects()) {
if(pe.getObjectType() == ObjectType.LINE) {
if(isEdge(pe)) {
//A line without anchors, convert to single edge
if(pe.getMAnchors().size() == 0) {
String source = getNodeId(pathway.getGraphIdContainer(pe.getMStart().getGraphRef()));
String target = getNodeId(pathway.getGraphIdContainer(pe.getMEnd().getGraphRef()));
Logger.log.trace("Line without anchors ( " + pe.getGraphId() + " ) to edge: " +
source + ", " + target
);
String type = pe.getStartLineType() + ", " + pe.getEndLineType();
CyEdge e = Cytoscape.getCyEdge(
source,
pe.getGraphId(),
target,
type
);
edges.add(e);
gpmlHandler.addEdge(e, pe);
//A line with anchors, split into multiple edges
} else {
String sId = nodeMap.get(
pathway.getGraphIdContainer(pe.getMStart().getGraphRef())
).getIdentifier();
String eId = nodeMap.get(
pathway.getGraphIdContainer(pe.getMEnd().getGraphRef())
).getIdentifier();
Logger.log.trace("Line with anchors ( " + pe.getGraphId() + " ) to edges: " +
sId + ", " + eId
);
CyEdge es = Cytoscape.getCyEdge(
sId,
pe.getGraphId() + "_start",
gpmlHandler.getNode(pe.getGraphId()).getParentIdentifier(),
GpmlHandler.ANCHOR_EDGE_TYPE
);
edges.add(es);
PathwayElement peStart = pe.copy();
peStart.setEndLineType(null);
gpmlHandler.addEdge(es, peStart);
CyEdge ee = Cytoscape.getCyEdge(
gpmlHandler.getNode(pe.getGraphId()).getParentIdentifier(),
pe.getGraphId() + "end",
eId,
GpmlHandler.ANCHOR_EDGE_TYPE
);
edges.add(ee);
PathwayElement peEnd = pe.copy();
peStart.setStartLineType(null);
gpmlHandler.addEdge(ee, peEnd);
}
}
}
}
//Fix anchor links
for(GpmlNode gn : gpmlHandler.getNodes()) {
if(gn instanceof GpmlAnchorNode) {
((GpmlAnchorNode)gn).cleanupAnchors();
}
}
}
public int[] getNodeIndicesArray() {
int[] inodes = new int[nodeMap.size()];
int i = 0;
for(CyNode n : nodeMap.values()) {
inodes[i++] = n.getRootGraphIndex();
}
return inodes;
}
public int[] getEdgeIndicesArray() {
int[] iedges = new int[edges.size()];
for(int i = 0; i< edges.size(); i++) {
iedges[i] = edges.get(i).getRootGraphIndex();
}
return iedges;
}
//Add a group node
private CyNode addGroup(PathwayElement group) {
CyGroup cyGroup = CyGroupManager.findGroup(group.getGroupId());
if(cyGroup == null) {
cyGroup = CyGroupManager.createGroup(group.getGroupId(), null);
}
CyNode gn = cyGroup.getGroupNode();
gn.setIdentifier(group.getGraphId() == null ? group.setGeneratedGraphId() : group.getGraphId());
nodeIds.put(group, gn.getIdentifier());
return gn;
}
//Add all nodes to the group
private void processGroups() {
for(PathwayElement pwElm : pathway.getDataObjects()) {
if(pwElm.getObjectType() == ObjectType.GROUP) {
GpmlNode gpmlNode = gpmlHandler.getNode(getNodeId(pwElm));
CyGroup cyGroup = CyGroupManager.getCyGroup(gpmlNode.getParent());
if(cyGroup == null) {
Logger.log.warn("Couldn't create group: CyGroupManager returned null");
return;
}
//The interaction name
String interaction = GpmlHandler.GROUP_EDGE_TYPE;
PathwayElement[] groupElements = pathway.getGroupElements(
pwElm.getGroupId()
).toArray(new PathwayElement[0]);
//Create the cytoscape parts of the group
for(int i = 0; i < groupElements.length; i++) {
PathwayElement peI = groupElements[i];
if(peI.getObjectType() == ObjectType.LINE) continue; //Skip grouped lines
GpmlNetworkElement neI = gpmlHandler.getNetworkElement(getNodeId(peI));
//Only add links to nodes, not to annotations
if(neI instanceof GpmlNode) {
cyGroup.addNode(((GpmlNode)neI).getParent());
edges.add(Cytoscape.getCyEdge(
cyGroup.getGroupNode().getIdentifier(),
"inGroup: " + cyGroup.getGroupName(),
neI.getParentIdentifier(), interaction)
);
// //Add links between all elements of the group
// for(int j = i + 1; j < groupElements.length; j++) {
// PathwayElement pe_j = groupElements[j];
// GpmlNetworkElement<?> ne_j = gpmlHandler.getNetworkElement(pe_j.getGraphId());
// if(ne_j instanceof GpmlNode) {
// edges.add(Cytoscape.getCyEdge(
// ne_i.getParentIdentifier(),
// "inGroup: " + cyGroup.getGroupName(),
// ne_j.getParentIdentifier(), interaction)
// );
// }
// }
}
}
}
}
}
private void setGroupViewer(CyNetworkView view, String groupViewer) {
for(GpmlNode gn : gpmlHandler.getNodes()) {
if(gn.getPathwayElement().getObjectType() == ObjectType.GROUP) {
CyGroup group = CyGroupManager.getCyGroup(gn.getParent());
CyGroupManager.setGroupViewer(group, groupViewer, view, true);
}
}
}
/**
* Add annotations, layout nodes, then create and apply visual style.
*
* @param view
*/
public void layout(GraphView view)
{
gpmlHandler.addAnnotations(view, nodeMap.values());
if(loadAsNetwork) gpmlHandler.showAnnotations(view, false);
gpmlHandler.applyGpmlLayout(view, nodeMap.values());
if(loadAsNetwork) {
CyLayoutAlgorithm alg = CyLayouts.getLayout("force-directed");
alg.doLayout();
}
gpmlHandler.applyGpmlVisualStyle();
view.fitContent();
}
}
|
9233cd301a8539a2a7b311467a0ef6db242d9999 | 797 | java | Java | cvdnn-lang/src/main/java/android/assist/ADB.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | cvdnn-lang/src/main/java/android/assist/ADB.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | cvdnn-lang/src/main/java/android/assist/ADB.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | 26.566667 | 132 | 0.628607 | 996,714 | package android.assist;
import android.assist.Shell.CommandResult;
public class ADB {
public static final int DEFAULT_ADB_PORT = 5555;
public static boolean adbTCP() {
return adbTCP(DEFAULT_ADB_PORT);
}
public static boolean adbTCP(int port) {
boolean result = false;
CommandResult commandResult = Shell.execute("setprop service.adb.tcp.port " + (port == -1 ? DEFAULT_ADB_PORT : port), true);
if (CommandResult.success(commandResult)) {
commandResult = Shell.execute("stop adbd", true);
if (CommandResult.success(commandResult)) {
commandResult = Shell.execute("start adbd", true);
result = CommandResult.success(commandResult);
}
}
return result;
}
}
|
9233cef2b6d60fac2bfc2552ebe0a342857eef7e | 201 | java | Java | src/main/java/com/kc/project/mapper/SysGeneratorSqlServerMapper.java | maixiangyu666/springboot-manager | 936958c43654241f28ae46061aafbbe5df7873ff | [
"MIT"
] | null | null | null | src/main/java/com/kc/project/mapper/SysGeneratorSqlServerMapper.java | maixiangyu666/springboot-manager | 936958c43654241f28ae46061aafbbe5df7873ff | [
"MIT"
] | null | null | null | src/main/java/com/kc/project/mapper/SysGeneratorSqlServerMapper.java | maixiangyu666/springboot-manager | 936958c43654241f28ae46061aafbbe5df7873ff | [
"MIT"
] | null | null | null | 16.75 | 70 | 0.716418 | 996,715 | package com.kc.project.mapper;
/**
* 代码生成sqlServer、 Mapper
* @author mxy
* @email ${email}
* @date 2020-4-19 09:28:13
*/
public interface SysGeneratorSqlServerMapper extends GeneratorMapper {
}
|
9233d0ac42276a985b004248b5d445b291d7998f | 2,134 | java | Java | QuerySet.java | elenidriva/Retrieval-of-the-k-closest-documents-using-Elasticsearch-and-evaluation | 8e7fe88efbd155f08653f2105c611da8447c7eaa | [
"MIT"
] | null | null | null | QuerySet.java | elenidriva/Retrieval-of-the-k-closest-documents-using-Elasticsearch-and-evaluation | 8e7fe88efbd155f08653f2105c611da8447c7eaa | [
"MIT"
] | null | null | null | QuerySet.java | elenidriva/Retrieval-of-the-k-closest-documents-using-Elasticsearch-and-evaluation | 8e7fe88efbd155f08653f2105c611da8447c7eaa | [
"MIT"
] | null | null | null | 36.793103 | 134 | 0.582474 | 996,716 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class QuerySet {
public static void main(String[] args) throws IOException {
File query = new File("C:\\Users\\ele_1\\Documents\\Mathimata\\Sustimata Anaktisis\\Project\\10 Queries in txt format");
//File dummy = new File("C:\\Users\\ele_1\\Documents\\Mathimata\\Sustimata Anaktisis\\Project\\10 Queries in txt format\\30%");
File[] Q = query.listFiles();
System.out.println("**Parsing the Query files**");
int index = 1;
for(File f: Q) {
if(f.isFile()) {
BufferedReader in = new BufferedReader(new FileReader(f));
String str;
int lines = 0;
System.out.println(lines);
while ((str = in.readLine())!= null) {
lines++;
}
System.out.println(lines);
double percentage = 0.9;
int linesKept = (int) Math.ceil(percentage*lines);
BufferedReader inToW = new BufferedReader(new FileReader(f));
System.out.println(linesKept);
int counter = 0;
// FileOutputStream fos = new FileOutputStream("Q0"+index+".txt", true);
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
FileWriter fileWriter =
new FileWriter("Q0"+index+".txt", true);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
String line;
while(counter < linesKept) {
line = inToW.readLine();
System.out.println(line);
bufferedWriter.write(line);
bufferedWriter.newLine();
counter++;
}
bufferedWriter.close();
index++;
}
}
}
} |
9233d329928570c47e6b3a4c8cbd1998ac100c7c | 325 | java | Java | src/cn/edu/gdut/zaoying/Option/series/gauge/axisLine/lineStyle/ColorArray.java | zaoying/EChartsAnnotation | 4f0e6c972114fbd4ab86bf5e3bd2e42dbe9ce2f1 | [
"MIT"
] | 22 | 2016-03-02T03:03:47.000Z | 2021-03-29T13:26:29.000Z | src/cn/edu/gdut/zaoying/Option/series/gauge/axisLine/lineStyle/ColorArray.java | zaoying/EChartsAnnotation | 4f0e6c972114fbd4ab86bf5e3bd2e42dbe9ce2f1 | [
"MIT"
] | 4 | 2016-03-03T08:58:12.000Z | 2017-09-13T02:30:44.000Z | src/cn/edu/gdut/zaoying/Option/series/gauge/axisLine/lineStyle/ColorArray.java | zaoying/EChartsAnnotation | 4f0e6c972114fbd4ab86bf5e3bd2e42dbe9ce2f1 | [
"MIT"
] | 18 | 2016-05-04T12:55:05.000Z | 2021-05-21T13:55:58.000Z | 32.5 | 67 | 0.836923 | 996,717 | package cn.edu.gdut.zaoying.Option.series.gauge.axisLine.lineStyle;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ColorArray {
} |
9233d3757e92e637856f7ad0e77964cad2fc7cf0 | 700 | java | Java | text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java | keigohtr/apitore-sdk-java | f11263b2d5024796d3748cf7713712be3c0fdd36 | [
"Apache-2.0"
] | 6 | 2017-07-09T13:16:41.000Z | 2020-07-20T02:59:13.000Z | text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java | apitore/apitore-response-parent | f11263b2d5024796d3748cf7713712be3c0fdd36 | [
"Apache-2.0"
] | null | null | null | text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java | apitore/apitore-response-parent | f11263b2d5024796d3748cf7713712be3c0fdd36 | [
"Apache-2.0"
] | 3 | 2017-07-05T14:32:03.000Z | 2018-09-13T08:31:23.000Z | 22.580645 | 70 | 0.795714 | 996,718 | package com.apitore.banana.response.textsimilarity;
import com.apitore.banana.response.BaseResponseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@ApiModel
@Data
@EqualsAndHashCode(callSuper=false)
public class TextSimilarityResponseEntity extends BaseResponseEntity {
/**
*
*/
private static final long serialVersionUID = 8870874086273031574L;
@ApiModelProperty(required=true, value="Text1")
private String text1;
@ApiModelProperty(required=true, value="Text2")
private String text2;
@ApiModelProperty(required=true, value="Similarity")
private double similarity;
}
|
9233d504bbe1815cc166dceb16fcbb559de050f5 | 2,726 | java | Java | thucydides-core/src/main/java/net/thucydides/core/reports/json/jackson/JacksonJSONConverter.java | thucydides-webtests/thucydides | df33ddf05141291da98e56c94237dbca2a3e4caa | [
"Apache-2.0"
] | 52 | 2015-01-03T20:40:54.000Z | 2021-12-27T02:14:24.000Z | thucydides-core/src/main/java/net/thucydides/core/reports/json/jackson/JacksonJSONConverter.java | thucydides-webtests/thucydides | df33ddf05141291da98e56c94237dbca2a3e4caa | [
"Apache-2.0"
] | 16 | 2015-03-04T20:34:50.000Z | 2022-02-01T00:57:58.000Z | thucydides-core/src/main/java/net/thucydides/core/reports/json/jackson/JacksonJSONConverter.java | thucydides-webtests/thucydides | df33ddf05141291da98e56c94237dbca2a3e4caa | [
"Apache-2.0"
] | 35 | 2015-01-12T07:59:00.000Z | 2022-03-12T06:15:13.000Z | 34.506329 | 111 | 0.736244 | 996,719 | package net.thucydides.core.reports.json.jackson;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.inject.Inject;
import net.thucydides.core.ThucydidesSystemProperty;
import net.thucydides.core.model.TestOutcome;
import net.thucydides.core.reports.json.JSONConverter;
import net.thucydides.core.util.EnvironmentVariables;
import javax.validation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Set;
public class JacksonJSONConverter implements JSONConverter {
private final ObjectMapper mapper;
private final ObjectReader reader;
private final ObjectWriter writer;
private final EnvironmentVariables environmentVariables;
private final Validator validator;
@Inject
public JacksonJSONConverter(EnvironmentVariables environmentVariables) {
this.environmentVariables = environmentVariables;
mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.registerModule(new GuavaModule());
mapper.registerModule(new TestOutcomeModule());
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
reader = mapper.reader(TestOutcome.class);
writer = mapper.writerWithType(TestOutcome.class);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
/**
* For testing purposes.
*/
protected ObjectMapper getMapper() {
return mapper;
}
@Override
public TestOutcome fromJson(InputStream inputStream) throws IOException {
TestOutcome outcome = reader.readValue(inputStream);
checkConstraints(outcome);
return outcome;
}
private void checkConstraints(TestOutcome outcome) {
Set<ConstraintViolation<TestOutcome>> violations = validator.validate(outcome);
if (!violations.isEmpty()) {
throw new ValidationException(Arrays.toString(violations.toArray()));
}
}
@Override
public void toJson(TestOutcome testOutcome, OutputStream outputStream) throws IOException {
if (usePrettyPrinting()) {
writer.withDefaultPrettyPrinter().writeValue(outputStream, testOutcome);
} else {
writer.writeValue(outputStream, testOutcome);
}
}
private boolean usePrettyPrinting() {
return environmentVariables.getPropertyAsBoolean(ThucydidesSystemProperty.JSON_PRETTY_PRINTING, false);
}
}
|
9233d5fdc4943827a97581398e14dc7ab8ad874d | 2,686 | java | Java | src/main/fns2.0_xsds/.build/net/opengis/gml/Boolean.java | faa-swim/aixm-5.1 | 561b2479a96c9928722e96411f11a089c0bfe649 | [
"Apache-2.0"
] | null | null | null | src/main/fns2.0_xsds/.build/net/opengis/gml/Boolean.java | faa-swim/aixm-5.1 | 561b2479a96c9928722e96411f11a089c0bfe649 | [
"Apache-2.0"
] | null | null | null | src/main/fns2.0_xsds/.build/net/opengis/gml/Boolean.java | faa-swim/aixm-5.1 | 561b2479a96c9928722e96411f11a089c0bfe649 | [
"Apache-2.0"
] | null | null | null | 25.339623 | 122 | 0.626582 | 996,720 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.01.27 at 07:41:16 AM EST
//
package net.opengis.gml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>boolean">
* <attribute name="nilReason" type="{http://www.opengis.net/gml/3.2}NilReasonType" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public class Boolean {
@XmlValue
protected boolean value;
@XmlAttribute(name = "nilReason")
protected List<String> nilReason;
/**
* Gets the value of the value property.
*
*/
public boolean isValue() {
return value;
}
/**
* Sets the value of the value property.
*
*/
public void setValue(boolean value) {
this.value = value;
}
public boolean isSetValue() {
return true;
}
/**
* Gets the value of the nilReason property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nilReason property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNilReason().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNilReason() {
if (nilReason == null) {
nilReason = new ArrayList<String>();
}
return this.nilReason;
}
public boolean isSetNilReason() {
return ((this.nilReason!= null)&&(!this.nilReason.isEmpty()));
}
public void unsetNilReason() {
this.nilReason = null;
}
}
|
9233d63786c9a9864b53ffc3c5f349190adb9aed | 2,941 | java | Java | tst/rapaio/ml/model/svm/OneClassSvmTest.java | rapaio/rapaio | 9d226ad07eb50f0d77409ba6d1d5e971134ae215 | [
"Apache-2.0"
] | null | null | null | tst/rapaio/ml/model/svm/OneClassSvmTest.java | rapaio/rapaio | 9d226ad07eb50f0d77409ba6d1d5e971134ae215 | [
"Apache-2.0"
] | null | null | null | tst/rapaio/ml/model/svm/OneClassSvmTest.java | rapaio/rapaio | 9d226ad07eb50f0d77409ba6d1d5e971134ae215 | [
"Apache-2.0"
] | null | null | null | 30.957895 | 106 | 0.653519 | 996,721 | package rapaio.ml.model.svm;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static rapaio.graphics.Plotter.*;
import static rapaio.sys.With.color;
import static rapaio.sys.With.fill;
import static rapaio.sys.With.pch;
import java.io.IOException;
import java.util.logging.Level;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import rapaio.core.RandomSource;
import rapaio.core.distributions.Normal;
import rapaio.core.distributions.Uniform;
import rapaio.core.tools.GridData;
import rapaio.data.Frame;
import rapaio.data.SolidFrame;
import rapaio.data.Var;
import rapaio.data.VarDouble;
import rapaio.data.VarInt;
import rapaio.experiment.ml.svm.libsvm.svm_model;
import rapaio.experiment.ml.svm.libsvm.svm_predict;
import rapaio.experiment.ml.svm.libsvm.svm_train;
import rapaio.graphics.opt.Gradient;
import rapaio.graphics.plot.GridLayer;
import rapaio.math.linear.DMatrix;
import rapaio.math.linear.DVector;
import rapaio.ml.common.kernel.RBFKernel;
import rapaio.sys.WS;
import rapaio.sys.With;
import rapaio.util.collection.DoubleArrays;
public class OneClassSvmTest {
private final int N = 2000;
private final int M = N / 10;
private final int LEN = N + M;
private Var x1;
private Var x2;
private Frame df;
private DMatrix xs;
@BeforeEach
void beforeEach() {
WS.initLog(Level.SEVERE);
RandomSource.setSeed(42);
Normal normal1 = Normal.of(0, 2);
Normal normal2 = Normal.of(1, 3);
x1 = VarDouble.from(N, row -> normal1.sampleNext()).name("x1");
x2 = VarDouble.from(N, row -> x1.getDouble(row) * 2 + normal2.sampleNext()).name("x2");
// add some random uniform
Uniform uniform = new Uniform(-10, 10);
for (int i = 0; i < M; i++) {
x1.addDouble(uniform.sampleNext());
x2.addDouble(uniform.sampleNext());
}
df = SolidFrame.byVars(x1, x2);
xs = DMatrix.copy(df);
}
@Test
void testOneClass() throws IOException {
svm_train t = new svm_train();
String[] argv = new String[] {"-s", "2",
"-t", "2",
"-g", "0.01",
"-n", "0.1",
"-b", "0"};
RandomSource.setSeed(42);
svm_model model = t.run(xs, DVector.fill(LEN, 0), argv);
svm_predict.Prediction pred = svm_predict.predict(model, xs, 1);
OneClassSvm ocs = OneClassSvm
.newModel()
.kernel.set(new RBFKernel(0.01))
.nu.set(0.1);
var result = ocs.fit(df, null).predict(df);
assertArrayEquals(DVector.wrap(pred.classes()).apply(v -> v < 0 ? 0 : 1).denseCopy().array(),
DoubleArrays.newFrom(0, pred.classes().length, i -> result.getAssignment().getDouble(i)));
}
}
|
9233d6f1137514dbf727509c49e0606053ffb78e | 538 | java | Java | edu/cmu/hcii/whyline/bytecode/IF_ACMPNE.java | andyjko/whyline | 0d9d4ba97da52143737cb5f2e60f4f8647a3e736 | [
"MIT"
] | 36 | 2016-05-04T17:25:20.000Z | 2019-08-26T03:35:40.000Z | edu/cmu/hcii/whyline/bytecode/IF_ACMPNE.java | vguen/whyline | e3da3d437a1dd246d18ba6d1d4c1fcbddd7514c3 | [
"MIT"
] | null | null | null | edu/cmu/hcii/whyline/bytecode/IF_ACMPNE.java | vguen/whyline | e3da3d437a1dd246d18ba6d1d4c1fcbddd7514c3 | [
"MIT"
] | 9 | 2020-07-01T14:37:14.000Z | 2022-02-14T16:37:13.000Z | 24.454545 | 62 | 0.723048 | 996,722 | package edu.cmu.hcii.whyline.bytecode;
/**
* @author Andrew J. Ko
*
*/
public final class IF_ACMPNE extends CompareReferencesBranch {
public IF_ACMPNE(CodeAttribute method, int offset) {
super(method, offset);
}
public final int getOpcode() { return 166; }
public int byteLength() { return 3; }
public int getNumberOfOperandsConsumed() { return 2; }
public int getNumberOfOperandsProduced() { return 0; }
public int getNumberOfOperandsPeekedAt() { return 0; }
public String getReadableDescription() { return "!="; }
}
|
9233d8af55213ab4596fb8be94a56bde68fc647f | 17,623 | java | Java | temp/src/minecraft/net/minecraft/client/gui/GuiTextField.java | blapplejuice/ByteClient | 5f04232468dfe5b609c043e3d4b094ff667d9c51 | [
"MIT"
] | 1 | 2021-03-24T12:20:04.000Z | 2021-03-24T12:20:04.000Z | temp/src/minecraft/net/minecraft/client/gui/GuiTextField.java | blapplejuice/ByteClient | 5f04232468dfe5b609c043e3d4b094ff667d9c51 | [
"MIT"
] | null | null | null | temp/src/minecraft/net/minecraft/client/gui/GuiTextField.java | blapplejuice/ByteClient | 5f04232468dfe5b609c043e3d4b094ff667d9c51 | [
"MIT"
] | 2 | 2021-03-27T15:43:42.000Z | 2021-03-27T15:50:42.000Z | 33.12594 | 212 | 0.609034 | 996,723 | package net.minecraft.client.gui;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiPageButtonList;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.MathHelper;
public class GuiTextField extends Gui {
private final int field_175208_g;
private final FontRenderer field_146211_a;
public int field_146209_f;
public int field_146210_g;
private final int field_146218_h;
private final int field_146219_i;
private String field_146216_j = "";
private int field_146217_k = 32;
private int field_146214_l;
private boolean field_146215_m = true;
private boolean field_146212_n = true;
private boolean field_146213_o;
private boolean field_146226_p = true;
private int field_146225_q;
private int field_146224_r;
private int field_146223_s;
private int field_146222_t = 14737632;
private int field_146221_u = 7368816;
private boolean field_146220_v = true;
private GuiPageButtonList.GuiResponder field_175210_x;
private Predicate<String> field_175209_y = Predicates.<String>alwaysTrue();
public GuiTextField(int p_i45542_1_, FontRenderer p_i45542_2_, int p_i45542_3_, int p_i45542_4_, int p_i45542_5_, int p_i45542_6_) {
this.field_175208_g = p_i45542_1_;
this.field_146211_a = p_i45542_2_;
this.field_146209_f = p_i45542_3_;
this.field_146210_g = p_i45542_4_;
this.field_146218_h = p_i45542_5_;
this.field_146219_i = p_i45542_6_;
}
public void func_175207_a(GuiPageButtonList.GuiResponder p_175207_1_) {
this.field_175210_x = p_175207_1_;
}
public void func_146178_a() {
++this.field_146214_l;
}
public void func_146180_a(String p_146180_1_) {
if(this.field_175209_y.apply(p_146180_1_)) {
if(p_146180_1_.length() > this.field_146217_k) {
this.field_146216_j = p_146180_1_.substring(0, this.field_146217_k);
} else {
this.field_146216_j = p_146180_1_;
}
this.func_146202_e();
}
}
public String func_146179_b() {
return this.field_146216_j;
}
public String func_146207_c() {
int i = this.field_146224_r < this.field_146223_s?this.field_146224_r:this.field_146223_s;
int j = this.field_146224_r < this.field_146223_s?this.field_146223_s:this.field_146224_r;
return this.field_146216_j.substring(i, j);
}
public void func_175205_a(Predicate<String> p_175205_1_) {
this.field_175209_y = p_175205_1_;
}
public void func_146191_b(String p_146191_1_) {
String s = "";
String s1 = ChatAllowedCharacters.func_71565_a(p_146191_1_);
int i = this.field_146224_r < this.field_146223_s?this.field_146224_r:this.field_146223_s;
int j = this.field_146224_r < this.field_146223_s?this.field_146223_s:this.field_146224_r;
int k = this.field_146217_k - this.field_146216_j.length() - (i - j);
int l = 0;
if(this.field_146216_j.length() > 0) {
s = s + this.field_146216_j.substring(0, i);
}
if(k < s1.length()) {
s = s + s1.substring(0, k);
l = k;
} else {
s = s + s1;
l = s1.length();
}
if(this.field_146216_j.length() > 0 && j < this.field_146216_j.length()) {
s = s + this.field_146216_j.substring(j);
}
if(this.field_175209_y.apply(s)) {
this.field_146216_j = s;
this.func_146182_d(i - this.field_146223_s + l);
if(this.field_175210_x != null) {
this.field_175210_x.func_175319_a(this.field_175208_g, this.field_146216_j);
}
}
}
public void func_146177_a(int p_146177_1_) {
if(this.field_146216_j.length() != 0) {
if(this.field_146223_s != this.field_146224_r) {
this.func_146191_b("");
} else {
this.func_146175_b(this.func_146187_c(p_146177_1_) - this.field_146224_r);
}
}
}
public void func_146175_b(int p_146175_1_) {
if(this.field_146216_j.length() != 0) {
if(this.field_146223_s != this.field_146224_r) {
this.func_146191_b("");
} else {
boolean flag = p_146175_1_ < 0;
int i = flag?this.field_146224_r + p_146175_1_:this.field_146224_r;
int j = flag?this.field_146224_r:this.field_146224_r + p_146175_1_;
String s = "";
if(i >= 0) {
s = this.field_146216_j.substring(0, i);
}
if(j < this.field_146216_j.length()) {
s = s + this.field_146216_j.substring(j);
}
if(this.field_175209_y.apply(s)) {
this.field_146216_j = s;
if(flag) {
this.func_146182_d(p_146175_1_);
}
if(this.field_175210_x != null) {
this.field_175210_x.func_175319_a(this.field_175208_g, this.field_146216_j);
}
}
}
}
}
public int func_175206_d() {
return this.field_175208_g;
}
public int func_146187_c(int p_146187_1_) {
return this.func_146183_a(p_146187_1_, this.func_146198_h());
}
public int func_146183_a(int p_146183_1_, int p_146183_2_) {
return this.func_146197_a(p_146183_1_, p_146183_2_, true);
}
public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_) {
int i = p_146197_2_;
boolean flag = p_146197_1_ < 0;
int j = Math.abs(p_146197_1_);
for(int k = 0; k < j; ++k) {
if(!flag) {
int l = this.field_146216_j.length();
i = this.field_146216_j.indexOf(32, i);
if(i == -1) {
i = l;
} else {
while(p_146197_3_ && i < l && this.field_146216_j.charAt(i) == 32) {
++i;
}
}
} else {
while(p_146197_3_ && i > 0 && this.field_146216_j.charAt(i - 1) == 32) {
--i;
}
while(i > 0 && this.field_146216_j.charAt(i - 1) != 32) {
--i;
}
}
}
return i;
}
public void func_146182_d(int p_146182_1_) {
this.func_146190_e(this.field_146223_s + p_146182_1_);
}
public void func_146190_e(int p_146190_1_) {
this.field_146224_r = p_146190_1_;
int i = this.field_146216_j.length();
this.field_146224_r = MathHelper.func_76125_a(this.field_146224_r, 0, i);
this.func_146199_i(this.field_146224_r);
}
public void func_146196_d() {
this.func_146190_e(0);
}
public void func_146202_e() {
this.func_146190_e(this.field_146216_j.length());
}
public boolean func_146201_a(char p_146201_1_, int p_146201_2_) {
if(!this.field_146213_o) {
return false;
} else if(GuiScreen.func_175278_g(p_146201_2_)) {
this.func_146202_e();
this.func_146199_i(0);
return true;
} else if(GuiScreen.func_175280_f(p_146201_2_)) {
GuiScreen.func_146275_d(this.func_146207_c());
return true;
} else if(GuiScreen.func_175279_e(p_146201_2_)) {
if(this.field_146226_p) {
this.func_146191_b(GuiScreen.func_146277_j());
}
return true;
} else if(GuiScreen.func_175277_d(p_146201_2_)) {
GuiScreen.func_146275_d(this.func_146207_c());
if(this.field_146226_p) {
this.func_146191_b("");
}
return true;
} else {
switch(p_146201_2_) {
case 14:
if(GuiScreen.func_146271_m()) {
if(this.field_146226_p) {
this.func_146177_a(-1);
}
} else if(this.field_146226_p) {
this.func_146175_b(-1);
}
return true;
case 199:
if(GuiScreen.func_146272_n()) {
this.func_146199_i(0);
} else {
this.func_146196_d();
}
return true;
case 203:
if(GuiScreen.func_146272_n()) {
if(GuiScreen.func_146271_m()) {
this.func_146199_i(this.func_146183_a(-1, this.func_146186_n()));
} else {
this.func_146199_i(this.func_146186_n() - 1);
}
} else if(GuiScreen.func_146271_m()) {
this.func_146190_e(this.func_146187_c(-1));
} else {
this.func_146182_d(-1);
}
return true;
case 205:
if(GuiScreen.func_146272_n()) {
if(GuiScreen.func_146271_m()) {
this.func_146199_i(this.func_146183_a(1, this.func_146186_n()));
} else {
this.func_146199_i(this.func_146186_n() + 1);
}
} else if(GuiScreen.func_146271_m()) {
this.func_146190_e(this.func_146187_c(1));
} else {
this.func_146182_d(1);
}
return true;
case 207:
if(GuiScreen.func_146272_n()) {
this.func_146199_i(this.field_146216_j.length());
} else {
this.func_146202_e();
}
return true;
case 211:
if(GuiScreen.func_146271_m()) {
if(this.field_146226_p) {
this.func_146177_a(1);
}
} else if(this.field_146226_p) {
this.func_146175_b(1);
}
return true;
default:
if(ChatAllowedCharacters.func_71566_a(p_146201_1_)) {
if(this.field_146226_p) {
this.func_146191_b(Character.toString(p_146201_1_));
}
return true;
} else {
return false;
}
}
}
}
public void func_146192_a(int p_146192_1_, int p_146192_2_, int p_146192_3_) {
boolean flag = p_146192_1_ >= this.field_146209_f && p_146192_1_ < this.field_146209_f + this.field_146218_h && p_146192_2_ >= this.field_146210_g && p_146192_2_ < this.field_146210_g + this.field_146219_i;
if(this.field_146212_n) {
this.func_146195_b(flag);
}
if(this.field_146213_o && flag && p_146192_3_ == 0) {
int i = p_146192_1_ - this.field_146209_f;
if(this.field_146215_m) {
i -= 4;
}
String s = this.field_146211_a.func_78269_a(this.field_146216_j.substring(this.field_146225_q), this.func_146200_o());
this.func_146190_e(this.field_146211_a.func_78269_a(s, i).length() + this.field_146225_q);
}
}
public void func_146194_f() {
if(this.func_146176_q()) {
if(this.func_146181_i()) {
func_73734_a(this.field_146209_f - 1, this.field_146210_g - 1, this.field_146209_f + this.field_146218_h + 1, this.field_146210_g + this.field_146219_i + 1, -6250336);
func_73734_a(this.field_146209_f, this.field_146210_g, this.field_146209_f + this.field_146218_h, this.field_146210_g + this.field_146219_i, -16777216);
}
int i = this.field_146226_p?this.field_146222_t:this.field_146221_u;
int j = this.field_146224_r - this.field_146225_q;
int k = this.field_146223_s - this.field_146225_q;
String s = this.field_146211_a.func_78269_a(this.field_146216_j.substring(this.field_146225_q), this.func_146200_o());
boolean flag = j >= 0 && j <= s.length();
boolean flag1 = this.field_146213_o && this.field_146214_l / 6 % 2 == 0 && flag;
int l = this.field_146215_m?this.field_146209_f + 4:this.field_146209_f;
int i1 = this.field_146215_m?this.field_146210_g + (this.field_146219_i - 8) / 2:this.field_146210_g;
int j1 = l;
if(k > s.length()) {
k = s.length();
}
if(s.length() > 0) {
String s1 = flag?s.substring(0, j):s;
j1 = this.field_146211_a.func_175063_a(s1, (float)l, (float)i1, i);
}
boolean flag2 = this.field_146224_r < this.field_146216_j.length() || this.field_146216_j.length() >= this.func_146208_g();
int k1 = j1;
if(!flag) {
k1 = j > 0?l + this.field_146218_h:l;
} else if(flag2) {
k1 = j1 - 1;
--j1;
}
if(s.length() > 0 && flag && j < s.length()) {
j1 = this.field_146211_a.func_175063_a(s.substring(j), (float)j1, (float)i1, i);
}
if(flag1) {
if(flag2) {
Gui.func_73734_a(k1, i1 - 1, k1 + 1, i1 + 1 + this.field_146211_a.field_78288_b, -3092272);
} else {
this.field_146211_a.func_175063_a("_", (float)k1, (float)i1, i);
}
}
if(k != j) {
int l1 = l + this.field_146211_a.func_78256_a(s.substring(0, k));
this.func_146188_c(k1, i1 - 1, l1 - 1, i1 + 1 + this.field_146211_a.field_78288_b);
}
}
}
private void func_146188_c(int p_146188_1_, int p_146188_2_, int p_146188_3_, int p_146188_4_) {
if(p_146188_1_ < p_146188_3_) {
int i = p_146188_1_;
p_146188_1_ = p_146188_3_;
p_146188_3_ = i;
}
if(p_146188_2_ < p_146188_4_) {
int j = p_146188_2_;
p_146188_2_ = p_146188_4_;
p_146188_4_ = j;
}
if(p_146188_3_ > this.field_146209_f + this.field_146218_h) {
p_146188_3_ = this.field_146209_f + this.field_146218_h;
}
if(p_146188_1_ > this.field_146209_f + this.field_146218_h) {
p_146188_1_ = this.field_146209_f + this.field_146218_h;
}
Tessellator tessellator = Tessellator.func_178181_a();
WorldRenderer worldrenderer = tessellator.func_178180_c();
GlStateManager.func_179131_c(0.0F, 0.0F, 255.0F, 255.0F);
GlStateManager.func_179090_x();
GlStateManager.func_179115_u();
GlStateManager.func_179116_f(5387);
worldrenderer.func_181668_a(7, DefaultVertexFormats.field_181705_e);
worldrenderer.func_181662_b((double)p_146188_1_, (double)p_146188_4_, 0.0D).func_181675_d();
worldrenderer.func_181662_b((double)p_146188_3_, (double)p_146188_4_, 0.0D).func_181675_d();
worldrenderer.func_181662_b((double)p_146188_3_, (double)p_146188_2_, 0.0D).func_181675_d();
worldrenderer.func_181662_b((double)p_146188_1_, (double)p_146188_2_, 0.0D).func_181675_d();
tessellator.func_78381_a();
GlStateManager.func_179134_v();
GlStateManager.func_179098_w();
}
public void func_146203_f(int p_146203_1_) {
this.field_146217_k = p_146203_1_;
if(this.field_146216_j.length() > p_146203_1_) {
this.field_146216_j = this.field_146216_j.substring(0, p_146203_1_);
}
}
public int func_146208_g() {
return this.field_146217_k;
}
public int func_146198_h() {
return this.field_146224_r;
}
public boolean func_146181_i() {
return this.field_146215_m;
}
public void func_146185_a(boolean p_146185_1_) {
this.field_146215_m = p_146185_1_;
}
public void func_146193_g(int p_146193_1_) {
this.field_146222_t = p_146193_1_;
}
public void func_146204_h(int p_146204_1_) {
this.field_146221_u = p_146204_1_;
}
public void func_146195_b(boolean p_146195_1_) {
if(p_146195_1_ && !this.field_146213_o) {
this.field_146214_l = 0;
}
this.field_146213_o = p_146195_1_;
}
public boolean func_146206_l() {
return this.field_146213_o;
}
public void func_146184_c(boolean p_146184_1_) {
this.field_146226_p = p_146184_1_;
}
public int func_146186_n() {
return this.field_146223_s;
}
public int func_146200_o() {
return this.func_146181_i()?this.field_146218_h - 8:this.field_146218_h;
}
public void func_146199_i(int p_146199_1_) {
int i = this.field_146216_j.length();
if(p_146199_1_ > i) {
p_146199_1_ = i;
}
if(p_146199_1_ < 0) {
p_146199_1_ = 0;
}
this.field_146223_s = p_146199_1_;
if(this.field_146211_a != null) {
if(this.field_146225_q > i) {
this.field_146225_q = i;
}
int j = this.func_146200_o();
String s = this.field_146211_a.func_78269_a(this.field_146216_j.substring(this.field_146225_q), j);
int k = s.length() + this.field_146225_q;
if(p_146199_1_ == this.field_146225_q) {
this.field_146225_q -= this.field_146211_a.func_78262_a(this.field_146216_j, j, true).length();
}
if(p_146199_1_ > k) {
this.field_146225_q += p_146199_1_ - k;
} else if(p_146199_1_ <= this.field_146225_q) {
this.field_146225_q -= this.field_146225_q - p_146199_1_;
}
this.field_146225_q = MathHelper.func_76125_a(this.field_146225_q, 0, i);
}
}
public void func_146205_d(boolean p_146205_1_) {
this.field_146212_n = p_146205_1_;
}
public boolean func_146176_q() {
return this.field_146220_v;
}
public void func_146189_e(boolean p_146189_1_) {
this.field_146220_v = p_146189_1_;
}
}
|
9233d972dbf24ff3e952678f1ea2472f3948a965 | 2,644 | java | Java | app/src/main/java/com/aid/moneymanager/models/DefaultCategory.java | YadgarovIslombek/MoneyManager | 6e9dcc70faba631a070355c2ed5efd44774a24ed | [
"MIT"
] | 2 | 2021-01-21T19:56:02.000Z | 2021-01-27T11:12:03.000Z | app/src/main/java/com/aid/moneymanager/models/DefaultCategory.java | YadgarovIslombek/MoneyManager | 6e9dcc70faba631a070355c2ed5efd44774a24ed | [
"MIT"
] | null | null | null | app/src/main/java/com/aid/moneymanager/models/DefaultCategory.java | YadgarovIslombek/MoneyManager | 6e9dcc70faba631a070355c2ed5efd44774a24ed | [
"MIT"
] | null | null | null | 55.083333 | 126 | 0.659228 | 996,724 | /*
* *
* * Created by Yadgarov Islombek on 2021
* * Copyright (c). All rights reserved.
* * Last modified 20.01.21 0:02
* بِسْمِ ٱللّٰهِ ٱلرَّحْمَٰنِ ٱلرَّحِيم *
*
*/
package com.aid.moneymanager.models;
import android.graphics.Color;
import com.aid.moneymanager.R;
public class DefaultCategory {
private static Category[] categories = new Category[]{
new Category(":others", "Boshqalar", R.drawable.category_default, Color.parseColor("#455a64")),
new Category(":clothing", "Kiyim-kechak", R.drawable.category_clothing, Color.parseColor("#d32f2f")),
new Category(":food", "Oziq=ovqat", R.drawable.category_food, Color.parseColor("#c2185b")),
new Category(":gas_station", "Yoqilg'i (Benzin)", R.drawable.category_gas_station, Color.parseColor("#7b1fa2")),
new Category(":gaz_station", "Yoqilg'i (Metan)", R.drawable.category_gas_station, Color.parseColor("#7b1fa2")),
new Category(":gazPr_station", "Yoqilg'i (Propan)", R.drawable.category_gas_station, Color.parseColor("#7b1fa2")),
new Category(":gaming", "O'yinlar", R.drawable.category_gaming, Color.parseColor("#512da8")),
new Category(":gift", "Sovg'a", R.drawable.category_gift, Color.parseColor("#303f9f")),
new Category(":holidays", "Bayram", R.drawable.category_holidays, Color.parseColor("#1976d2")),
new Category(":home", "Uy", R.drawable.category_home, Color.parseColor("#0288d1")),
new Category(":kids", "Bolalar", R.drawable.category_kids, Color.parseColor("#0097a7")),
new Category(":pharmacy", "Dori-darmon", R.drawable.category_pharmacy, Color.parseColor("#00796b")),
new Category(":repair", "Repair", R.drawable.category_repair, Color.parseColor("#388e3c")),
new Category(":shopping", "Xaridl", R.drawable.category_shopping, Color.parseColor("#689f38")),
new Category(":sport", "Sport", R.drawable.category_sport, Color.parseColor("#afb42b")),
new Category(":transfer", "Qarz", R.drawable.category_transfer, Color.parseColor("#fbc02d")),
new Category(":transport", "Yo'l kira", R.drawable.category_transport, Color.parseColor("#ffa000")),
new Category(":work", "Oylik", R.drawable.category_briefcase, Color.parseColor("#f57c00")),
};
public static Category createDefaultCategoryModel(String visibleName) {
return new Category("default", visibleName, R.drawable.category_default,
Color.parseColor("#26a69a"));
}
public static Category[] getDefaultCategories() {
return categories;
}
} |
9233da49965c75087f577a6b2e0bc579da61c7cb | 7,460 | java | Java | Client/src/main/java/client/controller/multiplayer/MultiplayerMapController.java | Hasatori/Hra | e0b34d06651f7db4a659a89b881b14535ed4e056 | [
"MIT"
] | null | null | null | Client/src/main/java/client/controller/multiplayer/MultiplayerMapController.java | Hasatori/Hra | e0b34d06651f7db4a659a89b881b14535ed4e056 | [
"MIT"
] | null | null | null | Client/src/main/java/client/controller/multiplayer/MultiplayerMapController.java | Hasatori/Hra | e0b34d06651f7db4a659a89b881b14535ed4e056 | [
"MIT"
] | null | null | null | 41.21547 | 204 | 0.591957 | 996,725 | package client.controller.multiplayer;
import client.model.connection.ServerConnection;
import client.model.map.Map;
import client.model.map.MapFactory;
import com.sun.javafx.scene.traversal.Direction;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import client.controller.MapController;
import client.model.protocol.map.MapProtocol;
import client.model.protocol.map.MapProtocolIn;
import client.view.DialogFactory;
import client.view.MapView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Optional;
/**
* Controller class for multiplayer while playing a map.
*/
public class MultiplayerMapController extends ServerController implements MapController {
private final Logger LOGGER = LoggerFactory.getLogger(MultiplayerMapController.class);
private Map map;
private final MapProtocol protocol;
private final String remotePlayerName;
private final int playerNumber, remotePlayerNumber;
private final String mapName;
private MapView view;
private boolean isOwner;
private Thread waitingForCommandsThread;
/**
* @param stage stage
* @param mapName name of the current map
* @param playerNumber number of a player
* @param playerName name of a player
* @param remotePlayerName name of a remote player
* @param remotePlayerNumber number of a remote player
* @param serverConnection server connection
* @param isOwner true=player is owner
*/
public MultiplayerMapController(Stage stage, String mapName, int playerNumber, String playerName, String remotePlayerName, int remotePlayerNumber, ServerConnection serverConnection, boolean isOwner) {
super(stage, serverConnection, playerName);
this.remotePlayerName = remotePlayerName;
this.map = MapFactory.getInstance().getMap(mapName, playerNumber, remotePlayerNumber, playerName, remotePlayerName);
this.isOwner = isOwner;
try {
this.view = new MapView(this, map.getMapParts(), mapName);
} catch (IOException e) {
LOGGER.error("Failed to load MapView", e);
}
this.protocol = new MapProtocol();
this.mapName = mapName;
this.playerNumber = playerNumber;
this.remotePlayerNumber = remotePlayerNumber;
}
@Override
public void loadView() {
stage.setScene(view);
stage.show();
waitForCommands();
}
@Override
public void movePlayer(KeyCode keyCode) {
try {
Direction direction = Direction.valueOf(keyCode.toString());
outgoingMessageProcessor.sendMessage(protocol.send().moving(direction));
map.movePlayer(direction, playerName);
view.reload(map.getMapParts());
if (map.checkWinCondition()) {
outgoingMessageProcessor.sendMessage(protocol.send().won());
}
} catch (IllegalArgumentException e) {
LOGGER.error("Moving player failed", e);
}
}
/**
* Method for sending a win message.
*/
private void won() {
if (isOwner) {
LobbyOwnerController lobbyOwnerController = new LobbyOwnerController(stage, playerName, serverConnection, mapName);
lobbyOwnerController.loadView();
lobbyOwnerController.setMap(mapName);
lobbyOwnerController.setSecondPlayerName(remotePlayerName);
} else {
new LobbySecondPlayerController(stage, remotePlayerName, playerName, mapName,
serverConnection).loadView();
}
}
@Override
public void quitMap() {
outgoingMessageProcessor.sendMessage(protocol.send().quitMap());
}
@Override
public void restartMap() {
outgoingMessageProcessor.sendMessage(protocol.send().restartMap());
}
/**
* Method for waiting for messages.
*/
public void waitForCommands() {
waitingForCommandsThread = new Thread(() -> {
String message = incomingMessageProcessor.getMessage();
while (message != null || !Thread.currentThread().isInterrupted()) {
if (protocol.disconnected(message)) {
disconnected();
break;
}
MapProtocolIn in = protocol.get(message);
if (in.youHaveLost()) {
Platform.runLater(() -> {
won();
DialogFactory.getAlert(Alert.AlertType.INFORMATION, "Game ended", "You have lost").showAndWait();
});
break;
}
if (in.youHaveWon()) {
Platform.runLater(() -> {
won();
DialogFactory.getAlert(Alert.AlertType.INFORMATION, "Game ended", "You have won").showAndWait();
});
break;
}
if (in.moveNexPlayer()) {
map.movePlayer(in.getDirectionToMoveOtherPlayer(), remotePlayerName);
Platform.runLater(() -> view.reload(map.getMapParts()));
}
if (in.restartMapRequest()) {
Platform.runLater(() -> {
Optional<ButtonType> result = DialogFactory.getConfirmDialog("Restarting map",
"Other player wants to restart the map.", "Do you agree?").showAndWait();
if (result.get() == ButtonType.OK) {
outgoingMessageProcessor.sendMessage(protocol.send().agreed());
} else {
outgoingMessageProcessor.sendMessage(protocol.send().disagreed());
}
});
}
if (in.agreed()) {
this.map = MapFactory.getInstance().getMap(mapName, playerNumber, remotePlayerNumber, playerName, remotePlayerName);
Platform.runLater(() -> view.reload(map.getMapParts()));
}
if (in.disagreed()) {
Platform.runLater(() -> DialogFactory.getAlert(Alert.AlertType.INFORMATION, "Restarting map", "Other player refused to restart the map.").showAndWait());
}
if (in.playerHasLeft()) {
Platform.runLater(() -> {
new MultiplayerController(stage, serverConnection, playerName).loadView();
DialogFactory.getAlert(Alert.AlertType.INFORMATION, "Map", "Other player has left").showAndWait();
});
break;
}
if (in.youHaveLeft()) {
Platform.runLater(() -> {
new MultiplayerController(stage, serverConnection, playerName).loadView();
DialogFactory.getAlert(Alert.AlertType.INFORMATION, "Game info", "You have left the game").showAndWait();
});
break;
}
message = incomingMessageProcessor.getMessage();
}
});
waitingForCommandsThread.start();
}
}
|
9233dbb7f1e37af160349b7605710241da83bf96 | 4,661 | java | Java | dl4j-examples/src/main/java/org/deeplearning4j/examples/wip/advanced/modelling/detectgender/PredictGenderTest.java | prashantr36/deeplearning4j-scheduler | 0391a412fcc4623c5336f00add80393c127de461 | [
"Apache-2.0"
] | 1,763 | 2016-08-05T19:47:37.000Z | 2019-09-08T18:31:10.000Z | dl4j-examples/src/main/java/org/deeplearning4j/examples/wip/advanced/modelling/detectgender/PredictGenderTest.java | prashantr36/deeplearning4j-scheduler | 0391a412fcc4623c5336f00add80393c127de461 | [
"Apache-2.0"
] | 494 | 2016-08-06T06:21:27.000Z | 2019-09-09T13:00:12.000Z | dl4j-examples/src/main/java/org/deeplearning4j/examples/wip/advanced/modelling/detectgender/PredictGenderTest.java | AlexRogalskiy/deeplearning4j-examples | 6d65b1ac8f14978e8280849f55214f0d3c0218c3 | [
"Apache-2.0"
] | 1,571 | 2016-08-06T04:04:39.000Z | 2019-09-07T01:49:24.000Z | 34.021898 | 110 | 0.594293 | 996,726 | /*******************************************************************************
*
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.examples.wip.advanced.modelling.detectgender;
/**
* Created by KITS on 9/14/2016.
*/
import org.deeplearning4j.examples.utils.DownloaderUtility;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import static org.deeplearning4j.examples.wip.advanced.modelling.detectgender.GenderRecordReader.nameToBinary;
public class PredictGenderTest implements Runnable {
private int row=0;
private JDialog jd;
private JTextField jtf;
private JLabel jlbl;
private String possibleCharacters;
private JLabel gender;
private String filePath;
private JButton btnNext;
private JLabel genderLabel;
private MultiLayerNetwork model;
public static void main(String[] args) throws Exception
{
PredictGenderTest pgt = new PredictGenderTest();
Thread t = new Thread(pgt);
t.start();
pgt.prepareInterface();
}
public void prepareInterface()
{
this.jd = new JDialog();
this.jd.getContentPane().setLayout(null);
this.jd.setBounds(100,100,300,250);
this.jd.setLocationRelativeTo(null);
this.jd.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.jd.setTitle("Predict Gender By Name");
//jd.add(jp);
this.jlbl = new JLabel();
this.jlbl.setBounds(5,10,100,20);
this.jlbl.setText("Enter Name : ");
this.jd.add(jlbl);
this.jtf = new JTextField();
this.jtf.setBounds(105,10,150,20);
this.jd.add(jtf);
this.genderLabel = new JLabel();
this.genderLabel.setBounds(5,12,70,170);
this.genderLabel.setText("Gender : ");
this.jd.add(genderLabel);
this.gender = new JLabel();
this.gender.setBounds(75,12,75,170);
this.jd.add(gender);
this.btnNext = new JButton();
this.btnNext.setBounds(5,150,150,20);
this.btnNext.setText("Predict");
this.btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (!jtf.getText().isEmpty()) {
String binaryData = nameToBinary(jtf.getText().toLowerCase());
//System.out.println("binaryData : " + binaryData);
String[] arr = binaryData.split(",");
INDArray features = Nd4j.zeros(1, 440);
for (int i = 0; i < arr.length; i++) {
features.putScalar(new int[]{0, i}, Integer.parseInt(arr[i]));
}
INDArray predicted = model.output(features);
System.out.println("output : " + predicted);
if (predicted.getDouble(0) > predicted.getDouble(1))
gender.setText("Female");
else if (predicted.getDouble(0) < predicted.getDouble(1))
gender.setText("Male");
else
gender.setText("Both male and female can have this name");
}
else
gender.setText("Enter name please..");
}
});
this.jd.add(this.btnNext);
this.jd.setVisible(true);
}
public void run()
{
try
{
this.filePath = DownloaderUtility.PREDICTGENDERDATA.Download() + "/Data";
this.model = MultiLayerNetwork.load(new File(this.filePath + "PredictGender.net"), true);
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}
}
|
9233dcd73c9c14d74729d1cbdf953660417726f4 | 1,167 | java | Java | core/src/main/java/org/namstorm/deltaforce/core/DeltaBuilder.java | sunnychanwork/deltaforce | 944139e7c0ee308857bbb51d46d29f32860019a7 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/namstorm/deltaforce/core/DeltaBuilder.java | sunnychanwork/deltaforce | 944139e7c0ee308857bbb51d46d29f32860019a7 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/namstorm/deltaforce/core/DeltaBuilder.java | sunnychanwork/deltaforce | 944139e7c0ee308857bbb51d46d29f32860019a7 | [
"Apache-2.0"
] | null | null | null | 17.681818 | 90 | 0.544987 | 996,727 | package org.namstorm.deltaforce.core;
/**
* Created by maxnam-storm on 9/8/2016.
*
* T is the underlying object this thing knows how to build
*/
public interface DeltaBuilder<T> {
/**
* Sets the "root" op - ie what is happening to the root objects (not just its fields)
*/
DeltaBuilder op(Delta.OP op);
/**
* Will visit deltas
* @param visitor
*/
void visitDeltas(DeltaVisitor visitor);
/**
* Builds a new version
* @return
*/
T build();
/**
* applies deltas to an object to
*
* applies to from object to which to apply this
* @return object that's been applied to
*/
T apply();
/**
* same as apply() but also clear the deltas afterwards
* @return object that's been applied to
*/
T applyAndClearDeltas();
/**
* clears out the deltas
*/
void clearDeltas();
/**
* creates a new object
*
* @see T .build()
* @see T .apply(T)
*
* @return
*/
T create();
T from();
/**
* Starting point for detlas
*
* @return
*/
DeltaBuilder<T> from(T from);
}
|
9233dcdc8b4a26681a5588f8beb1352f0a677c8c | 337 | java | Java | addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadataProvider.java | springdev-projects/spring-roo | 4a2e9f1eb17d4e49ad947503a63afef7d5a37842 | [
"Apache-2.0"
] | 416 | 2015-01-07T10:54:15.000Z | 2021-11-16T21:59:38.000Z | addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadataProvider.java | Huynhhung0/spring-roo | 1e7d745e389a9f6114b1618884e99bddd26251ee | [
"Apache-2.0"
] | 7 | 2015-01-09T12:29:16.000Z | 2016-10-24T06:57:49.000Z | addon-jpa/addon/src/main/java/org/springframework/roo/addon/jpa/addon/entity/factories/JpaEntityFactoryMetadataProvider.java | Huynhhung0/spring-roo | 1e7d745e389a9f6114b1618884e99bddd26251ee | [
"Apache-2.0"
] | 230 | 2015-01-05T05:11:24.000Z | 2021-11-16T21:59:45.000Z | 25.923077 | 91 | 0.807122 | 996,728 | package org.springframework.roo.addon.jpa.addon.entity.factories;
import org.springframework.roo.classpath.itd.ItdTriggerBasedMetadataProvider;
/**
* Provides {@link JpaEntityFactoryMetadata}.
*
* @author Sergio Clares
* @since 2.0
*/
public interface JpaEntityFactoryMetadataProvider extends ItdTriggerBasedMetadataProvider {
}
|
9233ddf6dbce221a9a674c36b7f11372adc7caa9 | 1,095 | java | Java | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/WindowsRegistryException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 90 | 2016-08-09T16:37:44.000Z | 2022-03-30T10:33:17.000Z | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/WindowsRegistryException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 33 | 2016-10-10T17:29:11.000Z | 2022-03-17T07:27:48.000Z | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/WindowsRegistryException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 48 | 2016-08-09T15:55:20.000Z | 2022-03-31T12:21:50.000Z | 33.181818 | 78 | 0.752511 | 996,729 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gigaspaces.internal.io;
import net.jini.space.InternalSpaceException;
@com.gigaspaces.api.InternalApi
public class WindowsRegistryException extends InternalSpaceException {
private static final long serialVersionUID = 9138962846813070482L;
public WindowsRegistryException(String message) {
super(message);
}
public WindowsRegistryException(String message, Throwable cause) {
super(message, cause);
}
}
|
9233de0bf10fdaa642adc5fd1d6afef0861bd0fc | 7,919 | java | Java | app/build/generated/source/r/debug/android/support/compat/R.java | shruti98/TourApp | cf79ab39d70e062b47f15c339ce3b6d0ec151245 | [
"MIT"
] | null | null | null | app/build/generated/source/r/debug/android/support/compat/R.java | shruti98/TourApp | cf79ab39d70e062b47f15c339ce3b6d0ec151245 | [
"MIT"
] | null | null | null | app/build/generated/source/r/debug/android/support/compat/R.java | shruti98/TourApp | cf79ab39d70e062b47f15c339ce3b6d0ec151245 | [
"MIT"
] | null | null | null | 59.097015 | 126 | 0.74719 | 996,730 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.compat;
public final class R {
public static final class attr {
public static final int font = 0x7f020078;
public static final int fontProviderAuthority = 0x7f02007a;
public static final int fontProviderCerts = 0x7f02007b;
public static final int fontProviderFetchStrategy = 0x7f02007c;
public static final int fontProviderFetchTimeout = 0x7f02007d;
public static final int fontProviderPackage = 0x7f02007e;
public static final int fontProviderQuery = 0x7f02007f;
public static final int fontStyle = 0x7f020080;
public static final int fontWeight = 0x7f020081;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f030000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f04003f;
public static final int notification_icon_bg_color = 0x7f040040;
public static final int ripple_material_light = 0x7f04004a;
public static final int secondary_text_default_material_light = 0x7f04004c;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f05004b;
public static final int compat_button_inset_vertical_material = 0x7f05004c;
public static final int compat_button_padding_horizontal_material = 0x7f05004d;
public static final int compat_button_padding_vertical_material = 0x7f05004e;
public static final int compat_control_corner_material = 0x7f05004f;
public static final int notification_action_icon_size = 0x7f050059;
public static final int notification_action_text_size = 0x7f05005a;
public static final int notification_big_circle_margin = 0x7f05005b;
public static final int notification_content_margin_start = 0x7f05005c;
public static final int notification_large_icon_height = 0x7f05005d;
public static final int notification_large_icon_width = 0x7f05005e;
public static final int notification_main_column_padding_top = 0x7f05005f;
public static final int notification_media_narrow_margin = 0x7f050060;
public static final int notification_right_icon_size = 0x7f050061;
public static final int notification_right_side_padding_top = 0x7f050062;
public static final int notification_small_icon_background_padding = 0x7f050063;
public static final int notification_small_icon_size_as_large = 0x7f050064;
public static final int notification_subtext_size = 0x7f050065;
public static final int notification_top_pad = 0x7f050066;
public static final int notification_top_pad_large_text = 0x7f050067;
}
public static final class drawable {
public static final int notification_action_background = 0x7f060063;
public static final int notification_bg = 0x7f060064;
public static final int notification_bg_low = 0x7f060065;
public static final int notification_bg_low_normal = 0x7f060066;
public static final int notification_bg_low_pressed = 0x7f060067;
public static final int notification_bg_normal = 0x7f060068;
public static final int notification_bg_normal_pressed = 0x7f060069;
public static final int notification_icon_background = 0x7f06006a;
public static final int notification_template_icon_bg = 0x7f06006b;
public static final int notification_template_icon_low_bg = 0x7f06006c;
public static final int notification_tile_bg = 0x7f06006d;
public static final int notify_panel_notification_icon_bg = 0x7f06006e;
}
public static final class id {
public static final int action_container = 0x7f07000d;
public static final int action_divider = 0x7f07000f;
public static final int action_image = 0x7f070010;
public static final int action_text = 0x7f070016;
public static final int actions = 0x7f070017;
public static final int async = 0x7f07001d;
public static final int blocking = 0x7f070020;
public static final int chronometer = 0x7f070028;
public static final int forever = 0x7f07003b;
public static final int icon = 0x7f07003f;
public static final int icon_group = 0x7f070040;
public static final int info = 0x7f070043;
public static final int italic = 0x7f070045;
public static final int line1 = 0x7f070047;
public static final int line3 = 0x7f070048;
public static final int normal = 0x7f070056;
public static final int notification_background = 0x7f070057;
public static final int notification_main_column = 0x7f070058;
public static final int notification_main_column_container = 0x7f070059;
public static final int right_icon = 0x7f070068;
public static final int right_side = 0x7f070069;
public static final int tag_transition_group = 0x7f070089;
public static final int text = 0x7f07008a;
public static final int text2 = 0x7f07008b;
public static final int time = 0x7f07008e;
public static final int title = 0x7f07008f;
}
public static final class integer {
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
public static final int notification_action = 0x7f09001c;
public static final int notification_action_tombstone = 0x7f09001d;
public static final int notification_template_custom_big = 0x7f09001e;
public static final int notification_template_icon_group = 0x7f09001f;
public static final int notification_template_part_chronometer = 0x7f090020;
public static final int notification_template_part_time = 0x7f090021;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0b002a;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0c00e7;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00e8;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00e9;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00ea;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00eb;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c0153;
public static final int Widget_Compat_NotificationActionText = 0x7f0c0154;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f02007a, 0x7f02007b, 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f02007f };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f020078, 0x7f020080, 0x7f020081 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
|
9233df09458a83ca4b8bd69a715a3e64d72ca364 | 8,029 | java | Java | src/test/java/io/github/externschool/planner/service/ScheduleEventTypeServiceTest.java | Benkoff/planner | fd52cd623d2016784bdf283abf8485c74d160852 | [
"MIT"
] | null | null | null | src/test/java/io/github/externschool/planner/service/ScheduleEventTypeServiceTest.java | Benkoff/planner | fd52cd623d2016784bdf283abf8485c74d160852 | [
"MIT"
] | null | null | null | src/test/java/io/github/externschool/planner/service/ScheduleEventTypeServiceTest.java | Benkoff/planner | fd52cd623d2016784bdf283abf8485c74d160852 | [
"MIT"
] | null | null | null | 38.78744 | 114 | 0.719517 | 996,731 | package io.github.externschool.planner.service;
import io.github.externschool.planner.entity.Role;
import io.github.externschool.planner.entity.User;
import io.github.externschool.planner.entity.schedule.ScheduleEvent;
import io.github.externschool.planner.entity.schedule.ScheduleEventType;
import io.github.externschool.planner.exceptions.EventTypeCanNotBeDeletedException;
import io.github.externschool.planner.factories.schedule.ScheduleEventTypeFactory;
import io.github.externschool.planner.repository.schedule.ScheduleEventRepository;
import io.github.externschool.planner.repository.schedule.ScheduleEventTypeRepository;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class ScheduleEventTypeServiceTest {
@Mock private ScheduleEventTypeRepository eventTypeRepository;
@Mock private ScheduleEventRepository eventRepository;
private ScheduleEventTypeService eventTypeService;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.eventTypeService = new ScheduleEventTypeServiceImpl(this.eventTypeRepository, this.eventRepository);
}
@Test
public void shouldReturnListOfEventTypes() {
ScheduleEventType oneType = new ScheduleEventType();
oneType.setName("TestEventType");
oneType.setAmountOfParticipants(1);
Mockito.when(eventTypeRepository.findAll())
.thenReturn(Collections.singletonList(oneType));
List<ScheduleEventType> scheduleEventTypes = this.eventTypeService.loadEventTypes();
assertThat(scheduleEventTypes)
.isNotNull()
.containsExactlyInAnyOrder(oneType);
}
@Test
public void shouldReturnOptionalEventType_whenGetEventTypeById() {
Optional<ScheduleEventType> expectedType = Optional.of(new ScheduleEventType("Type", 1));
when(eventTypeRepository.findById(1L))
.thenReturn(expectedType);
Optional<ScheduleEventType> actualType = eventTypeService.getEventTypeById(1L);
assertThat(actualType)
.isNotNull()
.isEqualTo(expectedType);
}
@Test
public void shouldReturnEventType_whenSaveEventType() {
ScheduleEventType expectedType = new ScheduleEventType("Type", 1);
when(eventTypeRepository.save(expectedType))
.thenReturn(expectedType);
when(eventTypeRepository.findByName(expectedType.getName()))
.thenReturn(null);
ScheduleEventType actualType = eventTypeService.saveEventType(expectedType);
assertThat(actualType)
.isNotNull()
.isEqualTo(expectedType);
}
@Test
public void shouldReturnUpdatedEventType_whenSaveUpdateEventType() {
Role role = new Role();
ScheduleEventType expectedType = new ScheduleEventType("Type", 99);
expectedType.setId(1L);
expectedType.addOwner(role);
when(eventTypeRepository.save(expectedType))
.thenReturn(expectedType);
ScheduleEventType actualType = eventTypeService.saveEventType(expectedType);
assertThat(actualType)
.isNotNull()
.isEqualToComparingFieldByFieldRecursively(expectedType);
System.out.println(expectedType);
}
@Test
public void shouldInvokeOnce_whenDeleteEventType() {
ScheduleEventType expectedType = new ScheduleEventType("Type", 1);
eventTypeService.deleteEventType(expectedType);
verify(eventTypeRepository, times(1)).delete(expectedType);
}
@Test(expected = EventTypeCanNotBeDeletedException.class)
public void shouldThrowException_whenDeletedEventTypeInUse() {
ScheduleEventType expectedType = new ScheduleEventType("Type", 1);
when(eventRepository.findAllByType(expectedType))
.thenReturn(Collections.singletonList(new ScheduleEvent()));
eventTypeService.deleteEventType(expectedType);
verify(eventTypeRepository, times(0)).delete(expectedType);
}
@Test
public void shouldReturnList_whenLoadEventTypes() {
ScheduleEventType eventType = ScheduleEventTypeFactory.createScheduleEventType();
when(this.eventTypeRepository.findAll()).thenReturn(Collections.singletonList(eventType));
List<ScheduleEventType> scheduleEventTypes = this.eventTypeService.loadEventTypes();
assertThat(scheduleEventTypes)
.isNotNull()
.containsExactlyInAnyOrder(eventType);
}
@Test
public void shouldReturnSortedList_whenGetAllEventTypesSorted() {
ScheduleEventType eventTypeOne = new ScheduleEventType("One", 1);
ScheduleEventType eventTypeTwo = new ScheduleEventType("Two", 2);
ScheduleEventType eventTypeOneAndTwo = new ScheduleEventType("OneAndTwo", 10);
when(eventTypeRepository.findAll())
.thenReturn(Arrays.asList(eventTypeTwo, eventTypeOne, eventTypeOneAndTwo));
List<ScheduleEventType> actualEvents = eventTypeService.getAllEventTypesSorted();
assertThat(actualEvents)
.isNotEmpty()
.containsExactly(eventTypeOne, eventTypeOneAndTwo, eventTypeTwo);
}
@Test
public void shouldReturnListsByRoles_whenGetAllEventTypesByUserRoles() {
Role roleOne = new Role("One");
Role roleTwo = new Role("Two");
User userOne = new User();
userOne.addRole(roleOne);
User userTwo = new User();
userTwo.addRole(roleTwo);
User userOneAndTwo = new User();
userOneAndTwo.addRole(roleOne);
userOneAndTwo.addRole(roleTwo);
ScheduleEventType eventTypeOne = new ScheduleEventType("One", 1);
eventTypeOne.addOwner(roleOne);
ScheduleEventType eventTypeTwo = new ScheduleEventType("Two", 2);
eventTypeTwo.addOwner(roleTwo);
ScheduleEventType eventTypeOneAndTwo = new ScheduleEventType("OneAndTwo", 10);
eventTypeOneAndTwo.addOwner(roleOne);
eventTypeOneAndTwo.addOwner(roleTwo);
when(eventTypeRepository.findAll())
.thenReturn(Arrays.asList(eventTypeOne, eventTypeTwo, eventTypeOneAndTwo));
List<ScheduleEventType> eventTypesOne = eventTypeService.getAllEventTypesByUserRoles(userOne);
List<ScheduleEventType> eventTypesTwo = eventTypeService.getAllEventTypesByUserRoles(userTwo);
List<ScheduleEventType> eventTypesOneAndTwo = eventTypeService.getAllEventTypesByUserRoles(userOneAndTwo);
List<ScheduleEventType> eventTypesZero = eventTypeService.getAllEventTypesByUserRoles(new User());
assertThat(eventTypesOne)
.isNotEmpty()
.containsExactlyInAnyOrder(eventTypeOne, eventTypeOneAndTwo)
.doesNotContain(eventTypeTwo);
assertThat(eventTypesTwo)
.isNotEmpty()
.containsExactlyInAnyOrder(eventTypeTwo, eventTypeOneAndTwo)
.doesNotContain(eventTypeOne);
assertThat(eventTypesOneAndTwo)
.isNotEmpty()
.containsExactlyInAnyOrder(eventTypeOne, eventTypeTwo, eventTypeOneAndTwo);
assertThat(eventTypesZero)
.isEmpty();
}
}
|
9233e0e67f95f1087419872152d083d0400f8885 | 344 | java | Java | jtransc-gen-common-tests/src/jtransc/jtransc/js/CustomJsRunTest.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 625 | 2016-02-08T21:20:19.000Z | 2022-03-28T13:03:16.000Z | jtransc-gen-common-tests/src/jtransc/jtransc/js/CustomJsRunTest.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 257 | 2016-02-10T13:33:14.000Z | 2021-09-13T12:12:30.000Z | jtransc-gen-common-tests/src/jtransc/jtransc/js/CustomJsRunTest.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 78 | 2016-02-24T14:11:08.000Z | 2021-08-13T12:47:00.000Z | 24.571429 | 91 | 0.688953 | 996,732 | package jtransc.jtransc.js;
import com.jtransc.annotation.JTranscRunCommand;
@JTranscRunCommand(target = "js", value = { "node", "{{ outputFile }}", "hello", "world" })
public class CustomJsRunTest {
static public void main(String[] args) {
System.out.println(args.length);
for (String arg : args) {
System.out.println(arg);
}
}
}
|
9233e3ce0810c77b7329da545ab8032d449ec53e | 1,341 | java | Java | demo/src/main/java/com/example/demo/controller/Project_controller.java | mybanking/database_SelectClassSystem | 357f29866759416b0b3ddb75a0763f882ab370e7 | [
"Apache-2.0"
] | null | null | null | demo/src/main/java/com/example/demo/controller/Project_controller.java | mybanking/database_SelectClassSystem | 357f29866759416b0b3ddb75a0763f882ab370e7 | [
"Apache-2.0"
] | null | null | null | demo/src/main/java/com/example/demo/controller/Project_controller.java | mybanking/database_SelectClassSystem | 357f29866759416b0b3ddb75a0763f882ab370e7 | [
"Apache-2.0"
] | null | null | null | 38.314286 | 217 | 0.781506 | 996,733 | package com.example.demo.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.Take;
import com.example.demo.mapper.Take_map;
import com.example.demo.service.Classroom_service;
import com.example.demo.service.Project_service;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class Project_controller {
@Autowired
Project_service service;
@RequestMapping("/create_project")//可以的(成功)
public JSONObject load_classroom(@Param("projectId") String projectId,@Param("projectName") String projectName,@Param("type") String type,@Param("teacherId") String teacherId,@Param("studentNum") long studentNum){
return service.create_project(projectId,projectName,type,teacherId,studentNum);
}
@RequestMapping("/personal_project")//测试(成功) 可能目前还没有该数据
public JSONObject load_classroom(@Param("stuId") String stuId){
return service.personal_project(stuId);
}
@RequestMapping("/all_the_project")
public JSONObject load_classroom(){
return service.all_the_project();
}
}
|
9233e5001582981b91fd2857d06d4a23ef4567dd | 326 | java | Java | src/com/taotao/mybatis/mapper2/SysUserMapper.java | tangbojian/generatorSqlmapCustom | 5d14f5399cb8d859a1b95ae4fa238f78078b7383 | [
"MIT"
] | null | null | null | src/com/taotao/mybatis/mapper2/SysUserMapper.java | tangbojian/generatorSqlmapCustom | 5d14f5399cb8d859a1b95ae4fa238f78078b7383 | [
"MIT"
] | null | null | null | src/com/taotao/mybatis/mapper2/SysUserMapper.java | tangbojian/generatorSqlmapCustom | 5d14f5399cb8d859a1b95ae4fa238f78078b7383 | [
"MIT"
] | null | null | null | 20.375 | 43 | 0.751534 | 996,734 | package com.taotao.mybatis.mapper2;
import com.taotao.mybatis.model4.SysUser;
import java.util.List;
public interface SysUserMapper {
int deleteByPrimaryKey(Long id);
int insert(SysUser record);
SysUser selectByPrimaryKey(Long id);
List<SysUser> selectAll();
int updateByPrimaryKey(SysUser record);
} |
9233e5a166dbf984b00dba616e2e7d9bd0a21cfa | 770 | java | Java | data/train/java/a411cb2569d68c0124a692800379346acde2c3a2RepositoryChangeEvent.java | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/java/a411cb2569d68c0124a692800379346acde2c3a2RepositoryChangeEvent.java | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/java/a411cb2569d68c0124a692800379346acde2c3a2RepositoryChangeEvent.java | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | 16.73913 | 55 | 0.715584 | 996,735 | package org.middleheaven.domain.repository;
public class RepositoryChangeEvent<E> {
private Repository<E> repository;
private E instance;
private boolean removed;
private boolean added;
private boolean updated;
public RepositoryChangeEvent(Repository<E> repository,
E instance, boolean removed, boolean added,
boolean updated) {
super();
this.repository = repository;
this.instance = instance;
this.removed = removed;
this.added = added;
this.updated = updated;
}
public Repository<E> getRepository() {
return repository;
}
public E getInstance() {
return instance;
}
public boolean isRemoved() {
return removed;
}
public boolean isAdded() {
return added;
}
public boolean isUpdated() {
return updated;
}
}
|
9233e5ae56ad3bd931d823bd1c79729c04b34dc4 | 314 | java | Java | governator-core/src/main/java/com/netflix/governator/internal/GovernatorFeatureSet.java | zmyer/governator | d90ae018cb9f2497911e1c08f46b0d96fd7b4200 | [
"Apache-2.0"
] | 704 | 2015-01-04T07:58:34.000Z | 2022-03-27T11:50:29.000Z | governator-core/src/main/java/com/netflix/governator/internal/GovernatorFeatureSet.java | zmyer/governator | d90ae018cb9f2497911e1c08f46b0d96fd7b4200 | [
"Apache-2.0"
] | 93 | 2015-01-15T01:29:03.000Z | 2021-04-10T00:14:43.000Z | governator-core/src/main/java/com/netflix/governator/internal/GovernatorFeatureSet.java | zmyer/governator | d90ae018cb9f2497911e1c08f46b0d96fd7b4200 | [
"Apache-2.0"
] | 148 | 2015-01-15T01:10:12.000Z | 2022-02-25T06:50:52.000Z | 22.428571 | 73 | 0.713376 | 996,736 | package com.netflix.governator.internal;
import com.netflix.governator.GovernatorFeature;
/**
* Container of Governator features.
*/
public interface GovernatorFeatureSet {
/**
* @return Get the value of the feature or the default if none is set
*/
<T> T get(GovernatorFeature<T> feature);
}
|
9233e5b6695161aee0f8bad1c25c51438f655603 | 416 | java | Java | processor/src/test/fixtures/input/com/example/post_mount_or_update/PublicAccessViaInterfacePostMountOrUpdateModel.java | lolaalamal/react4j | 80a74bfad0e0a8ceb85107ede5d76ca022f248b3 | [
"Apache-2.0"
] | 27 | 2017-11-16T08:43:10.000Z | 2022-02-24T08:44:02.000Z | processor/src/test/fixtures/input/com/example/post_mount_or_update/PublicAccessViaInterfacePostMountOrUpdateModel.java | lolaalamal/react4j | 80a74bfad0e0a8ceb85107ede5d76ca022f248b3 | [
"Apache-2.0"
] | 80 | 2018-02-05T22:15:30.000Z | 2022-02-11T01:59:33.000Z | processor/src/test/fixtures/input/com/example/post_mount_or_update/PublicAccessViaInterfacePostMountOrUpdateModel.java | lolaalamal/react4j | 80a74bfad0e0a8ceb85107ede5d76ca022f248b3 | [
"Apache-2.0"
] | null | null | null | 18.086957 | 61 | 0.798077 | 996,737 | package com.example.post_mount_or_update;
import react4j.ReactNode;
import react4j.annotations.PostMountOrUpdate;
import react4j.annotations.Render;
import react4j.annotations.View;
@View
abstract class PublicAccessViaInterfacePostMountOrUpdateModel
implements PostMountOrUpdateInterface
{
@PostMountOrUpdate
public void postMountOrUpdate()
{
}
@Render
ReactNode render()
{
return null;
}
}
|
9233e5ce5c690c447be7cde203afdc785688aab5 | 432 | java | Java | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/ImmediateMenuActivity.java | yls871435707/CateMenu | 077d55ccb6aa6ebcf72c5d3fadbcebc34ebda9b6 | [
"Apache-2.0"
] | null | null | null | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/ImmediateMenuActivity.java | yls871435707/CateMenu | 077d55ccb6aa6ebcf72c5d3fadbcebc34ebda9b6 | [
"Apache-2.0"
] | null | null | null | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/ImmediateMenuActivity.java | yls871435707/CateMenu | 077d55ccb6aa6ebcf72c5d3fadbcebc34ebda9b6 | [
"Apache-2.0"
] | null | null | null | 24 | 57 | 0.75463 | 996,738 | package com.example.administrator.catemenu.activity;
import android.app.Activity;
import android.os.Bundle;
import com.example.administrator.catemenu.R;
/**
* Created by abc on 2016/11/11.
*/
public class ImmediateMenuActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_immediate_menu);
}
}
|
9233e5ddb46b20047cd35797b9e9b6636cd775a7 | 3,508 | java | Java | src/main/java/netQuant/display/SamplePanel.java | proteomicsyates/RadialTopologyViewer | ca296c1bdfed76716e2976dfaf2180997e8b52d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/netQuant/display/SamplePanel.java | proteomicsyates/RadialTopologyViewer | ca296c1bdfed76716e2976dfaf2180997e8b52d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/netQuant/display/SamplePanel.java | proteomicsyates/RadialTopologyViewer | ca296c1bdfed76716e2976dfaf2180997e8b52d1 | [
"Apache-2.0"
] | null | null | null | 29.982906 | 86 | 0.616306 | 996,739 | // Medusa is a graph viewer which allows interactive editing of networks
// (edges and nodes) and also connects to databases.
//
// Copyright (C) 2006 Sean Hooper
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330,
// Boston, MA 02111-1307 USA
/*
* SamplePanel.java
*
* Created on den 24 september 2006, 20:32
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package netQuant.display;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import netQuant.NetQuantSettings;
import netQuant.graph.Edge;
import netQuant.graph.Node;
/**
*
* @author sean
*/
public class SamplePanel extends BasicGraphPanel{
/**
* Creates a new instance of SamplePanel
*/
public SamplePanel(NetQuantSettings ms) {
super(ms);
}
public void paintEdge(Graphics2D g, Edge e){
g.setPaint(basicEdgeColor);
paintPathWithConfLabel(g,e);
//super.paintEdge(g,e);
}
public void paintPathWithConfLabel(Graphics2D g2d, Edge e){
// get the values
Node from =graph.getNode(e.getFromName());
Node to = graph.getNode(e.n2);
int x1 = (int)from.getX();
int y1 = (int)from.getY();
int x2 = (int)to.getX();
int y2 = (int)to.getY();
// show conf as string
float conf=e.getConf();
String conf_string=Float.toString(conf);
int lastIndex=conf_string.length();
int last=Math.min(lastIndex,3);
conf_string=conf_string.substring(0,last);
// just draw the line
g2d.drawLine(x1,y1,x2,y2);
// on half points, add conf label
// provide the dimensions in each direction,
// i.e from halfx-width to halfx+width
int width=11;
int height=6;
int halfx=(int)(x1+x2)/2;
int halfy=(int)(y1+y2)/2;
g2d.setColor(Color.YELLOW.brighter());
g2d.fillRect(halfx-width,halfy-height,width*2,height*2);
g2d.setColor(Color.BLACK);
g2d.drawRect(halfx-width,halfy-height,width*2,height*2);
g2d.setColor(Color.BLACK);
g2d.drawString(conf_string,halfx-width+1,halfy+height-1);
}
// public void paintNode(Graphics2D g, Node n){
//
// g.setPaint(n.getColor());
// int x=(int) n.getX() - correct;
// int y=(int) n.getY() - correct;
//
// Shape shape = medusa.display.PaintTools.getShape(n.getShape(),x,y,nodeSize);
// g.fill(shape);
// g.setPaint(Color.black);
// if (n.isFixed())
// g.setPaint(Color.yellow);
// g.draw(shape);
// g.setPaint(fontColor);
// g.setFont(nodeFont);
// if (label)
// g.drawString(n.getLabel(),x-2,y-2);
// }
}
|
9233e60fc35b4b3739aa4152383bc641b505a939 | 1,476 | java | Java | Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/EmptyCompositeException.java | bdcht/ghidra | 9e732318148cd11edeb4862afd23d56418551812 | [
"Apache-2.0"
] | 17 | 2022-01-15T03:52:37.000Z | 2022-03-30T18:12:17.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/EmptyCompositeException.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 9 | 2022-01-15T03:58:02.000Z | 2022-02-21T10:22:49.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/util/datatype/EmptyCompositeException.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 3 | 2019-12-02T13:36:50.000Z | 2019-12-04T05:40:12.000Z | 28.384615 | 75 | 0.691734 | 996,740 | /* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.app.util.datatype;
import ghidra.program.model.data.Composite;
import ghidra.util.exception.UsrException;
/**
* Exception thrown if the composite data type is empty.
* Typically this will be thrown if the user tries to save or apply a
* composite with no components.
*/
public class EmptyCompositeException extends UsrException {
/**
* Constructor.
*/
public EmptyCompositeException() {
super("Data type is empty.");
}
/**
* Constructor
* @param composite the structure data type that is empty.
*/
public EmptyCompositeException(Composite composite) {
super(composite.getDisplayName() + " is empty.");
}
/**
* Constructor
* @param message detailed message explaining exception
*/
public EmptyCompositeException(String message) {
super(message);
}
}
|
9233e69fd680f6ca90cf772e65f41b16d3400f55 | 17,657 | java | Java | deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/VariationalAutoencoderParamInitializer.java | firasdib/deeplearning4j | ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4 | [
"Apache-2.0"
] | 2 | 2020-10-07T18:23:06.000Z | 2021-06-13T16:17:28.000Z | deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/VariationalAutoencoderParamInitializer.java | firasdib/deeplearning4j | ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4 | [
"Apache-2.0"
] | null | null | null | deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/VariationalAutoencoderParamInitializer.java | firasdib/deeplearning4j | ecfd11e4c6e72361a913821ce38b7a7b01c9b9f4 | [
"Apache-2.0"
] | null | null | null | 43.705446 | 127 | 0.631364 | 996,741 | package org.deeplearning4j.nn.params;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.distribution.Distributions;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.deeplearning4j.nn.conf.layers.variational.VariationalAutoencoder;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.rng.distribution.Distribution;
import org.nd4j.linalg.indexing.NDArrayIndex;
import java.util.*;
/**
* Parameter initializer for the Variational Autoencoder model.
*
* See: Kingma & Welling, 2013: Auto-Encoding Variational Bayes - https://arxiv.org/abs/1312.6114
*
* @author Alex Black
*/
public class VariationalAutoencoderParamInitializer extends DefaultParamInitializer {
private static final VariationalAutoencoderParamInitializer INSTANCE = new VariationalAutoencoderParamInitializer();
public static VariationalAutoencoderParamInitializer getInstance() {
return INSTANCE;
}
public static final String WEIGHT_KEY_SUFFIX = "W";
public static final String BIAS_KEY_SUFFIX = "b";
public static final String PZX_PREFIX = "pZX";
public static final String PZX_MEAN_PREFIX = PZX_PREFIX + "Mean";
public static final String PZX_LOGSTD2_PREFIX = PZX_PREFIX + "LogStd2";
public static final String ENCODER_PREFIX = "e";
public static final String DECODER_PREFIX = "d";
/** Key for weight parameters connecting the last encoder layer and the mean values for p(z|data) */
public static final String PZX_MEAN_W = "pZXMean" + WEIGHT_KEY_SUFFIX;
/** Key for bias parameters for the mean values for p(z|data) */
public static final String PZX_MEAN_B = "pZXMean" + BIAS_KEY_SUFFIX;
/** Key for weight parameters connecting the last encoder layer and the log(sigma^2) values for p(z|data) */
public static final String PZX_LOGSTD2_W = PZX_LOGSTD2_PREFIX + WEIGHT_KEY_SUFFIX;
/** Key for bias parameters for log(sigma^2) in p(z|data) */
public static final String PZX_LOGSTD2_B = PZX_LOGSTD2_PREFIX + BIAS_KEY_SUFFIX;
public static final String PXZ_PREFIX = "pXZ";
/** Key for weight parameters connecting the last decoder layer and p(data|z) (according to whatever
* {@link org.deeplearning4j.nn.conf.layers.variational.ReconstructionDistribution} is set for the VAE) */
public static final String PXZ_W = PXZ_PREFIX + WEIGHT_KEY_SUFFIX;
/** Key for bias parameters connecting the last decoder layer and p(data|z) (according to whatever
* {@link org.deeplearning4j.nn.conf.layers.variational.ReconstructionDistribution} is set for the VAE) */
public static final String PXZ_B = PXZ_PREFIX + BIAS_KEY_SUFFIX;
@Override
public int numParams(NeuralNetConfiguration conf) {
VariationalAutoencoder layer = (VariationalAutoencoder) conf.getLayer();
int nIn = layer.getNIn();
int nOut = layer.getNOut();
int[] encoderLayerSizes = layer.getEncoderLayerSizes();
int[] decoderLayerSizes = layer.getDecoderLayerSizes();
int paramCount = 0;
for (int i = 0; i < encoderLayerSizes.length; i++) {
int encoderLayerIn;
if (i == 0) {
encoderLayerIn = nIn;
} else {
encoderLayerIn = encoderLayerSizes[i - 1];
}
paramCount += (encoderLayerIn + 1) * encoderLayerSizes[i]; //weights + bias
}
//Between the last encoder layer and the parameters for p(z|x):
int lastEncLayerSize = encoderLayerSizes[encoderLayerSizes.length - 1];
paramCount += (lastEncLayerSize + 1) * 2 * nOut; //Mean and variance parameters used in unsupervised training
//Decoder:
for (int i = 0; i < decoderLayerSizes.length; i++) {
int decoderLayerNIn;
if (i == 0) {
decoderLayerNIn = nOut;
} else {
decoderLayerNIn = decoderLayerSizes[i - 1];
}
paramCount += (decoderLayerNIn + 1) * decoderLayerSizes[i];
}
//Between last decoder layer and parameters for p(x|z):
int nDistributionParams = layer.getOutputDistribution().distributionInputSize(nIn);
int lastDecLayerSize = decoderLayerSizes[decoderLayerSizes.length - 1];
paramCount += (lastDecLayerSize + 1) * nDistributionParams;
return paramCount;
}
@Override
public List<String> paramKeys(Layer l) {
VariationalAutoencoder layer = (VariationalAutoencoder) l;
int[] encoderLayerSizes = layer.getEncoderLayerSizes();
int[] decoderLayerSizes = layer.getDecoderLayerSizes();
List<String> p = new ArrayList<>();
int soFar = 0;
for (int i = 0; i < encoderLayerSizes.length; i++) {
String sW = "e" + i + WEIGHT_KEY_SUFFIX;
String sB = "e" + i + BIAS_KEY_SUFFIX;
p.add(sW);
p.add(sB);
}
//Last encoder layer -> p(z|x)
p.add(PZX_MEAN_W);
p.add(PZX_MEAN_B);
//Pretrain params
p.add(PZX_LOGSTD2_W);
p.add(PZX_LOGSTD2_B);
for (int i = 0; i < decoderLayerSizes.length; i++) {
String sW = "d" + i + WEIGHT_KEY_SUFFIX;
String sB = "d" + i + BIAS_KEY_SUFFIX;
p.add(sW);
p.add(sB);
}
//Finally, p(x|z):
p.add(PXZ_W);
p.add(PXZ_B);
return p;
}
@Override
public List<String> weightKeys(Layer layer) {
List<String> out = new ArrayList<>();
for(String s : paramKeys(layer)){
if(isWeightParam(s)){
out.add(s);
}
}
return out;
}
@Override
public List<String> biasKeys(Layer layer) {
List<String> out = new ArrayList<>();
for(String s : paramKeys(layer)){
if(isBiasParam(s)){
out.add(s);
}
}
return out;
}
@Override
public boolean isWeightParam(String key) {
return key.endsWith(WEIGHT_KEY_SUFFIX);
}
@Override
public boolean isBiasParam(String key) {
return key.endsWith(BIAS_KEY_SUFFIX);
}
@Override
public Map<String, INDArray> init(NeuralNetConfiguration conf, INDArray paramsView, boolean initializeParams) {
if (paramsView.length() != numParams(conf)) {
throw new IllegalArgumentException("Incorrect paramsView length: Expected length " + numParams(conf)
+ ", got length " + paramsView.length());
}
Map<String, INDArray> ret = new LinkedHashMap<>();
VariationalAutoencoder layer = (VariationalAutoencoder) conf.getLayer();
int nIn = layer.getNIn();
int nOut = layer.getNOut();
int[] encoderLayerSizes = layer.getEncoderLayerSizes();
int[] decoderLayerSizes = layer.getDecoderLayerSizes();
WeightInit weightInit = layer.getWeightInit();
Distribution dist = Distributions.createDistribution(layer.getDist());
int soFar = 0;
for (int i = 0; i < encoderLayerSizes.length; i++) {
int encoderLayerNIn;
if (i == 0) {
encoderLayerNIn = nIn;
} else {
encoderLayerNIn = encoderLayerSizes[i - 1];
}
int weightParamCount = encoderLayerNIn * encoderLayerSizes[i];
INDArray weightView = paramsView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + weightParamCount));
soFar += weightParamCount;
INDArray biasView = paramsView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + encoderLayerSizes[i]));
soFar += encoderLayerSizes[i];
INDArray layerWeights = createWeightMatrix(encoderLayerNIn, encoderLayerSizes[i], weightInit, dist,
weightView, initializeParams);
INDArray layerBiases = createBias(encoderLayerSizes[i], 0.0, biasView, initializeParams); //TODO don't hardcode 0
String sW = "e" + i + WEIGHT_KEY_SUFFIX;
String sB = "e" + i + BIAS_KEY_SUFFIX;
ret.put(sW, layerWeights);
ret.put(sB, layerBiases);
conf.addVariable(sW);
conf.addVariable(sB);
}
//Last encoder layer -> p(z|x)
int nWeightsPzx = encoderLayerSizes[encoderLayerSizes.length - 1] * nOut;
INDArray pzxWeightsMean =
paramsView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nWeightsPzx));
soFar += nWeightsPzx;
INDArray pzxBiasMean = paramsView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nOut));
soFar += nOut;
INDArray pzxWeightsMeanReshaped = createWeightMatrix(encoderLayerSizes[encoderLayerSizes.length - 1], nOut,
weightInit, dist, pzxWeightsMean, initializeParams);
INDArray pzxBiasMeanReshaped = createBias(nOut, 0.0, pzxBiasMean, initializeParams); //TODO don't hardcode 0
ret.put(PZX_MEAN_W, pzxWeightsMeanReshaped);
ret.put(PZX_MEAN_B, pzxBiasMeanReshaped);
conf.addVariable(PZX_MEAN_W);
conf.addVariable(PZX_MEAN_B);
//Pretrain params
INDArray pzxWeightsLogStdev2 =
paramsView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nWeightsPzx));
soFar += nWeightsPzx;
INDArray pzxBiasLogStdev2 = paramsView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nOut));
soFar += nOut;
INDArray pzxWeightsLogStdev2Reshaped = createWeightMatrix(encoderLayerSizes[encoderLayerSizes.length - 1], nOut,
weightInit, dist, pzxWeightsLogStdev2, initializeParams);
INDArray pzxBiasLogStdev2Reshaped = createBias(nOut, 0.0, pzxBiasLogStdev2, initializeParams); //TODO don't hardcode 0
ret.put(PZX_LOGSTD2_W, pzxWeightsLogStdev2Reshaped);
ret.put(PZX_LOGSTD2_B, pzxBiasLogStdev2Reshaped);
conf.addVariable(PZX_LOGSTD2_W);
conf.addVariable(PZX_LOGSTD2_B);
for (int i = 0; i < decoderLayerSizes.length; i++) {
int decoderLayerNIn;
if (i == 0) {
decoderLayerNIn = nOut;
} else {
decoderLayerNIn = decoderLayerSizes[i - 1];
}
int weightParamCount = decoderLayerNIn * decoderLayerSizes[i];
INDArray weightView = paramsView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + weightParamCount));
soFar += weightParamCount;
INDArray biasView = paramsView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + decoderLayerSizes[i]));
soFar += decoderLayerSizes[i];
INDArray layerWeights = createWeightMatrix(decoderLayerNIn, decoderLayerSizes[i], weightInit, dist,
weightView, initializeParams);
INDArray layerBiases = createBias(decoderLayerSizes[i], 0.0, biasView, initializeParams); //TODO don't hardcode 0
String sW = "d" + i + WEIGHT_KEY_SUFFIX;
String sB = "d" + i + BIAS_KEY_SUFFIX;
ret.put(sW, layerWeights);
ret.put(sB, layerBiases);
conf.addVariable(sW);
conf.addVariable(sB);
}
//Finally, p(x|z):
int nDistributionParams = layer.getOutputDistribution().distributionInputSize(nIn);
int pxzWeightCount = decoderLayerSizes[decoderLayerSizes.length - 1] * nDistributionParams;
INDArray pxzWeightView =
paramsView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + pxzWeightCount));
soFar += pxzWeightCount;
INDArray pxzBiasView = paramsView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + nDistributionParams));
INDArray pxzWeightsReshaped = createWeightMatrix(decoderLayerSizes[decoderLayerSizes.length - 1],
nDistributionParams, weightInit, dist, pxzWeightView, initializeParams);
INDArray pxzBiasReshaped = createBias(nDistributionParams, 0.0, pxzBiasView, initializeParams); //TODO don't hardcode 0
ret.put(PXZ_W, pxzWeightsReshaped);
ret.put(PXZ_B, pxzBiasReshaped);
conf.addVariable(PXZ_W);
conf.addVariable(PXZ_B);
return ret;
}
@Override
public Map<String, INDArray> getGradientsFromFlattened(NeuralNetConfiguration conf, INDArray gradientView) {
Map<String, INDArray> ret = new LinkedHashMap<>();
VariationalAutoencoder layer = (VariationalAutoencoder) conf.getLayer();
int nIn = layer.getNIn();
int nOut = layer.getNOut();
int[] encoderLayerSizes = layer.getEncoderLayerSizes();
int[] decoderLayerSizes = layer.getDecoderLayerSizes();
int soFar = 0;
for (int i = 0; i < encoderLayerSizes.length; i++) {
int encoderLayerNIn;
if (i == 0) {
encoderLayerNIn = nIn;
} else {
encoderLayerNIn = encoderLayerSizes[i - 1];
}
int weightParamCount = encoderLayerNIn * encoderLayerSizes[i];
INDArray weightGradView = gradientView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + weightParamCount));
soFar += weightParamCount;
INDArray biasGradView = gradientView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + encoderLayerSizes[i]));
soFar += encoderLayerSizes[i];
INDArray layerWeights = weightGradView.reshape('f', encoderLayerNIn, encoderLayerSizes[i]);
INDArray layerBiases = biasGradView; //Aready correct shape (row vector)
ret.put("e" + i + WEIGHT_KEY_SUFFIX, layerWeights);
ret.put("e" + i + BIAS_KEY_SUFFIX, layerBiases);
}
//Last encoder layer -> p(z|x)
int nWeightsPzx = encoderLayerSizes[encoderLayerSizes.length - 1] * nOut;
INDArray pzxWeightsMean =
gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nWeightsPzx));
soFar += nWeightsPzx;
INDArray pzxBiasMean = gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nOut));
soFar += nOut;
INDArray pzxWeightGradMeanReshaped =
pzxWeightsMean.reshape('f', encoderLayerSizes[encoderLayerSizes.length - 1], nOut);
ret.put(PZX_MEAN_W, pzxWeightGradMeanReshaped);
ret.put(PZX_MEAN_B, pzxBiasMean);
////////////////////////////////////////////////////////
INDArray pzxWeightsLogStdev2 =
gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nWeightsPzx));
soFar += nWeightsPzx;
INDArray pzxBiasLogStdev2 = gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + nOut));
soFar += nOut;
INDArray pzxWeightsLogStdev2Reshaped = createWeightMatrix(encoderLayerSizes[encoderLayerSizes.length - 1], nOut,
null, null, pzxWeightsLogStdev2, false); //TODO
ret.put(PZX_LOGSTD2_W, pzxWeightsLogStdev2Reshaped);
ret.put(PZX_LOGSTD2_B, pzxBiasLogStdev2);
for (int i = 0; i < decoderLayerSizes.length; i++) {
int decoderLayerNIn;
if (i == 0) {
decoderLayerNIn = nOut;
} else {
decoderLayerNIn = decoderLayerSizes[i - 1];
}
int weightParamCount = decoderLayerNIn * decoderLayerSizes[i];
INDArray weightView = gradientView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + weightParamCount));
soFar += weightParamCount;
INDArray biasView = gradientView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + decoderLayerSizes[i]));
soFar += decoderLayerSizes[i];
INDArray layerWeights =
createWeightMatrix(decoderLayerNIn, decoderLayerSizes[i], null, null, weightView, false);
INDArray layerBiases = createBias(decoderLayerSizes[i], 0.0, biasView, false); //TODO don't hardcode 0
String sW = "d" + i + WEIGHT_KEY_SUFFIX;
String sB = "d" + i + BIAS_KEY_SUFFIX;
ret.put(sW, layerWeights);
ret.put(sB, layerBiases);
}
//Finally, p(x|z):
int nDistributionParams = layer.getOutputDistribution().distributionInputSize(nIn);
int pxzWeightCount = decoderLayerSizes[decoderLayerSizes.length - 1] * nDistributionParams;
INDArray pxzWeightView =
gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(soFar, soFar + pxzWeightCount));
soFar += pxzWeightCount;
INDArray pxzBiasView = gradientView.get(NDArrayIndex.point(0),
NDArrayIndex.interval(soFar, soFar + nDistributionParams));
INDArray pxzWeightsReshaped = createWeightMatrix(decoderLayerSizes[decoderLayerSizes.length - 1],
nDistributionParams, null, null, pxzWeightView, false);
INDArray pxzBiasReshaped = createBias(nDistributionParams, 0.0, pxzBiasView, false);
ret.put(PXZ_W, pxzWeightsReshaped);
ret.put(PXZ_B, pxzBiasReshaped);
return ret;
}
}
|
9233e7277fbe9297028bd5f237f07cd5c73fa6a1 | 256 | java | Java | LabAssignmentSolutions/Assignment06/src/lesson6/labs/Author.java | avendesta/mpp-corazza | b07d13c2a8df834f5fc9f9e6da2cf28ac737ec68 | [
"MIT"
] | null | null | null | LabAssignmentSolutions/Assignment06/src/lesson6/labs/Author.java | avendesta/mpp-corazza | b07d13c2a8df834f5fc9f9e6da2cf28ac737ec68 | [
"MIT"
] | null | null | null | LabAssignmentSolutions/Assignment06/src/lesson6/labs/Author.java | avendesta/mpp-corazza | b07d13c2a8df834f5fc9f9e6da2cf28ac737ec68 | [
"MIT"
] | null | null | null | 19.692308 | 71 | 0.746094 | 996,742 | package lesson6.labs;
public class Author {
String name;
Qualification qualification;
Integer age;
public Author(String name, Qualification qualification, Integer age) {
this.name = name;
this.qualification = qualification;
this.age = age;
}
}
|
9233e77acd766be1bdebe09ec3682e983fddca71 | 273 | java | Java | src/main/java/com/hb0730/feishu/robot/core/model/post/tag/PostTag.java | hb0730/java-feishu-robot | 428609e1f4db5f63ef47a0b48441ca2d5e3a4783 | [
"MIT"
] | null | null | null | src/main/java/com/hb0730/feishu/robot/core/model/post/tag/PostTag.java | hb0730/java-feishu-robot | 428609e1f4db5f63ef47a0b48441ca2d5e3a4783 | [
"MIT"
] | null | null | null | src/main/java/com/hb0730/feishu/robot/core/model/post/tag/PostTag.java | hb0730/java-feishu-robot | 428609e1f4db5f63ef47a0b48441ca2d5e3a4783 | [
"MIT"
] | null | null | null | 19.5 | 56 | 0.739927 | 996,743 | package com.hb0730.feishu.robot.core.model.post.tag;
import com.hb0730.feishu.robot.core.model.Tag;
import com.hb0730.feishu.robot.core.model.IMessage;
/**
* tag
*
* @author bing_huang
* @date 2021/12/16
*/
public abstract class PostTag implements IMessage, Tag {
}
|
9233e8f00e05a7f79d9f50f94994c1959a2e7e11 | 14,255 | java | Java | app/src/main/java/com/hrrock/snapbook/adapters/ProfileListViewAdapter.java | hiteshgarg002/Snapbook | 2684d9e602d3e3556643ec6108c209e863dc17dd | [
"MIT"
] | 7 | 2018-07-29T09:01:18.000Z | 2021-10-06T03:52:39.000Z | app/src/main/java/com/hrrock/snapbook/adapters/ProfileListViewAdapter.java | hiteshgarg002/Snapbook | 2684d9e602d3e3556643ec6108c209e863dc17dd | [
"MIT"
] | null | null | null | app/src/main/java/com/hrrock/snapbook/adapters/ProfileListViewAdapter.java | hiteshgarg002/Snapbook | 2684d9e602d3e3556643ec6108c209e863dc17dd | [
"MIT"
] | 1 | 2019-12-13T11:06:04.000Z | 2019-12-13T11:06:04.000Z | 52.601476 | 207 | 0.66973 | 996,744 | package com.hrrock.snapbook.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hrrock.snapbook.R;
import com.hrrock.snapbook.models.ProfilePostsListViewModel;
import com.hrrock.snapbook.networks.VolleyConnect;
import com.hrrock.snapbook.utils.GlideApp;
import com.hrrock.snapbook.utils.SquareImageView;
import org.json.JSONObject;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileListViewAdapter extends RecyclerView.Adapter<ProfileListViewAdapter.MyHolder> {
private List<ProfilePostsListViewModel> list = Collections.emptyList();
private LayoutInflater inflater;
private Context ctx;
private StringRequest stringRequest;
private JsonArrayRequest jsonArrayRequest;
private RequestQueue requestQueue;
private static final String POLL_UP = "up";
private static final String POLL_DOWN = "down";
private static final String USER_PREFERENCES = "userinfo";
private SharedPreferences preferences;
private View.OnClickListener clickListener;
public ProfileListViewAdapter(Context context, List<ProfilePostsListViewModel> list, View.OnClickListener onClickListener) {
inflater = LayoutInflater.from(context);
this.list = list;
this.ctx = context;
this.requestQueue = VolleyConnect.getInstance().getRequestQueue();
this.preferences = context.getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE);
this.clickListener = onClickListener;
}
class MyHolder extends RecyclerView.ViewHolder {
SquareImageView photo;
CircleImageView dp;
TextView caption, username, date, voteUp, voteDown;
ImageView thumbsUp, thumbsDown, comment;
LinearLayout votingLinear, captionLinear;
MyHolder(View itemView) {
super(itemView);
dp = itemView.findViewById(R.id.dpOnProfilePostsListView);
photo = itemView.findViewById(R.id.postOnProfilePostsListView);
username = itemView.findViewById(R.id.userNameOnProfilePostsListView);
thumbsUp = itemView.findViewById(R.id.thumb_upOnProfilePostsListView);
thumbsDown = itemView.findViewById(R.id.thumb_downOnProfilePostsListView);
comment = itemView.findViewById(R.id.comments_OnProfilePostsListView);
votingLinear = itemView.findViewById(R.id.linearVotes);
captionLinear = itemView.findViewById(R.id.linearCaptionOnProfilePostsListView);
date = itemView.findViewById(R.id.dateOnProfilePostsListView);
caption = itemView.findViewById(R.id.captionOnProfilePostsListView);
voteUp = itemView.findViewById(R.id.upVotesOnProfilePostsListView);
voteDown = itemView.findViewById(R.id.downVotesOnProfilePostsListView);
}
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.layout_profile_posts_list_view_row, parent, false);
return new MyHolder(v);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
ProfilePostsListViewModel listViewModel = list.get(position);
if (listViewModel != null) {
GlideApp.with(ctx.getApplicationContext())
.load(ctx.getResources().getString(R.string.BASE_URL_PROFILE_PIC) + listViewModel.getUserName() + ".jpg")
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.dp);
Glide.with(ctx.getApplicationContext()).load(ctx.getString(R.string.BASE_URL_PHOTOS_PROFILE)
+ listViewModel.getPhoto()).into(holder.photo);
holder.username.setText(listViewModel.getUserName());
holder.date.setText(listViewModel.getDate());
if (!Objects.equals(listViewModel.getVoteUp(), "0")
|| !Objects.equals(listViewModel.getVoteDown(), "0")
|| !Objects.equals(listViewModel.getVoteUp(), "0")
&& !Objects.equals(listViewModel.getVoteDown(), "0")) {
holder.voteUp.setText(listViewModel.getVoteUp() + " " + ctx.getString(R.string.vote_up));
holder.voteDown.setText(listViewModel.getVoteDown() + " " + ctx.getString(R.string.vote_down));
holder.votingLinear.setVisibility(View.VISIBLE);
} else {
holder.votingLinear.setVisibility(View.GONE);
}
if (Objects.equals(listViewModel.getPollStatus(), "up")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
} else if (Objects.equals(listViewModel.getPollStatus(), "down")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
} else {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
}
if (!Objects.equals(listViewModel.getCaption(), "")) {
holder.caption.setText(listViewModel.getCaption());
holder.captionLinear.setVisibility(View.VISIBLE);
} else {
holder.captionLinear.setVisibility(View.GONE);
}
holder.thumbsUp.setOnClickListener(view -> {
if (Objects.equals(listViewModel.getPollStatus(), "up")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
} else if (Objects.equals(listViewModel.getPollStatus(), "down")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
} else {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
}
setPollOnAction(listViewModel, POLL_UP, holder.thumbsUp, holder.thumbsDown, holder.voteUp, holder.voteDown, holder.votingLinear);
});
holder.thumbsDown.setOnClickListener(view -> {
if (Objects.equals(listViewModel.getPollStatus(), "up")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
} else if (Objects.equals(listViewModel.getPollStatus(), "down")) {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
} else {
holder.thumbsUp.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
holder.thumbsDown.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
}
setPollOnAction(listViewModel, POLL_DOWN, holder.thumbsDown, holder.thumbsUp, holder.voteUp, holder.voteDown, holder.votingLinear);
});
setClickListeners(holder.comment);
setTagsToViews(holder.comment, position);
}
}
private void setPollOnAction(ProfilePostsListViewModel listViewModel, String polltype, ImageView poll, ImageView otherPoll, TextView voteUp, TextView voteDown, LinearLayout votingLinear) {
final String url = "http://" + ctx.getString(R.string.ip) + "/Snapbook/index.php/PollingController/setPoll?" +
"postid=" + listViewModel.getPostId() + "&username=" + preferences.getString("username", "") + "&polltype=" + polltype;
stringRequest = new StringRequest(url, response -> {
updateVoteCount(listViewModel, voteUp, voteDown, votingLinear);
if (Objects.equals(response, "up") || Objects.equals(response, "down")) {
poll.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.link_blue, null)));
otherPoll.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
if (!Objects.equals(listViewModel.getUserName(), preferences.getString("username", ""))) {
sendVoteNotification(listViewModel.getToken());
makeNotification(listViewModel.getUserName(), listViewModel.getPostId());
}
} else {
poll.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
otherPoll.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null)));
if (!Objects.equals(listViewModel.getUserName(), preferences.getString("username", ""))) {
removeNotification(listViewModel.getUserName(), listViewModel.getPostId());
}
}
}, error -> poll.setImageTintList(ColorStateList.valueOf(ctx.getResources().getColor(R.color.white, null))));
requestQueue.add(stringRequest);
}
@SuppressLint("SetTextI18n")
private void updateVoteCount(ProfilePostsListViewModel listViewModel, TextView voteUp, TextView voteDown, LinearLayout votingLinear) {
final String url = "http://" + ctx.getString(R.string.ip) + "/Snapbook/index.php/PollingController/updateVoteCount?" +
"postid=" + listViewModel.getPostId();
//Toast.makeText(ctx,newsFeedModel.getPostId()+"",Toast.LENGTH_SHORT).show();
jsonArrayRequest = new JsonArrayRequest(url, response -> {
JSONObject jsonObject = response.optJSONObject(0);
if (!Objects.equals(jsonObject.optString("voteup"), "0") || !Objects.equals(jsonObject.optString("votedown"), "0")
|| !Objects.equals(jsonObject.optString("voteup"), "0") && !Objects.equals(jsonObject.optString("votedown"), "0")) {
voteUp.setText(jsonObject.optString("voteup") + " " + ctx.getString(R.string.vote_up));
voteDown.setText(jsonObject.optString("votedown") + " " + ctx.getString(R.string.vote_down));
votingLinear.setVisibility(View.VISIBLE);
} else {
votingLinear.setVisibility(View.GONE);
}
// Toast.makeText(ctx,jsonObject.optString("voteup")+"-"+jsonObject.optString("votedown"),Toast.LENGTH_SHORT).show();
}, error -> {
});
requestQueue.add(jsonArrayRequest);
}
private void sendVoteNotification(String token) {
final String url = "http://" + ctx.getString(R.string.ip) + "/Firebase/notification.php?" +
"regId=" + token + "&title=Snapbook&message=" + preferences.getString("username", "") + " voted on your post!&push_type=individual";
stringRequest = new StringRequest(url, response -> {
}, error -> {
});
requestQueue.add(stringRequest);
}
private void makeNotification(String username, String postId) {
final String url = "http://" + ctx.getString(R.string.ip) + "/Snapbook/index.php/NotificationController/makeYouNotification?" +
"uname=" + preferences.getString("username", "") + "&username=" + username + "¬ification=" + preferences.getString("username", "") + " voted on your post!&postid=" + postId + "&type=vote";
stringRequest = new StringRequest(url, response -> {
}, error -> {
});
requestQueue.add(stringRequest);
}
private void removeNotification(String username, String postId) {
final String url = "http://" + ctx.getString(R.string.ip) + "/Snapbook/index.php/NotificationController/removeYouNotification?" +
"uname=" + preferences.getString("username", "") + "&username=" + username + "¬ification=" + preferences.getString("username", "") + " voted on your post!&postid=" + postId + "&type=vote";
stringRequest = new StringRequest(url, response -> {
}, error -> {
});
requestQueue.add(stringRequest);
}
@Override
public int getItemCount() {
return list.size();
}
@Override
public long getItemId(int position) {
return 0;
}
private void setClickListeners(View view) {
view.setOnClickListener(clickListener);
}
private void setTagsToViews(View view, int position) {
view.setTag(R.id.key_position, position);
}
}
|
9233e924fc4f4e4695444c2223e2b2a1ffc0c61b | 1,246 | java | Java | src/test/java/nablarch/fw/messaging/CustomDefaultSyncMessageConvertor.java | nablarch/nablarch-fw-messaging | e5e527ab6f7e23b90725c4aabf77667c08305a76 | [
"Apache-2.0"
] | null | null | null | src/test/java/nablarch/fw/messaging/CustomDefaultSyncMessageConvertor.java | nablarch/nablarch-fw-messaging | e5e527ab6f7e23b90725c4aabf77667c08305a76 | [
"Apache-2.0"
] | 4 | 2016-11-18T01:09:18.000Z | 2021-03-31T10:16:17.000Z | src/test/java/nablarch/fw/messaging/CustomDefaultSyncMessageConvertor.java | nablarch/nablarch-fw-messaging | e5e527ab6f7e23b90725c4aabf77667c08305a76 | [
"Apache-2.0"
] | null | null | null | 30.390244 | 124 | 0.662921 | 996,745 | package nablarch.fw.messaging;
/**
* フレームワーク制御ヘッダをカスタマイズするクラス。
* @author Kiyohito Itoh
*/
public class CustomDefaultSyncMessageConvertor extends SyncMessageConvertor {
/**
* {@inheritDoc}
* <pre>
* 下記のフレームワーク制御ヘッダをヘッダMapに追加後にスーパークラスの処理を呼び出す。
*
* test: "test"
* </pre>
*/
@Override
protected SendingMessage createSendingMessage(
MessageSenderSettings settings, SyncMessage requestMessage) {
requestMessage.getHeaderRecord().put("test", "test");
return super.createSendingMessage(settings, requestMessage);
}
/**
* {@inheritDoc}
* <pre>
* スーパークラスの処理を呼び出し取得した応答電文に対して、
* 下記のフレームワーク制御ヘッダをヘッダMapに追加する。
*
* receivedDate: "20111020"
* </pre>
*/
@Override
public SyncMessage convertOnReceiveSync(MessageSenderSettings settings, SyncMessage requestMessage,
SendingMessage sendingMessage, ReceivedMessage receivedMessage) {
SyncMessage responseMessage = super.convertOnReceiveSync(settings, requestMessage, sendingMessage, receivedMessage);
responseMessage.getHeaderRecord().put("receivedDate", "20111020");
return responseMessage;
}
}
|
9233e94055dee050ac0d1d3b3e23804ea08a30c9 | 377 | java | Java | service/src/main/java/uk/gov/hmcts/reform/fpl/service/children/validation/user/AdminUserValidator.java | damongreen123/fpl-ccd-configuration | 722138312853574b35285e24fdc15dc30b3cb73e | [
"MIT"
] | 6 | 2019-08-16T12:58:12.000Z | 2021-09-27T09:04:36.000Z | service/src/main/java/uk/gov/hmcts/reform/fpl/service/children/validation/user/AdminUserValidator.java | damongreen123/fpl-ccd-configuration | 722138312853574b35285e24fdc15dc30b3cb73e | [
"MIT"
] | 2,084 | 2018-10-02T16:15:34.000Z | 2022-03-31T18:04:14.000Z | service/src/main/java/uk/gov/hmcts/reform/fpl/service/children/validation/user/AdminUserValidator.java | damongreen123/fpl-ccd-configuration | 722138312853574b35285e24fdc15dc30b3cb73e | [
"MIT"
] | 7 | 2018-11-29T18:05:37.000Z | 2022-01-25T13:57:25.000Z | 25.133333 | 72 | 0.734748 | 996,746 | package uk.gov.hmcts.reform.fpl.service.children.validation.user;
import uk.gov.hmcts.reform.fpl.service.UserService;
public abstract class AdminUserValidator extends UserSpecificValidator {
public AdminUserValidator(UserService user) {
super(user);
}
@Override
protected final boolean acceptsUser() {
return user.isHmctsAdminUser();
}
}
|
9233e9c1595ea430a8d7969b4f60275fe36e74f3 | 2,775 | java | Java | engine/src/main/java/io/camunda/zeebe/process/test/engine/RecordStreamSourceImpl.java | camunda-cloud/zeebe-process-test | 41ba1b6be84de43d102099e2722cd4c0b77e25a9 | [
"Apache-2.0"
] | 9 | 2021-12-10T09:35:27.000Z | 2022-02-23T14:07:27.000Z | engine/src/main/java/io/camunda/zeebe/process/test/engine/RecordStreamSourceImpl.java | camunda-cloud/zeebe-process-test | 41ba1b6be84de43d102099e2722cd4c0b77e25a9 | [
"Apache-2.0"
] | 127 | 2021-12-10T15:26:51.000Z | 2022-03-10T13:45:23.000Z | engine/src/main/java/io/camunda/zeebe/process/test/engine/RecordStreamSourceImpl.java | camunda-cloud/camunda-cloud-testing | 6095324478d24d8a2d707aad567be891965254b1 | [
"Apache-2.0"
] | 2 | 2021-12-20T04:56:32.000Z | 2022-02-10T22:11:56.000Z | 33.035714 | 95 | 0.725405 | 996,747 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.process.test.engine;
import io.camunda.zeebe.engine.processing.streamprocessor.TypedEventRegistry;
import io.camunda.zeebe.logstreams.log.LogStreamReader;
import io.camunda.zeebe.logstreams.log.LoggedEvent;
import io.camunda.zeebe.process.test.api.RecordStreamSource;
import io.camunda.zeebe.protocol.impl.record.CopiedRecord;
import io.camunda.zeebe.protocol.impl.record.RecordMetadata;
import io.camunda.zeebe.protocol.impl.record.UnifiedRecordValue;
import io.camunda.zeebe.protocol.record.Record;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class RecordStreamSourceImpl implements RecordStreamSource {
private final LogStreamReader logStreamReader;
private final int partitionId;
private final List<Record<?>> records = new ArrayList<>();
private volatile long lastPosition = -1L;
public RecordStreamSourceImpl(final LogStreamReader logStreamReader, final int partitionId) {
this.logStreamReader = logStreamReader;
this.partitionId = partitionId;
}
@Override
public Iterable<Record<?>> getRecords() {
updateWithNewRecords();
return Collections.unmodifiableList(records);
}
private void updateWithNewRecords() {
synchronized (logStreamReader) {
if (lastPosition < 0) {
logStreamReader.seekToFirstEvent();
} else {
logStreamReader.seekToNextEvent(lastPosition);
}
while (logStreamReader.hasNext()) {
final LoggedEvent event = logStreamReader.next();
final CopiedRecord<UnifiedRecordValue> record = mapToRecord(event);
records.add(record);
lastPosition = event.getPosition();
}
}
}
private CopiedRecord<UnifiedRecordValue> mapToRecord(final LoggedEvent event) {
final RecordMetadata metadata = new RecordMetadata();
event.readMetadata(metadata);
final UnifiedRecordValue value;
try {
value =
TypedEventRegistry.EVENT_REGISTRY
.get(metadata.getValueType())
.getDeclaredConstructor()
.newInstance();
} catch (final Exception e) {
throw new RuntimeException(e);
}
event.readValue(value);
return new CopiedRecord<>(
value,
metadata,
event.getKey(),
partitionId,
event.getPosition(),
event.getSourceEventPosition(),
event.getTimestamp());
}
}
|
9233ebd583f3cc3d881f292c34d92984c6d17491 | 1,810 | java | Java | data/src/main/java/com/example/labratour/data/VectorSimilarityCalculator.java | Arye182/LabraTour | 29339a2c4da4db799ab87006794695e11ea36c9b | [
"MIT"
] | null | null | null | data/src/main/java/com/example/labratour/data/VectorSimilarityCalculator.java | Arye182/LabraTour | 29339a2c4da4db799ab87006794695e11ea36c9b | [
"MIT"
] | null | null | null | data/src/main/java/com/example/labratour/data/VectorSimilarityCalculator.java | Arye182/LabraTour | 29339a2c4da4db799ab87006794695e11ea36c9b | [
"MIT"
] | null | null | null | 24.794521 | 119 | 0.628177 | 996,748 | package com.example.labratour.data;
import java.util.Vector;
public class VectorSimilarityCalculator extends SimilarityCalculator <Vector<Double>> implements Calculator {
private int vectorOneEuclideanNorm;
private int vectortwoEuclideanNorm;
public VectorSimilarityCalculator(Vector<Double> vectorOne, Vector<Double> vectorTwo) {
super(vectorOne, vectorTwo);
}
public double calcSim() throws Exception{
try{
result = cosineSim(this.objectOne, this.objectTwo,vectorOneEuclideanNorm, vectortwoEuclideanNorm);
if (result==-1){
throw new Exception("error in calculation");
}
return result;
}catch (Exception exception){
throw exception;
}
}
@Override
public void prepareInput() {
this.vectorOneEuclideanNorm = euclideanNorm((Vector<Double>)this.objectOne);
this.vectortwoEuclideanNorm = euclideanNorm((Vector<Double>)this.objectTwo);
}
private int euclideanNorm(Vector<Double> vector) {
// TODO: 20/09/2021 a
return 1;
}
public static Double dotProduct(Vector<Double> v1, Vector<Double> v2) {
double sum = 0;
if (verifySize(v1, v2)) {
for (int i = 0; i < v1.size(); i++) {
sum += (v1.get(i) * v2.get(i));
}
}
return sum;
}
public static boolean verifySize(Vector<Double> v1, Vector<Double> v2) {
if (v1.size()==v2.size()){
return true;
}
return false;
}
public static double cosineSim(Vector<Double> v1, Vector<Double> v2, double euclideanNorm1, double euclideanNorm2){
if ((euclideanNorm1!=0)&&(euclideanNorm2!=0)){
return (dotProduct(v1, v2) / (euclideanNorm1 * euclideanNorm2));
}
return -1;
}
}
|
9233ebec94f4b3231c04a41ab94c7532acd7d9b1 | 5,961 | java | Java | src/main/java/com/hfut/laboratory/controller/ProjectController.java | yzx66-net/accout_mange | 53ecff652e7a4648f222ac735516c085d8e778a6 | [
"Apache-2.0"
] | 60 | 2020-07-28T15:03:53.000Z | 2021-02-16T05:57:03.000Z | src/main/java/com/hfut/laboratory/controller/ProjectController.java | shidahai/accout_mange | 362d56ac13add72fdbe6f4028f0ac39101961ead | [
"Apache-2.0"
] | 1 | 2020-11-15T09:20:36.000Z | 2020-11-15T09:49:39.000Z | src/main/java/com/hfut/laboratory/controller/ProjectController.java | shidahai/accout_mange | 362d56ac13add72fdbe6f4028f0ac39101961ead | [
"Apache-2.0"
] | 33 | 2020-07-29T04:35:39.000Z | 2021-02-02T07:14:00.000Z | 39.217105 | 138 | 0.695018 | 996,749 | package com.hfut.laboratory.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfut.laboratory.enums.ReturnCode;
import com.hfut.laboratory.pojo.Project;
import com.hfut.laboratory.pojo.RecordBusiness;
import com.hfut.laboratory.service.ProjectService;
import com.hfut.laboratory.service.RecordBusinessService;
import com.hfut.laboratory.util.QueryWapperUtils;
import com.hfut.laboratory.vo.ApiResponse;
import com.hfut.laboratory.vo.PageResult;
import com.hfut.laboratory.vo.project.ProjectSimple;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author yzx
* @since 2019-11-06
*/
@RestController
@RequestMapping("project")
@Api(tags = "收费项目的相关接口")
@Slf4j
public class ProjectController {
@Autowired
private ProjectService projectService;
@Autowired
private RecordBusinessService recordBusinessService;
@GetMapping("/list")
@ApiOperation("获取收费项目列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "current",value = "当前页"),
@ApiImplicitParam(name = "size",value = "需要数据的条数limit")
})
@Cacheable(value = "getProjectList",keyGenerator="simpleKeyGenerator")
public ApiResponse getProjectList(@RequestParam(required = false,defaultValue = "1") Integer current,
@RequestParam(required = false,defaultValue = "20") Integer size){
Page<Project> page=new Page<>(current,size);
IPage<Project> projectIPage = projectService.page(page, null);
return ApiResponse.ok(new PageResult<>(projectIPage.getRecords(),projectIPage.getTotal(),projectIPage.getSize()));
}
@GetMapping("/simple/list")
@ApiOperation("获取没有冻结的收费项目列表id、name列表")
@Cacheable(value = "getProjectSimpleList",keyGenerator="simpleKeyGenerator")
public ApiResponse getProjectSimpleList(){
List<ProjectSimple> res=new ArrayList<>();
projectService.list(QueryWapperUtils.getInWapper("status",1))
.forEach(project -> res.add(new ProjectSimple(((Project)project).getId(),((Project)project).getName())));
return ApiResponse.ok(res);
}
@GetMapping("/simple/all/list")
@ApiOperation("获取所有收费项目列表")
@Cacheable(value = "getAllProjectSimpleList",keyGenerator="simpleKeyGenerator")
public ApiResponse getAllProjectSimpleList(){
List<ProjectSimple> res=new ArrayList<>();
projectService.list(null).forEach(project -> res.add(new ProjectSimple(((Project)project).getId(),((Project)project).getName())));
return ApiResponse.ok(res);
}
@GetMapping("/{id}")
@ApiOperation("通过id获取收费项目")
@ApiImplicitParam(name = "id",value = "收费项目的id")
@Cacheable(value = "getProjectById",keyGenerator="simpleKeyGenerator")
public ApiResponse getProjectById(@PathVariable Integer id){
Project project = projectService.getById(id);
return ApiResponse.ok(project);
}
@PostMapping("/freeze/{id}")
@ApiOperation("冻结项目")
public ApiResponse freezeProject(@PathVariable Integer id){
Project project = projectService.getById(id);
if(project==null){
return ApiResponse.selfError(ReturnCode.PROJECT_NOT_EXITST);
}
project.setStatus(project.getStatus()==1 ? 0 : 1);
projectService.updateById(project);
return ApiResponse.ok();
}
@PostMapping("/add")
@ApiOperation("添加收费项目(需要权限:[pro_add])")
@ApiImplicitParam(name = "project",value = "收费项目的json对象")
public ApiResponse insertProject(@RequestBody Project project){
if(project.getPercentage()==null || project.getPrice()==null ||project.getName()==null){
return ApiResponse.selfError(ReturnCode.NEED_PARAM);
}
boolean res=projectService.save(project);
project.setStatus(1);
return res ? ApiResponse.created():ApiResponse.serverError();
}
@PutMapping("/edit")
@ApiOperation("修改收费项目(需要权限:[pro_edit])")
@ApiImplicitParam(name = "project",value = "收费项目的json对象")
public ApiResponse updateProject(@RequestBody Project project){
if(project.getId()==null || project.getPercentage()==null || project.getPrice()==null ||project.getName()==null){
return ApiResponse.selfError(ReturnCode.NEED_PARAM);
}
if(projectService.getById(project.getId())==null){
return ApiResponse.selfError(ReturnCode.PROJECT_NOT_EXITST);
}
boolean res=projectService.updateById(project);
return res ? ApiResponse.ok():ApiResponse.serverError();
}
@DeleteMapping("/del/{id}")
@ApiOperation("删除收费项目(需要权限:[pro_del])")
@ApiImplicitParam(name = "id",value = "收费项目的id")
public ApiResponse deleteProject(@PathVariable Integer id){
boolean res=true;
QueryWrapper<RecordBusiness> queryWapper=new QueryWrapper<>();
queryWapper.and(wapper->wapper.in("type",2))
.and(wapper->wapper.in("thing_id",id));
if(recordBusinessService.list(queryWapper).size()!=0){
return ApiResponse.selfError(ReturnCode.DELETE_FALI_Foreign_KEY);
}
try{
res=projectService.removeById(id);
}catch (Exception e){
log.info(this.getClass().getName()+"deleteProject:error");
return ApiResponse.selfError(ReturnCode.DELETE_FALI_Foreign_KEY);
}
return res ? ApiResponse.ok():ApiResponse.serverError();
}
}
|
9233ecac69d655af428dc4a95784d0d1eacb9f85 | 875 | java | Java | src/gof/behavioural/iterator/CountIterator.java | tushar2708/design_patterns | 6a85066f5a190cb93c1808497b3aeb1a472e4ca3 | [
"MIT"
] | null | null | null | src/gof/behavioural/iterator/CountIterator.java | tushar2708/design_patterns | 6a85066f5a190cb93c1808497b3aeb1a472e4ca3 | [
"MIT"
] | null | null | null | src/gof/behavioural/iterator/CountIterator.java | tushar2708/design_patterns | 6a85066f5a190cb93c1808497b3aeb1a472e4ca3 | [
"MIT"
] | null | null | null | 23.026316 | 71 | 0.620571 | 996,750 | package gof.behavioural.iterator;
public class CountIterator implements java.util.Enumeration
{
public int x;
public CountIterator(){
}
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
@Override
public boolean hasMoreElements() {
if(x<10){
return true;
}
return false;
}
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @throws NoSuchElementException if no more elements exist.
*/
@Override
public Object nextElement() {
return x++;
}
}
|
9233ed84cb5ccfbb25d1e26ad737461fc8b6f6ea | 825 | java | Java | jsflab/src/main/java/com/pilotojsf/managedbean/dia4/facelets/CarroModel.java | antoniolazaro/jsflabs | d39f709c715eb38b9607004181218f26d9db5d61 | [
"Apache-2.0"
] | 1 | 2016-10-31T18:50:09.000Z | 2016-10-31T18:50:09.000Z | jsflab/src/main/java/com/pilotojsf/managedbean/dia4/facelets/CarroModel.java | antoniolazaro/jsflabs | d39f709c715eb38b9607004181218f26d9db5d61 | [
"Apache-2.0"
] | null | null | null | jsflab/src/main/java/com/pilotojsf/managedbean/dia4/facelets/CarroModel.java | antoniolazaro/jsflabs | d39f709c715eb38b9607004181218f26d9db5d61 | [
"Apache-2.0"
] | null | null | null | 17.553191 | 48 | 0.707879 | 996,751 | package com.pilotojsf.managedbean.dia4.facelets;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class CarroModel implements Serializable
{
private String nome;
private String marca;
private List<String> modelos;
public CarroModel() {
// TODO Auto-generated constructor stub
}
public CarroModel(String nome, String marca) {
super();
this.nome = nome;
this.marca = marca;
this.modelos = new ArrayList<>();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public List<String> getModelos() {
return modelos;
}
public void setModelos(List<String> modelos) {
this.modelos = modelos;
}
}
|
9233eee223b93abbff8951fd923b86321fb52dec | 17,655 | java | Java | src/main/java/org/apache/hadoop/hbase/zookeeper/SchemaChangeTracker.java | whitepages/hbase | 0b2bdc5dc4a090297f747a1a47715456a305afe4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/hbase/zookeeper/SchemaChangeTracker.java | whitepages/hbase | 0b2bdc5dc4a090297f747a1a47715456a305afe4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/hbase/zookeeper/SchemaChangeTracker.java | whitepages/hbase | 0b2bdc5dc4a090297f747a1a47715456a305afe4 | [
"Apache-2.0"
] | null | null | null | 37.012579 | 101 | 0.664174 | 996,752 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.zookeeper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.monitoring.MonitoredTask;
import org.apache.hadoop.hbase.monitoring.TaskMonitor;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.RegionServerServices;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Writables;
import org.apache.zookeeper.KeeperException;
import org.apache.hadoop.hbase.util.Writables;
import org.apache.hadoop.io.Writable;
import java.io.*;
import java.util.List;
/**
* Region server schema change tracker. RS uses this tracker to keep track of
* alter schema requests from master and updates the status once the schema change
* is complete.
*/
public class SchemaChangeTracker extends ZooKeeperNodeTracker {
public static final Log LOG = LogFactory.getLog(SchemaChangeTracker.class);
private RegionServerServices regionServer = null;
private volatile int sleepTimeMillis = 0;
/**
* Constructs a new ZK node tracker.
* <p/>
* <p>After construction, use {@link #start} to kick off tracking.
*
* @param watcher
* @param node
* @param abortable
*/
public SchemaChangeTracker(ZooKeeperWatcher watcher,
Abortable abortable,
RegionServerServices regionServer) {
super(watcher, watcher.schemaZNode, abortable);
this.regionServer = regionServer;
}
@Override
public void start() {
try {
watcher.registerListener(this);
ZKUtil.listChildrenAndWatchThem(watcher, node);
// Clean-up old in-process schema changes for this RS now?
} catch (KeeperException e) {
LOG.error("RegionServer SchemaChangeTracker startup failed with " +
"KeeperException.", e);
}
}
/**
* This event will be triggered whenever new schema change request is processed by the
* master. The path will be of the format /hbase/schema/<table name>
* @param path full path of the node whose children have changed
*/
@Override
public void nodeChildrenChanged(String path) {
LOG.debug("NodeChildrenChanged. Path = " + path);
if (path.equals(watcher.schemaZNode)) {
try {
List<String> tables =
ZKUtil.listChildrenAndWatchThem(watcher, watcher.schemaZNode);
LOG.debug("RS.SchemaChangeTracker: " +
"Current list of tables with schema change = " + tables);
if (tables != null) {
handleSchemaChange(tables);
} else {
LOG.error("No tables found for schema change event." +
" Skipping instant schema refresh");
}
} catch (KeeperException ke) {
String errmsg = "KeeperException while handling nodeChildrenChanged for path = "
+ path + " Cause = " + ke.getCause();
LOG.error(errmsg, ke);
TaskMonitor.get().createStatus(errmsg);
}
}
}
private void handleSchemaChange(List<String> tables) {
for (String tableName : tables) {
if (tableName != null) {
LOG.debug("Processing schema change with status for table = " + tableName);
handleSchemaChange(tableName);
}
}
}
private void handleSchemaChange(String tableName) {
int refreshedRegionsCount = 0, onlineRegionsCount = 0;
MonitoredTask status = null;
try {
List<HRegion> onlineRegions =
regionServer.getOnlineRegions(Bytes.toBytes(tableName));
if (onlineRegions != null && !onlineRegions.isEmpty()) {
status = TaskMonitor.get().createStatus("Region server "
+ regionServer.getServerName().getServerName()
+ " handling schema change for table = " + tableName
+ " number of online regions = " + onlineRegions.size());
onlineRegionsCount = onlineRegions.size();
createStateNode(tableName, onlineRegions.size());
for (HRegion hRegion : onlineRegions) {
regionServer.refreshRegion(hRegion);
refreshedRegionsCount ++;
}
SchemaAlterStatus alterStatus = getSchemaAlterStatus(tableName);
alterStatus.update(SchemaAlterStatus.AlterState.SUCCESS, refreshedRegionsCount);
updateSchemaChangeStatus(tableName, alterStatus);
String msg = "Refresh schema completed for table name = " + tableName
+ " server = " + regionServer.getServerName().getServerName()
+ " online Regions = " + onlineRegions.size()
+ " refreshed Regions = " + refreshedRegionsCount;
LOG.debug(msg);
status.setStatus(msg);
} else {
LOG.debug("Server " + regionServer.getServerName().getServerName()
+ " has no online regions for table = " + tableName
+ " Ignoring the schema change request");
}
} catch (IOException ioe) {
reportAndLogSchemaRefreshError(tableName, onlineRegionsCount,
refreshedRegionsCount, ioe, status);
} catch (KeeperException ke) {
reportAndLogSchemaRefreshError(tableName, onlineRegionsCount,
refreshedRegionsCount, ke, status);
}
}
private int getZKNodeVersion(String nodePath) throws KeeperException {
return ZKUtil.checkExists(this.watcher, nodePath);
}
private void reportAndLogSchemaRefreshError(String tableName,
int onlineRegionsCount,
int refreshedRegionsCount,
Throwable exception,
MonitoredTask status) {
try {
String errmsg =
" Region Server " + regionServer.getServerName().getServerName()
+ " failed during schema change process. Cause = "
+ exception.getCause()
+ " Number of onlineRegions = " + onlineRegionsCount
+ " Processed regions = " + refreshedRegionsCount;
SchemaAlterStatus alterStatus = getSchemaAlterStatus(tableName);
alterStatus.update(SchemaAlterStatus.AlterState.FAILURE,
refreshedRegionsCount, errmsg);
String nodePath = getSchemaChangeNodePathForTableAndServer(tableName,
regionServer.getServerName().getServerName());
ZKUtil.updateExistingNodeData(this.watcher, nodePath,
Writables.getBytes(alterStatus), getZKNodeVersion(nodePath));
LOG.info("reportAndLogSchemaRefreshError() " +
" Updated child ZKNode with SchemaAlterStatus = "
+ alterStatus + " for table = " + tableName);
if (status == null) {
status = TaskMonitor.get().createStatus(errmsg);
} else {
status.setStatus(errmsg);
}
} catch (KeeperException e) {
// Retry ?
String errmsg = "KeeperException while updating the schema change node with "
+ "error status for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Cause = " + e.getCause();
LOG.error(errmsg, e);
TaskMonitor.get().createStatus(errmsg);
} catch(IOException ioe) {
// retry ??
String errmsg = "IOException while updating the schema change node with "
+ "server name for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Cause = " + ioe.getCause();
TaskMonitor.get().createStatus(errmsg);
LOG.error(errmsg, ioe);
}
}
private void createStateNode(String tableName, int numberOfOnlineRegions)
throws IOException {
SchemaAlterStatus sas =
new SchemaAlterStatus(regionServer.getServerName().getServerName(),
numberOfOnlineRegions);
LOG.debug("Creating Schema Alter State node = " + sas);
try {
ZKUtil.createSetData(this.watcher,
getSchemaChangeNodePathForTableAndServer(tableName,
regionServer.getServerName().getServerName()),
Writables.getBytes(sas));
} catch (KeeperException ke) {
String errmsg = "KeeperException while creating the schema change node with "
+ "server name for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Message = " + ke.getCause();
LOG.error(errmsg, ke);
TaskMonitor.get().createStatus(errmsg);
}
}
private SchemaAlterStatus getSchemaAlterStatus(String tableName)
throws KeeperException, IOException {
byte[] statusBytes = ZKUtil.getData(this.watcher,
getSchemaChangeNodePathForTableAndServer(tableName,
regionServer.getServerName().getServerName()));
if (statusBytes == null || statusBytes.length <= 0) {
return null;
}
SchemaAlterStatus sas = new SchemaAlterStatus();
Writables.getWritable(statusBytes, sas);
return sas;
}
private void updateSchemaChangeStatus(String tableName,
SchemaAlterStatus schemaAlterStatus)
throws KeeperException, IOException {
try {
if(sleepTimeMillis > 0) {
try {
LOG.debug("SchemaChangeTracker sleeping for "
+ sleepTimeMillis);
Thread.sleep(sleepTimeMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
ZKUtil.updateExistingNodeData(this.watcher,
getSchemaChangeNodePathForTableAndServer(tableName,
regionServer.getServerName().getServerName()),
Writables.getBytes(schemaAlterStatus), -1);
String msg = "Schema change tracker completed for table = " + tableName
+ " status = " + schemaAlterStatus;
LOG.debug(msg);
TaskMonitor.get().createStatus(msg);
} catch (KeeperException.NoNodeException e) {
String errmsg = "KeeperException.NoNodeException while updating the schema "
+ "change node with server name for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Cause = " + e.getCause();
TaskMonitor.get().createStatus(errmsg);
LOG.error(errmsg, e);
} catch (KeeperException e) {
// Retry ?
String errmsg = "KeeperException while updating the schema change node with "
+ "server name for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Cause = " + e.getCause();
LOG.error(errmsg, e);
TaskMonitor.get().createStatus(errmsg);
} catch(IOException ioe) {
String errmsg = "IOException while updating the schema change node with "
+ "server name for table = "
+ tableName + " server = "
+ regionServer.getServerName().getServerName()
+ " Cause = " + ioe.getCause();
LOG.error(errmsg, ioe);
TaskMonitor.get().createStatus(errmsg);
}
}
private String getSchemaChangeNodePathForTable(String tableName) {
return ZKUtil.joinZNode(watcher.schemaZNode, tableName);
}
private String getSchemaChangeNodePathForTableAndServer(
String tableName, String regionServerName) {
return ZKUtil.joinZNode(getSchemaChangeNodePathForTable(tableName),
regionServerName);
}
public int getSleepTimeMillis() {
return sleepTimeMillis;
}
/**
* Set a sleep time in millis before this RS can update it's progress status.
* Used only for test cases to test complex test scenarios such as RS failures and
* RS exemption handling.
* @param sleepTimeMillis
*/
public void setSleepTimeMillis(int sleepTimeMillis) {
this.sleepTimeMillis = sleepTimeMillis;
}
/**
* Check whether there are any schema change requests that are in progress now for the given table.
* We simply assume that a schema change is in progress if we see a ZK schema node this
* any table. We may revisit for fine grained checks such as check the current alter status
* et al, but it is not required now.
* @return
*/
public boolean isSchemaChangeInProgress(String tableName) {
try {
List<String> schemaChanges = ZKUtil.listChildrenAndWatchThem(this.watcher,
watcher.schemaZNode);
if (schemaChanges != null) {
for (String alterTableName : schemaChanges) {
if (alterTableName.equals(tableName)) {
return true;
}
}
return false;
}
} catch (KeeperException ke) {
LOG.debug("isSchemaChangeInProgress. " +
"KeeperException while getting current schema change progress.");
return false;
}
return false;
}
/**
* Holds the current alter state for a table. Alter state includes the
* current alter status (INPROCESS, FAILURE, SUCCESS, or IGNORED, current RS
* host name, timestamp of alter request, number of online regions this RS has for
* the given table, number of processed regions and an errorCause in case
* if the RS failed during the schema change process.
*
* RS keeps track of schema change requests per table using the alter status and
* periodically updates the alter status based on schema change status.
*/
public static class SchemaAlterStatus implements Writable {
public enum AlterState {
INPROCESS, // Inprocess alter
SUCCESS, // completed alter
FAILURE, // failure alter
IGNORED // Ignore the alter processing.
}
private AlterState currentAlterStatus;
// TimeStamp
private long stamp;
private int numberOfOnlineRegions;
private String errorCause = " ";
private String hostName;
private int numberOfRegionsProcessed = 0;
public SchemaAlterStatus() {
}
public SchemaAlterStatus(String hostName, int numberOfOnlineRegions) {
this.numberOfOnlineRegions = numberOfOnlineRegions;
this.stamp = System.currentTimeMillis();
this.currentAlterStatus = AlterState.INPROCESS;
//this.rsToProcess = activeHosts;
this.hostName = hostName;
}
public AlterState getCurrentAlterStatus() {
return currentAlterStatus;
}
public void setCurrentAlterStatus(AlterState currentAlterStatus) {
this.currentAlterStatus = currentAlterStatus;
}
public int getNumberOfOnlineRegions() {
return numberOfOnlineRegions;
}
public void setNumberOfOnlineRegions(int numberOfRegions) {
this.numberOfOnlineRegions = numberOfRegions;
}
public int getNumberOfRegionsProcessed() {
return numberOfRegionsProcessed;
}
public void setNumberOfRegionsProcessed(int numberOfRegionsProcessed) {
this.numberOfRegionsProcessed = numberOfRegionsProcessed;
}
public String getErrorCause() {
return errorCause;
}
public void setErrorCause(String errorCause) {
this.errorCause = errorCause;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public void update(AlterState state, int numberOfRegions, String errorCause) {
this.currentAlterStatus = state;
this.numberOfRegionsProcessed = numberOfRegions;
this.errorCause = errorCause;
}
public void update(AlterState state, int numberOfRegions) {
this.currentAlterStatus = state;
this.numberOfRegionsProcessed = numberOfRegions;
}
public void update(AlterState state) {
this.currentAlterStatus = state;
}
public void update(SchemaAlterStatus status) {
this.currentAlterStatus = status.getCurrentAlterStatus();
this.numberOfRegionsProcessed = status.getNumberOfRegionsProcessed();
this.errorCause = status.getErrorCause();
}
@Override
public void readFields(DataInput in) throws IOException {
currentAlterStatus = AlterState.valueOf(in.readUTF());
stamp = in.readLong();
numberOfOnlineRegions = in.readInt();
hostName = Bytes.toString(Bytes.readByteArray(in));
numberOfRegionsProcessed = in.readInt();
errorCause = Bytes.toString(Bytes.readByteArray(in));
}
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(currentAlterStatus.name());
out.writeLong(stamp);
out.writeInt(numberOfOnlineRegions);
Bytes.writeByteArray(out, Bytes.toBytes(hostName));
out.writeInt(numberOfRegionsProcessed);
Bytes.writeByteArray(out, Bytes.toBytes(errorCause));
}
@Override
public String toString() {
return
" state= " + currentAlterStatus
+ ", ts= " + stamp
+ ", number of online regions = " + numberOfOnlineRegions
+ ", host= " + hostName + " processed regions = " + numberOfRegionsProcessed
+ ", errorCause = " + errorCause;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.